hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
c56b9b06ae502fce07714117b0076c69d2698a13
2,500
package com.acme.model; import com.google.common.collect.*; import net.nullschool.grains.*; import org.joda.time.*; import java.util.*; /** * 2013-05-09<p/> * * This class holds examples of TypePolicy objects customized with immutable types available from common open source * libraries, allowing the Maven grains-plugin to use these types during code generation. For illustrative purposes, * there are two customized type policies defined: * <ol> * <li>STANDARD_JODA: adds immutable JodaTime objects</li> * <li>STANDARD_JODA_GUAVA: adds immutable JodaTime objects and defines mappings for Guava immutable * collections.</li> * </ol> * * The custom type policy to use during code generation is defined by the grains-plugin POM configuration. For example: * <pre> * &lt;configuration&gt; * &lt;typePolicy&gt;com.acme.model.CustomTypePolicies.STANDARD_JODA&lt;/typePolicy&gt; * &lt;/configuration&gt; * </pre> * * Changing the type policy configuration from STANDARD_JODA to STANDARD_JODA_GUAVA will cause the generated code to * use Guava's immutable collections rather than the const collections natively available from the Grains framework. * Make sure to update the {@link com.acme.Sample} class as well to use these different collection types. * * @author Cameron Beccario */ public class CustomTypePolicies { /** * A standard policy that supports JodaTime. */ public static final ConfigurableTypePolicy STANDARD_JODA = ConfigurableTypePolicy.STANDARD .withImmutableTypes(LocalDate.class, DateTime.class); /** * A standard policy that supports JodaTime and Guava immutable collections. */ public static final ConfigurableTypePolicy STANDARD_JODA_GUAVA = ConfigurableTypePolicy.STANDARD .withImmutableTypes(LocalDate.class, DateTime.class) .withImmutableMapping(Set.class, ImmutableSet.class) .withImmutableMapping(Map.class, ImmutableMap.class) .withImmutableMapping(List.class, ImmutableList.class) .withImmutableMapping(SortedSet.class, ImmutableSortedSet.class) .withImmutableMapping(SortedMap.class, ImmutableSortedMap.class) .withImmutableMapping(Collection.class, ImmutableCollection.class) .withImmutableMapping(Multimap.class, ImmutableMultimap.class) .withImmutableMapping(SetMultimap.class, ImmutableSetMultimap.class) .withImmutableMapping(ListMultimap.class, ImmutableListMultimap.class); }
43.103448
119
0.7488
52a5722225e71dbdc0123f25d117efb277c78ecc
3,029
/** * Copyright 2021 Tianmian Tech. 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.welab.wefe.serving.service.api.setting; import com.welab.wefe.common.exception.StatusCodeWithException; import com.welab.wefe.common.fieldvalidate.annotation.Check; import com.welab.wefe.common.web.api.base.AbstractNoneOutputApi; import com.welab.wefe.common.web.api.base.Api; import com.welab.wefe.common.web.dto.AbstractApiInput; import com.welab.wefe.common.web.dto.ApiResult; import com.welab.wefe.serving.service.service.GlobalSettingService; import org.springframework.beans.factory.annotation.Autowired; /** * @author Zane */ @Api(path = "global_setting/initialize", name = "Initialize system", desc = "Initialize the system and set global parameters.") public class InitializeApi extends AbstractNoneOutputApi<InitializeApi.Input> { @Autowired private GlobalSettingService globalSettingService; @Override protected ApiResult<?> handler(Input input) throws StatusCodeWithException { globalSettingService.initialize(input); return success(); } public static class Input extends AbstractApiInput { @Check(name = "联邦成员id") private String memberId; @Check( name = "联邦成员名称", require = true, messageOnEmpty = "请输入成员名称", regex = "^[\\u4e00-\\u9fa5()0-9a-zA-Z ]{3,12}$", messageOnInvalid = "成员名称仅支持中文、英文与数字,且长度为 3 - 12。" ) private String memberName; @Check(name = "公钥") private String rsaPublicKey; @Check(name = "私钥") private String rsaPrivateKey; //region getter/setter public String getMemberId() { return memberId; } public void setMemberId(String memberId) { this.memberId = memberId; } public String getMemberName() { return memberName; } public void setMemberName(String memberName) { this.memberName = memberName; } public String getRsaPublicKey() { return rsaPublicKey; } public void setRsaPublicKey(String rsaPublicKey) { this.rsaPublicKey = rsaPublicKey; } public String getRsaPrivateKey() { return rsaPrivateKey; } public void setRsaPrivateKey(String rsaPrivateKey) { this.rsaPrivateKey = rsaPrivateKey; } //endregion } }
29.407767
127
0.659624
74caceae07c969569fcad17454823de357f916fb
41,878
/* * Copyright (C) 2018 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 android.hardware.biometrics; import static android.Manifest.permission.USE_BIOMETRIC; import static android.Manifest.permission.USE_BIOMETRIC_INTERNAL; import static android.hardware.biometrics.BiometricManager.Authenticators; import android.annotation.CallbackExecutor; import android.annotation.IntDef; import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.RequiresPermission; import android.content.Context; import android.content.DialogInterface; import android.hardware.face.FaceManager; import android.hardware.fingerprint.FingerprintManager; import android.os.Binder; import android.os.Bundle; import android.os.CancellationSignal; import android.os.IBinder; import android.os.RemoteException; import android.os.ServiceManager; import android.security.identity.IdentityCredential; import android.security.keystore.KeyGenParameterSpec; import android.security.keystore.KeyProperties; import android.text.TextUtils; import android.util.Log; import com.android.internal.R; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.security.Signature; import java.util.concurrent.Executor; import javax.crypto.Cipher; import javax.crypto.Mac; /** * A class that manages a system-provided biometric dialog. */ public class BiometricPrompt implements BiometricAuthenticator, BiometricConstants { private static final String TAG = "BiometricPrompt"; /** * @hide */ public static final String KEY_TITLE = "title"; /** * @hide */ @RequiresPermission(USE_BIOMETRIC_INTERNAL) public static final String KEY_USE_DEFAULT_TITLE = "use_default_title"; /** * @hide */ public static final String KEY_SUBTITLE = "subtitle"; /** * @hide */ public static final String KEY_DESCRIPTION = "description"; /** * @hide */ @RequiresPermission(USE_BIOMETRIC_INTERNAL) public static final String KEY_DEVICE_CREDENTIAL_TITLE = "device_credential_title"; /** * @hide */ @RequiresPermission(USE_BIOMETRIC_INTERNAL) public static final String KEY_DEVICE_CREDENTIAL_SUBTITLE = "device_credential_subtitle"; /** * @hide */ @RequiresPermission(USE_BIOMETRIC_INTERNAL) public static final String KEY_DEVICE_CREDENTIAL_DESCRIPTION = "device_credential_description"; /** * @hide */ public static final String KEY_NEGATIVE_TEXT = "negative_text"; /** * @hide */ public static final String KEY_REQUIRE_CONFIRMATION = "require_confirmation"; /** * This is deprecated. Internally we should use {@link #KEY_AUTHENTICATORS_ALLOWED} * @hide */ public static final String KEY_ALLOW_DEVICE_CREDENTIAL = "allow_device_credential"; /** * If this key is set, we will ignore {@link #KEY_ALLOW_DEVICE_CREDENTIAL} * @hide */ public static final String KEY_AUTHENTICATORS_ALLOWED = "authenticators_allowed"; /** * If this is set, check the Device Policy Manager for allowed biometrics. * @hide */ @RequiresPermission(USE_BIOMETRIC_INTERNAL) public static final String EXTRA_DISALLOW_BIOMETRICS_IF_POLICY_EXISTS = "check_dpm"; /** * Request to receive system events, such as back gesture/button. See * {@link AuthenticationCallback#onSystemEvent(int)} * @hide */ @RequiresPermission(USE_BIOMETRIC_INTERNAL) public static final String KEY_RECEIVE_SYSTEM_EVENTS = "receive_system_events"; /** * Error/help message will show for this amount of time. * For error messages, the dialog will also be dismissed after this amount of time. * Error messages will be propagated back to the application via AuthenticationCallback * after this amount of time. * @hide */ public static final int HIDE_DIALOG_DELAY = 2000; // ms /** * @hide */ public static final int DISMISSED_REASON_BIOMETRIC_CONFIRMED = 1; /** * Dialog is done animating away after user clicked on the button set via * {@link BiometricPrompt.Builder#setNegativeButton(CharSequence, Executor, * DialogInterface.OnClickListener)}. * @hide */ public static final int DISMISSED_REASON_NEGATIVE = 2; /** * @hide */ public static final int DISMISSED_REASON_USER_CANCEL = 3; /** * Authenticated, confirmation not required. Dialog animated away. * @hide */ public static final int DISMISSED_REASON_BIOMETRIC_CONFIRM_NOT_REQUIRED = 4; /** * Error message shown on SystemUI. When BiometricService receives this, the UI is already * gone. * @hide */ public static final int DISMISSED_REASON_ERROR = 5; /** * Dialog dismissal requested by BiometricService. * @hide */ public static final int DISMISSED_REASON_SERVER_REQUESTED = 6; /** * @hide */ public static final int DISMISSED_REASON_CREDENTIAL_CONFIRMED = 7; private static class ButtonInfo { Executor executor; DialogInterface.OnClickListener listener; ButtonInfo(Executor ex, DialogInterface.OnClickListener l) { executor = ex; listener = l; } } /** * A builder that collects arguments to be shown on the system-provided biometric dialog. */ public static class Builder { private final Bundle mBundle; private ButtonInfo mPositiveButtonInfo; private ButtonInfo mNegativeButtonInfo; private Context mContext; /** * Creates a builder for a {@link BiometricPrompt} dialog. * @param context The {@link Context} that will be used to build the prompt. */ public Builder(Context context) { mBundle = new Bundle(); mContext = context; } /** * Required: Sets the title that will be shown on the prompt. * @param title The title to display. * @return This builder. */ @NonNull public Builder setTitle(@NonNull CharSequence title) { mBundle.putCharSequence(KEY_TITLE, title); return this; } /** * Shows a default, modality-specific title for the prompt if the title would otherwise be * null or empty. Currently for internal use only. * @return This builder. * @hide */ @RequiresPermission(USE_BIOMETRIC_INTERNAL) @NonNull public Builder setUseDefaultTitle() { mBundle.putBoolean(KEY_USE_DEFAULT_TITLE, true); return this; } /** * Optional: Sets a subtitle that will be shown on the prompt. * @param subtitle The subtitle to display. * @return This builder. */ @NonNull public Builder setSubtitle(@NonNull CharSequence subtitle) { mBundle.putCharSequence(KEY_SUBTITLE, subtitle); return this; } /** * Optional: Sets a description that will be shown on the prompt. * @param description The description to display. * @return This builder. */ @NonNull public Builder setDescription(@NonNull CharSequence description) { mBundle.putCharSequence(KEY_DESCRIPTION, description); return this; } /** * Sets an optional title, subtitle, and/or description that will override other text when * the user is authenticating with PIN/pattern/password. Currently for internal use only. * @return This builder. * @hide */ @RequiresPermission(USE_BIOMETRIC_INTERNAL) @NonNull public Builder setTextForDeviceCredential( @Nullable CharSequence title, @Nullable CharSequence subtitle, @Nullable CharSequence description) { if (title != null) { mBundle.putCharSequence(KEY_DEVICE_CREDENTIAL_TITLE, title); } if (subtitle != null) { mBundle.putCharSequence(KEY_DEVICE_CREDENTIAL_SUBTITLE, subtitle); } if (description != null) { mBundle.putCharSequence(KEY_DEVICE_CREDENTIAL_DESCRIPTION, description); } return this; } /** * Required: Sets the text, executor, and click listener for the negative button on the * prompt. This is typically a cancel button, but may be also used to show an alternative * method for authentication, such as a screen that asks for a backup password. * * <p>Note that this setting is not required, and in fact is explicitly disallowed, if * device credential authentication is enabled via {@link #setAllowedAuthenticators(int)} or * {@link #setDeviceCredentialAllowed(boolean)}. * * @param text Text to be shown on the negative button for the prompt. * @param executor Executor that will be used to run the on click callback. * @param listener Listener containing a callback to be run when the button is pressed. * @return This builder. */ @NonNull public Builder setNegativeButton(@NonNull CharSequence text, @NonNull @CallbackExecutor Executor executor, @NonNull DialogInterface.OnClickListener listener) { if (TextUtils.isEmpty(text)) { throw new IllegalArgumentException("Text must be set and non-empty"); } if (executor == null) { throw new IllegalArgumentException("Executor must not be null"); } if (listener == null) { throw new IllegalArgumentException("Listener must not be null"); } mBundle.putCharSequence(KEY_NEGATIVE_TEXT, text); mNegativeButtonInfo = new ButtonInfo(executor, listener); return this; } /** * Optional: Sets a hint to the system for whether to require user confirmation after * authentication. For example, implicit modalities like face and iris are passive, meaning * they don't require an explicit user action to complete authentication. If set to true, * these modalities should require the user to take some action (e.g. press a button) * before {@link AuthenticationCallback#onAuthenticationSucceeded(AuthenticationResult)} is * called. Defaults to true. * * <p>A typical use case for not requiring confirmation would be for low-risk transactions, * such as re-authenticating a recently authenticated application. A typical use case for * requiring confirmation would be for authorizing a purchase. * * <p>Note that this just passes a hint to the system, which the system may then ignore. For * example, a value of false may be ignored if the user has disabled implicit authentication * in Settings, or if it does not apply to a particular modality (e.g. fingerprint). * * @param requireConfirmation true if explicit user confirmation should be required, or * false otherwise. * @return This builder. */ @NonNull public Builder setConfirmationRequired(boolean requireConfirmation) { mBundle.putBoolean(KEY_REQUIRE_CONFIRMATION, requireConfirmation); return this; } /** * Optional: If enabled, the user will be given the option to authenticate with their device * PIN, pattern, or password. Developers should first check {@link * BiometricManager#canAuthenticate(int)} for {@link Authenticators#DEVICE_CREDENTIAL} * before enabling. If the device is not secured with a credential, * {@link AuthenticationCallback#onAuthenticationError(int, CharSequence)} will be invoked * with {@link BiometricPrompt#BIOMETRIC_ERROR_NO_DEVICE_CREDENTIAL}. Defaults to false. * * <p>Note that enabling this option replaces the negative button on the prompt with one * that allows the user to authenticate with their device credential, making it an error to * call {@link #setNegativeButton(CharSequence, Executor, DialogInterface.OnClickListener)}. * * @param allowed true if the prompt should fall back to asking for the user's device * credential (PIN/pattern/password), or false otherwise. * @return This builder. * * @deprecated Replaced by {@link #setAllowedAuthenticators(int)}. */ @Deprecated @NonNull public Builder setDeviceCredentialAllowed(boolean allowed) { mBundle.putBoolean(KEY_ALLOW_DEVICE_CREDENTIAL, allowed); return this; } /** * Optional: Specifies the type(s) of authenticators that may be invoked by * {@link BiometricPrompt} to authenticate the user. Available authenticator types are * defined in {@link Authenticators} and can be combined via bitwise OR. Defaults to: * <ul> * <li>{@link Authenticators#BIOMETRIC_WEAK} for non-crypto authentication, or</li> * <li>{@link Authenticators#BIOMETRIC_STRONG} for crypto-based authentication.</li> * </ul> * * <p>If this method is used and no authenticator of any of the specified types is available * at the time <code>BiometricPrompt#authenticate(...)</code> is called, authentication will * be canceled and {@link AuthenticationCallback#onAuthenticationError(int, CharSequence)} * will be invoked with an appropriate error code. * * <p>This method should be preferred over {@link #setDeviceCredentialAllowed(boolean)} and * overrides the latter if both are used. Using this method to enable device credential * authentication (with {@link Authenticators#DEVICE_CREDENTIAL}) will replace the negative * button on the prompt, making it an error to also call * {@link #setNegativeButton(CharSequence, Executor, DialogInterface.OnClickListener)}. * * <p>If unlocking cryptographic operation(s), it is the application's responsibility to * request authentication with the proper set of authenticators (e.g. match the * authenticators specified during key generation). * * @see KeyGenParameterSpec.Builder#setUserAuthenticationParameters(int, int) * @see KeyProperties#AUTH_BIOMETRIC_STRONG * @see KeyProperties#AUTH_DEVICE_CREDENTIAL * * @param authenticators A bit field representing all valid authenticator types that may be * invoked by the prompt. * @return This builder. */ @NonNull public Builder setAllowedAuthenticators(@Authenticators.Types int authenticators) { mBundle.putInt(KEY_AUTHENTICATORS_ALLOWED, authenticators); return this; } /** * If set check the Device Policy Manager for disabled biometrics. * * @param checkDevicePolicyManager * @return This builder. * @hide */ @NonNull public Builder setDisallowBiometricsIfPolicyExists(boolean checkDevicePolicyManager) { mBundle.putBoolean(EXTRA_DISALLOW_BIOMETRICS_IF_POLICY_EXISTS, checkDevicePolicyManager); return this; } /** * If set, receive internal events via {@link AuthenticationCallback#onSystemEvent(int)} * @param set * @return This builder. * @hide */ @NonNull public Builder setReceiveSystemEvents(boolean set) { mBundle.putBoolean(KEY_RECEIVE_SYSTEM_EVENTS, set); return this; } /** * Creates a {@link BiometricPrompt}. * * @return An instance of {@link BiometricPrompt}. * * @throws IllegalArgumentException If any required fields are unset, or if given any * invalid combination of field values. */ @NonNull public BiometricPrompt build() { final CharSequence title = mBundle.getCharSequence(KEY_TITLE); final CharSequence negative = mBundle.getCharSequence(KEY_NEGATIVE_TEXT); final boolean useDefaultTitle = mBundle.getBoolean(KEY_USE_DEFAULT_TITLE, false); final boolean deviceCredentialAllowed = mBundle.getBoolean(KEY_ALLOW_DEVICE_CREDENTIAL); final @Authenticators.Types int authenticators = mBundle.getInt(KEY_AUTHENTICATORS_ALLOWED, 0); final boolean willShowDeviceCredentialButton = deviceCredentialAllowed || (authenticators & Authenticators.DEVICE_CREDENTIAL) != 0; if (TextUtils.isEmpty(title) && !useDefaultTitle) { throw new IllegalArgumentException("Title must be set and non-empty"); } else if (TextUtils.isEmpty(negative) && !willShowDeviceCredentialButton) { throw new IllegalArgumentException("Negative text must be set and non-empty"); } else if (!TextUtils.isEmpty(negative) && willShowDeviceCredentialButton) { throw new IllegalArgumentException("Can't have both negative button behavior" + " and device credential enabled"); } return new BiometricPrompt(mContext, mBundle, mPositiveButtonInfo, mNegativeButtonInfo); } } private class OnAuthenticationCancelListener implements CancellationSignal.OnCancelListener { @Override public void onCancel() { cancelAuthentication(); } } private final IBinder mToken = new Binder(); private final Context mContext; private final IAuthService mService; private final Bundle mBundle; private final ButtonInfo mPositiveButtonInfo; private final ButtonInfo mNegativeButtonInfo; private CryptoObject mCryptoObject; private Executor mExecutor; private AuthenticationCallback mAuthenticationCallback; private final IBiometricServiceReceiver mBiometricServiceReceiver = new IBiometricServiceReceiver.Stub() { @Override public void onAuthenticationSucceeded(@AuthenticationResultType int authenticationType) throws RemoteException { mExecutor.execute(() -> { final AuthenticationResult result = new AuthenticationResult(mCryptoObject, authenticationType); mAuthenticationCallback.onAuthenticationSucceeded(result); }); } @Override public void onAuthenticationFailed() throws RemoteException { mExecutor.execute(() -> { mAuthenticationCallback.onAuthenticationFailed(); }); } @Override public void onError(int modality, int error, int vendorCode) throws RemoteException { mExecutor.execute(() -> { String errorMessage; switch (modality) { case TYPE_FACE: errorMessage = FaceManager.getErrorString(mContext, error, vendorCode); break; case TYPE_FINGERPRINT: errorMessage = FingerprintManager.getErrorString(mContext, error, vendorCode); break; default: errorMessage = ""; } mAuthenticationCallback.onAuthenticationError(error, errorMessage); }); } @Override public void onAcquired(int acquireInfo, String message) throws RemoteException { mExecutor.execute(() -> { mAuthenticationCallback.onAuthenticationHelp(acquireInfo, message); }); } @Override public void onDialogDismissed(int reason) throws RemoteException { // Check the reason and invoke OnClickListener(s) if necessary if (reason == DISMISSED_REASON_BIOMETRIC_CONFIRMED) { mPositiveButtonInfo.executor.execute(() -> { mPositiveButtonInfo.listener.onClick(null, DialogInterface.BUTTON_POSITIVE); }); } else if (reason == DISMISSED_REASON_NEGATIVE) { mNegativeButtonInfo.executor.execute(() -> { mNegativeButtonInfo.listener.onClick(null, DialogInterface.BUTTON_NEGATIVE); }); } } @Override public void onSystemEvent(int event) throws RemoteException { mExecutor.execute(() -> { mAuthenticationCallback.onSystemEvent(event); }); } }; private BiometricPrompt(Context context, Bundle bundle, ButtonInfo positiveButtonInfo, ButtonInfo negativeButtonInfo) { mContext = context; mBundle = bundle; mPositiveButtonInfo = positiveButtonInfo; mNegativeButtonInfo = negativeButtonInfo; mService = IAuthService.Stub.asInterface( ServiceManager.getService(Context.AUTH_SERVICE)); } /** * Gets the title for the prompt, as set by {@link Builder#setTitle(CharSequence)}. * @return The title of the prompt, which is guaranteed to be non-null. */ @NonNull public CharSequence getTitle() { return mBundle.getCharSequence(KEY_TITLE, ""); } /** * Whether to use a default modality-specific title. For internal use only. * @return See {@link Builder#setUseDefaultTitle()}. * @hide */ @RequiresPermission(USE_BIOMETRIC_INTERNAL) public boolean shouldUseDefaultTitle() { return mBundle.getBoolean(KEY_USE_DEFAULT_TITLE, false); } /** * Gets the subtitle for the prompt, as set by {@link Builder#setSubtitle(CharSequence)}. * @return The subtitle for the prompt, or null if the prompt has no subtitle. */ @Nullable public CharSequence getSubtitle() { return mBundle.getCharSequence(KEY_SUBTITLE); } /** * Gets the description for the prompt, as set by {@link Builder#setDescription(CharSequence)}. * @return The description for the prompt, or null if the prompt has no description. */ @Nullable public CharSequence getDescription() { return mBundle.getCharSequence(KEY_DESCRIPTION); } /** * Gets the negative button text for the prompt, as set by * {@link Builder#setNegativeButton(CharSequence, Executor, DialogInterface.OnClickListener)}. * @return The negative button text for the prompt, or null if no negative button text was set. */ @Nullable public CharSequence getNegativeButtonText() { return mBundle.getCharSequence(KEY_NEGATIVE_TEXT); } /** * Determines if explicit user confirmation is required by the prompt, as set by * {@link Builder#setConfirmationRequired(boolean)}. * * @return true if explicit user confirmation is required, or false otherwise. */ public boolean isConfirmationRequired() { return mBundle.getBoolean(KEY_REQUIRE_CONFIRMATION, true); } /** * Gets the type(s) of authenticators that may be invoked by the prompt to authenticate the * user, as set by {@link Builder#setAllowedAuthenticators(int)}. * * @return A bit field representing the type(s) of authenticators that may be invoked by the * prompt (as defined by {@link Authenticators}), or 0 if this field was not set. */ @Nullable public int getAllowedAuthenticators() { return mBundle.getInt(KEY_AUTHENTICATORS_ALLOWED, 0); } /** * A wrapper class for the cryptographic operations supported by BiometricPrompt. * * <p>Currently the framework supports {@link Signature}, {@link Cipher}, {@link Mac}, and * {@link IdentityCredential}. * * <p>Cryptographic operations in Android can be split into two categories: auth-per-use and * time-based. This is specified during key creation via the timeout parameter of the * {@link KeyGenParameterSpec.Builder#setUserAuthenticationParameters(int, int)} API. * * <p>CryptoObjects are used to unlock auth-per-use keys via * {@link BiometricPrompt#authenticate(CryptoObject, CancellationSignal, Executor, * AuthenticationCallback)}, whereas time-based keys are unlocked for their specified duration * any time the user authenticates with the specified authenticators (e.g. unlocking keyguard). * If a time-based key is not available for use (i.e. none of the allowed authenticators have * been unlocked recently), applications can prompt the user to authenticate via * {@link BiometricPrompt#authenticate(CancellationSignal, Executor, AuthenticationCallback)} * * @see Builder#setAllowedAuthenticators(int) */ public static final class CryptoObject extends android.hardware.biometrics.CryptoObject { public CryptoObject(@NonNull Signature signature) { super(signature); } public CryptoObject(@NonNull Cipher cipher) { super(cipher); } public CryptoObject(@NonNull Mac mac) { super(mac); } public CryptoObject(@NonNull IdentityCredential credential) { super(credential); } /** * Get {@link Signature} object. * @return {@link Signature} object or null if this doesn't contain one. */ public Signature getSignature() { return super.getSignature(); } /** * Get {@link Cipher} object. * @return {@link Cipher} object or null if this doesn't contain one. */ public Cipher getCipher() { return super.getCipher(); } /** * Get {@link Mac} object. * @return {@link Mac} object or null if this doesn't contain one. */ public Mac getMac() { return super.getMac(); } /** * Get {@link IdentityCredential} object. * @return {@link IdentityCredential} object or null if this doesn't contain one. */ public @Nullable IdentityCredential getIdentityCredential() { return super.getIdentityCredential(); } } /** * Authentication type reported by {@link AuthenticationResult} when the user authenticated by * entering their device PIN, pattern, or password. */ public static final int AUTHENTICATION_RESULT_TYPE_DEVICE_CREDENTIAL = 1; /** * Authentication type reported by {@link AuthenticationResult} when the user authenticated by * presenting some form of biometric (e.g. fingerprint or face). */ public static final int AUTHENTICATION_RESULT_TYPE_BIOMETRIC = 2; /** * An {@link IntDef} representing the type of auth, as reported by {@link AuthenticationResult}. * @hide */ @Retention(RetentionPolicy.SOURCE) @IntDef({AUTHENTICATION_RESULT_TYPE_DEVICE_CREDENTIAL, AUTHENTICATION_RESULT_TYPE_BIOMETRIC}) public @interface AuthenticationResultType { } /** * Container for callback data from {@link #authenticate(CancellationSignal, Executor, * AuthenticationCallback)} and {@link #authenticate(CryptoObject, CancellationSignal, Executor, * AuthenticationCallback)}. */ public static class AuthenticationResult extends BiometricAuthenticator.AuthenticationResult { /** * Authentication result * @param crypto * @param authenticationType * @hide */ public AuthenticationResult(CryptoObject crypto, @AuthenticationResultType int authenticationType) { // Identifier and userId is not used for BiometricPrompt. super(crypto, authenticationType, null /* identifier */, 0 /* userId */); } /** * Provides the crypto object associated with this transaction. * @return The crypto object provided to {@link #authenticate(CryptoObject, * CancellationSignal, Executor, AuthenticationCallback)} */ public CryptoObject getCryptoObject() { return (CryptoObject) super.getCryptoObject(); } /** * Provides the type of authentication (e.g. device credential or biometric) that was * requested from and successfully provided by the user. * * @return An integer value representing the authentication method used. */ public @AuthenticationResultType int getAuthenticationType() { return super.getAuthenticationType(); } } /** * Callback structure provided to {@link BiometricPrompt#authenticate(CancellationSignal, * Executor, AuthenticationCallback)} or {@link BiometricPrompt#authenticate(CryptoObject, * CancellationSignal, Executor, AuthenticationCallback)}. Users must provide an implementation * of this for listening to authentication events. */ public abstract static class AuthenticationCallback extends BiometricAuthenticator.AuthenticationCallback { /** * Called when an unrecoverable error has been encountered and the operation is complete. * No further actions will be made on this object. * @param errorCode An integer identifying the error message * @param errString A human-readable error string that can be shown on an UI */ @Override public void onAuthenticationError(int errorCode, CharSequence errString) {} /** * Called when a recoverable error has been encountered during authentication. The help * string is provided to give the user guidance for what went wrong, such as "Sensor dirty, * please clean it." * @param helpCode An integer identifying the error message * @param helpString A human-readable string that can be shown on an UI */ @Override public void onAuthenticationHelp(int helpCode, CharSequence helpString) {} /** * Called when a biometric is recognized. * @param result An object containing authentication-related data */ public void onAuthenticationSucceeded(AuthenticationResult result) {} /** * Called when a biometric is valid but not recognized. */ @Override public void onAuthenticationFailed() {} /** * Called when a biometric has been acquired, but hasn't been processed yet. * @hide */ @Override public void onAuthenticationAcquired(int acquireInfo) {} /** * Receiver for internal system events. See {@link Builder#setReceiveSystemEvents(boolean)} * @hide */ public void onSystemEvent(int event) {} } /** * Authenticates for the given user. * * @param cancel An object that can be used to cancel authentication * @param executor An executor to handle callback events * @param callback An object to receive authentication events * @param userId The user to authenticate * * @hide */ @RequiresPermission(USE_BIOMETRIC_INTERNAL) public void authenticateUser(@NonNull CancellationSignal cancel, @NonNull @CallbackExecutor Executor executor, @NonNull AuthenticationCallback callback, int userId) { if (cancel == null) { throw new IllegalArgumentException("Must supply a cancellation signal"); } if (executor == null) { throw new IllegalArgumentException("Must supply an executor"); } if (callback == null) { throw new IllegalArgumentException("Must supply a callback"); } authenticateInternal(null /* crypto */, cancel, executor, callback, userId); } /** * This call warms up the biometric hardware, displays a system-provided dialog, and starts * scanning for a biometric. It terminates when {@link * AuthenticationCallback#onAuthenticationError(int, CharSequence)} is called, when {@link * AuthenticationCallback#onAuthenticationSucceeded( AuthenticationResult)}, or when the user * dismisses the system-provided dialog, at which point the crypto object becomes invalid. This * operation can be canceled by using the provided cancel object. The application will receive * authentication errors through {@link AuthenticationCallback}, and button events through the * corresponding callback set in {@link Builder#setNegativeButton(CharSequence, Executor, * DialogInterface.OnClickListener)}. It is safe to reuse the {@link BiometricPrompt} object, * and calling {@link BiometricPrompt#authenticate(CancellationSignal, Executor, * AuthenticationCallback)} while an existing authentication attempt is occurring will stop the * previous client and start a new authentication. The interrupted client will receive a * cancelled notification through {@link AuthenticationCallback#onAuthenticationError(int, * CharSequence)}. * * <p>Note: Applications generally should not cancel and start authentication in quick * succession. For example, to properly handle authentication across configuration changes, it's * recommended to use BiometricPrompt in a fragment with setRetainInstance(true). By doing so, * the application will not need to cancel/restart authentication during the configuration * change. * * <p>Per the Android CDD, only biometric authenticators that meet or exceed the requirements * for <strong>Strong</strong> are permitted to integrate with Keystore to perform related * cryptographic operations. Therefore, it is an error to call this method after explicitly * calling {@link Builder#setAllowedAuthenticators(int)} with any biometric strength other than * {@link Authenticators#BIOMETRIC_STRONG}. * * @throws IllegalArgumentException If any argument is null, or if the allowed biometric * authenticator strength is explicitly set to {@link Authenticators#BIOMETRIC_WEAK}. Prior to * {@link android.os.Build.VERSION_CODES#R}, this exception is also thrown if * {@link Builder#setDeviceCredentialAllowed(boolean)} was explicitly set to true. * * @param crypto A cryptographic operation to be unlocked after successful authentication. * @param cancel An object that can be used to cancel authentication. * @param executor An executor to handle callback events. * @param callback An object to receive authentication events. */ @RequiresPermission(USE_BIOMETRIC) public void authenticate(@NonNull CryptoObject crypto, @NonNull CancellationSignal cancel, @NonNull @CallbackExecutor Executor executor, @NonNull AuthenticationCallback callback) { if (crypto == null) { throw new IllegalArgumentException("Must supply a crypto object"); } if (cancel == null) { throw new IllegalArgumentException("Must supply a cancellation signal"); } if (executor == null) { throw new IllegalArgumentException("Must supply an executor"); } if (callback == null) { throw new IllegalArgumentException("Must supply a callback"); } // Disallow explicitly setting any non-Strong biometric authenticator types. final @Authenticators.Types int authenticators = mBundle.getInt( KEY_AUTHENTICATORS_ALLOWED, Authenticators.BIOMETRIC_STRONG); final int biometricStrength = authenticators & Authenticators.BIOMETRIC_WEAK; if ((biometricStrength & ~Authenticators.BIOMETRIC_STRONG) != 0) { throw new IllegalArgumentException("Only Strong biometrics supported with crypto"); } authenticateInternal(crypto, cancel, executor, callback, mContext.getUserId()); } /** * This call warms up the biometric hardware, displays a system-provided dialog, and starts * scanning for a biometric. It terminates when {@link * AuthenticationCallback#onAuthenticationError(int, CharSequence)} is called, when {@link * AuthenticationCallback#onAuthenticationSucceeded( AuthenticationResult)} is called, or when * the user dismisses the system-provided dialog. This operation can be canceled by using the * provided cancel object. The application will receive authentication errors through {@link * AuthenticationCallback}, and button events through the corresponding callback set in {@link * Builder#setNegativeButton(CharSequence, Executor, DialogInterface.OnClickListener)}. It is * safe to reuse the {@link BiometricPrompt} object, and calling {@link * BiometricPrompt#authenticate(CancellationSignal, Executor, AuthenticationCallback)} while * an existing authentication attempt is occurring will stop the previous client and start a new * authentication. The interrupted client will receive a cancelled notification through {@link * AuthenticationCallback#onAuthenticationError(int, CharSequence)}. * * <p>Note: Applications generally should not cancel and start authentication in quick * succession. For example, to properly handle authentication across configuration changes, it's * recommended to use BiometricPrompt in a fragment with setRetainInstance(true). By doing so, * the application will not need to cancel/restart authentication during the configuration * change. * * @throws IllegalArgumentException If any of the arguments are null. * * @param cancel An object that can be used to cancel authentication. * @param executor An executor to handle callback events. * @param callback An object to receive authentication events. */ @RequiresPermission(USE_BIOMETRIC) public void authenticate(@NonNull CancellationSignal cancel, @NonNull @CallbackExecutor Executor executor, @NonNull AuthenticationCallback callback) { if (cancel == null) { throw new IllegalArgumentException("Must supply a cancellation signal"); } if (executor == null) { throw new IllegalArgumentException("Must supply an executor"); } if (callback == null) { throw new IllegalArgumentException("Must supply a callback"); } authenticateInternal(null /* crypto */, cancel, executor, callback, mContext.getUserId()); } private void cancelAuthentication() { if (mService != null) { try { mService.cancelAuthentication(mToken, mContext.getOpPackageName()); } catch (RemoteException e) { Log.e(TAG, "Unable to cancel authentication", e); } } } private void authenticateInternal(@Nullable CryptoObject crypto, @NonNull CancellationSignal cancel, @NonNull @CallbackExecutor Executor executor, @NonNull AuthenticationCallback callback, int userId) { try { if (cancel.isCanceled()) { Log.w(TAG, "Authentication already canceled"); return; } else { cancel.setOnCancelListener(new OnAuthenticationCancelListener()); } mCryptoObject = crypto; mExecutor = executor; mAuthenticationCallback = callback; final long sessionId = crypto != null ? crypto.getOpId() : 0; final Bundle bundle; if (crypto != null) { // Allowed authenticators should default to BIOMETRIC_STRONG for crypto auth. // Note that we use a new bundle here so as to not overwrite the application's // preference, since it is possible that the same prompt configuration be used // without a crypto object later. bundle = new Bundle(mBundle); bundle.putInt(KEY_AUTHENTICATORS_ALLOWED, mBundle.getInt(KEY_AUTHENTICATORS_ALLOWED, Authenticators.BIOMETRIC_STRONG)); } else { bundle = mBundle; } mService.authenticate(mToken, sessionId, userId, mBiometricServiceReceiver, mContext.getOpPackageName(), bundle); } catch (RemoteException e) { Log.e(TAG, "Remote exception while authenticating", e); mExecutor.execute(() -> { callback.onAuthenticationError(BiometricPrompt.BIOMETRIC_ERROR_HW_UNAVAILABLE, mContext.getString(R.string.biometric_error_hw_unavailable)); }); } } }
42.258325
100
0.65741
be9bbd0a18f28f605c762a1c00065b3a016bd227
253
package com.github.bingoohuang.blackcat.agent.collectors; import com.github.bingoohuang.blackcat.sdk.protobuf.BlackcatMsg.BlackcatReq; import com.google.common.base.Optional; public interface BlackcatCollector { Optional<BlackcatReq> collect(); }
28.111111
76
0.822134
7b94caeab5eb8428d9234ea6a7271eb5e518c92c
948
package org.usfirst.frc308.FRC2018308.subsystems; import edu.wpi.first.wpilibj.DoubleSolenoid; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.command.Subsystem; import org.usfirst.frc308.FRC2018308.Robot; import org.usfirst.frc308.FRC2018308.RobotMap; import org.usfirst.frc308.FRC2018308.commands.*; // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=IMPORTS import com.ctre.CANTalon; public class Claw extends Subsystem { public static Solenoid clawSolenoid = RobotMap.clawSolenoid; @Override protected void initDefaultCommand() { setDefaultCommand(new TeleopClaw()); } @Override public void periodic() { Robot.claw.openClaw(); } public void openClaw() { if(Robot.oi.codriver.getRawButton(3) == true) { Claw.clawSolenoid.set(false); } if(Robot.oi.codriver.getRawButton(1) == true) { Claw.clawSolenoid.set(true); } } public void autoOpenClaw() { Claw.clawSolenoid.set(true);; } }
22.046512
61
0.75211
07813d0ca178f1d8d7df5fe94f7fc60002d0dfd9
5,789
package com.example.tests.appmanager; import com.example.tests.model.LocalValueData; import org.openqa.selenium.*; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import java.util.concurrent.TimeUnit; import static org.testng.Assert.assertTrue; public class LocalValueHelper extends HelperBase { public boolean acceptNextAlert = true; public LocalValueHelper(WebDriver driver) { super(driver); } public void submitLocalValueCreation() throws InterruptedException { click(By.xpath("//button[@type='submit']")); Thread.sleep(1000); } public void fillLocalValueForm(LocalValueData localValueData) throws InterruptedException { type(By.id("poll-title"), localValueData.getTitle()); type(By.id("poll-description"), localValueData.getDescription()); select_2(By.xpath("//*[@id='select2-poll-region_id-container']"), By.xpath("//input[@type='search']"), localValueData.getRegion()); Thread.sleep(500); //Костыль, нужно переделать select_2(By.xpath("//*[@id='municipal-div']/div/span/span[1]/span/span[2]"), By.xpath("//input[@type='search']"), localValueData.getMunicipality()); type(By.id("poll-form_date_from"), localValueData.getDate_start()); type(By.id("poll-form_date_to"), localValueData.getDate_end()); type(By.id("attachment-0-title"), localValueData.getAttachment_name()); type(By.id("attachment-0-description"), localValueData.getAttachment_description_1()); attach(By.id("attachment-0-file"), localValueData.getAttachment_1()); type(By.id("pollquestion-0-title"), localValueData.getQuestion_1()); type(By.id("pollquestion-0-rating_to"), localValueData.getQuestion_option_1()); } public void initLocalValueCreation() { click(By.linkText("Создать обсуждение (оценка)")); } public void selectLocalValueModify() { while (true) { if(driver.findElements(By.linkText("Тестовая оценка МЗ для редактирования")).size() != 0) { click(By.linkText("Тестовая оценка МЗ для редактирования")); break; } else { try { click(By.linkText("»")); } catch (NoSuchElementException ex) { Assert.fail("NoSuchElementException", ex); } } } } public void selectLocalValuePublish() { while (true) { if(driver.findElements(By.linkText("Тестовая оценка МЗ тест (Опубликован)")).size() != 0) { click(By.linkText("Тестовая оценка МЗ тест (Опубликован)")); break; } else { try { click(By.linkText("»")); } catch (NoSuchElementException ex) { Assert.fail("NoSuchElementException", ex); } } } } public void selectLocalValueDelete() { while (true) { if(driver.findElements(By.linkText("Тестовая оценка МЗ (Удалено)")).size() != 0) { click(By.linkText("Тестовая оценка МЗ (Удалено)")); break; } else { try { click(By.linkText("»")); } catch (NoSuchElementException ex) { Assert.fail("NoSuchElementException", ex); } } } } public void initLocalValueModification() { click(By.linkText("Редактировать")); } public void modifyLocalValueForm(LocalValueData localValueData) throws InterruptedException { type(By.id("poll-title"), localValueData.getTitle()); type(By.id("poll-description"), localValueData.getDescription()); select_2(By.xpath("//*[@id='select2-poll-region_id-container']"), By.xpath("//input[@type='search']"), localValueData.getRegion()); Thread.sleep(500); //Костыль, нужно переделать select_2(By.xpath("//*[@id='municipal-div']/div/span/span[1]/span/span[2]"), By.xpath("//input[@type='search']"), localValueData.getMunicipality()); type(By.id("poll-form_date_from"), localValueData.getDate_start()); type(By.id("poll-form_date_to"), localValueData.getDate_end()); type(By.id("attachment-0-title"), localValueData.getAttachment_name()); type(By.id("attachment-0-description"), localValueData.getAttachment_description_1()); attach(By.id("attachment-0-file"), localValueData.getAttachment_1()); type(By.id("pollquestion-0-title"), localValueData.getQuestion_1()); type(By.id("pollquestion-0-rating_to"), localValueData.getQuestion_option_1()); } private String closeAlertAndGetItsText() { try { Alert alert = driver.switchTo().alert(); String alertText = alert.getText(); if (acceptNextAlert) { alert.accept(); } else { alert.dismiss(); } return alertText; } finally { acceptNextAlert = true; } } public void submitLocalValueModification() throws InterruptedException { click(By.xpath("//button[@type='submit']")); Thread.sleep(1000); } public void deleteLocalValue() throws InterruptedException { click(By.linkText("Удалить")); assertTrue(closeAlertAndGetItsText().matches("^Вы действительно хотите удалить этот элемент[\\s\\S]$")); Thread.sleep(1000); } public void publishLocalValue() throws InterruptedException { click(By.linkText("Опубликовать")); Thread.sleep(1000); } }
31.291892
156
0.606841
94cf1f3f718e25a74b50d249e6c013419e6b2b0e
2,598
/** Copyright 2017 Andrea "Stock" Stocchero 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.pepstock.coderba.client.events; import org.pepstock.coderba.client.entities.Range; import org.pepstock.coderba.client.entities.TextMarker; /** * Fired when the range is cleared, either through cursor movement in combination with <code>clearOnEnter</code> or through a * call to its <code>clear()</code> method.<br> * Will only be fired once per handle.<br> * Note that deleting the range through text editing does not fire this event, because an undo action might bring the range back * into existence. * * @author Andrea "Stock" Stocchero */ public final class TextMarkerClearEvent extends AbstractTextMarkerEvent<TextMarkerClearEventHandler> { /** * Event type */ public static final Type<TextMarkerClearEventHandler> TYPE = new Type<>(); /** * Event name */ public static final String NAME = "clear"; // range instance private final Range range; /** * Creates a text marker {@value NAME} event. * * @param textMarker text marker instance * @param range range instance which gives the part of the document that the range spanned when it was cleared. */ public TextMarkerClearEvent(TextMarker textMarker, Range range) { super(TYPE, textMarker); // checks if range is consistent if (range == null) { // if no, excpetion throw new IllegalArgumentException("Range is null"); } this.range = range; } /** * Returns the range which gives the part of the document that the range spanned when it was cleared. * * @return the range instance */ public Range getRange() { return range; } /* * (non-Javadoc) * * @see com.google.gwt.event.shared.GwtEvent#getAssociatedType() */ @Override public Type<TextMarkerClearEventHandler> getAssociatedType() { return TYPE; } /* * (non-Javadoc) * * @see com.google.gwt.event.shared.GwtEvent#dispatch(com.google.gwt.event.shared.EventHandler) */ @Override protected void dispatch(TextMarkerClearEventHandler handler) { handler.onClear(this); } }
29.522727
128
0.724788
5aa7a797b0e3f1750f5d913de52f45f28fbef51c
894
package frc.robot.util; import java.util.ArrayDeque; import java.util.Deque; public class MovingAverage { //For finding averages of the most recent //certain number of values in a discrete continuous flow of values Deque<Double> dq; //Double ended queue: a linear storage that can //be edited from both ends, pronounced "deck" int size; double sum; public MovingAverage(int size) { dq = new ArrayDeque<>(); this.size = size; sum = 0; } public void nextVal(double val) { //Add value, remove oldest value if already at size sum += val; dq.add(val); if (dq.size() > size) { sum -= dq.getFirst(); dq.removeFirst(); } } public double get() { //Get average of values currently stored if (dq.size() == 0) return 0; return sum / dq.size(); } }
27.090909
89
0.589485
e121938742c03aa84971b86795f0713495e070dc
2,638
package com.shiyajian.examples.consumer.utils; import org.apache.commons.fileupload.disk.DiskFileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.io.IOUtils; import org.springframework.http.MediaType; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; import javax.annotation.Nullable; import javax.validation.constraints.NotNull; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; /** * @author shiyajian * create: 2018-11-25 */ public class MultipartFileUtil { private MultipartFileUtil() { //no instance } /** * 将file转换成MultipartFile * * @param source 源文件 * @param fieldName field字段名称,default : file * @return */ public static MultipartFile from(@NotNull File source, @Nullable String fieldName) { if (source == null) { return null; } fieldName = fieldName == null ? "file" : fieldName; DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem(fieldName, MediaType.TEXT_PLAIN_VALUE, true, source.getName()); try (InputStream input = new FileInputStream(source); OutputStream os = fileItem.getOutputStream()) { IOUtils.copy(input, os); } catch (Exception e) { throw new IllegalArgumentException("Invalid file: " + e, e); } return new CommonsMultipartFile(fileItem); } public static MultipartFile[] from(File[] source, String fieldName) { if (source.length == 0) { return new MultipartFile[0]; } fieldName = fieldName == null ? "file" : fieldName; List<MultipartFile> multipartFiles = new ArrayList<>(); for (File file : source) { DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem(fieldName, MediaType.TEXT_PLAIN_VALUE, true, file.getName()); try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) { IOUtils.copy(input, os); } catch (Exception e) { throw new IllegalArgumentException("Invalid file: " + e, e); } multipartFiles.add(new CommonsMultipartFile(fileItem)); } MultipartFile[] multipartFileArr = new MultipartFile[multipartFiles.size()]; return multipartFiles.toArray(multipartFileArr); } }
33.820513
98
0.657316
541f775534ca7068c0777c87a6899b330b9d4d1b
3,560
/*************************GO-LICENSE-START********************************* * Copyright 2014 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *************************GO-LICENSE-END***********************************/ package com.thoughtworks.go.server.security; import com.thoughtworks.go.config.CaseInsensitiveString; import com.thoughtworks.go.domain.NullUser; import com.thoughtworks.go.domain.User; import com.thoughtworks.go.server.domain.Username; import com.thoughtworks.go.server.service.UserService; import com.thoughtworks.go.server.util.UserHelper; import org.springframework.security.DisabledException; import org.springframework.security.context.SecurityContext; import org.springframework.security.context.SecurityContextHolder; import org.springframework.security.ui.FilterChainOrder; import org.springframework.security.ui.SpringSecurityFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static com.thoughtworks.go.domain.PersistentObject.NOT_PERSISTED; import static com.thoughtworks.go.server.security.SessionDenialAwareAuthenticationProcessingFilterEntryPoint.SESSION_DENIED; import static org.springframework.security.ui.AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY; /** * @understands */ public class UserEnabledCheckFilter extends SpringSecurityFilter { private final UserService userService; public UserEnabledCheckFilter(UserService userService) { this.userService = userService; } protected void doFilterHttp(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { User user = getUser(request); if (user.getId() != NOT_PERSISTED && UserHelper.getUserId(request) == null) { UserHelper.setUserId(request, user.getId()); } if (!user.isEnabled()) { SecurityContext context = SecurityContextHolder.getContext(); request.getSession().setAttribute(SPRING_SECURITY_LAST_EXCEPTION_KEY, new DisabledException("Your account has been disabled by the administrator")); request.setAttribute(SESSION_DENIED, true); context.setAuthentication(null); UserHelper.setUserId(request, null); } chain.doFilter(request, response); } private User getUser(HttpServletRequest request) { Long userId = UserHelper.getUserId(request); if (userId == null) { Username userName = UserHelper.getUserName(); if (userName.isAnonymous() || userName.isGoAgentUser()) { return new NullUser(); } return userService.findUserByName(CaseInsensitiveString.str(userName.getUsername())); } else { return userService.load(userId); } } public int getOrder() { return FilterChainOrder.AUTHENTICATION_PROCESSING_FILTER + 1; } }
41.395349
160
0.722472
2d376be60e771f191128764fad670bc95b6b156d
3,190
package UnitTest.DataStructureTest.treeTest.binaryTreeTest.binaryTreeApplyTest; import DataStructure.tree.binaryTree.binaryTreeApply.JudgeMirrorBinaryTree; import DataStructure.tree.binaryTree.binaryTreeRealize.BinaryTreeImpl; import UnitTest.DataStructureTest.treeTest.BinaryTreeTestDemo; import org.junit.Test; /** * @author liujun * @version 1.0 * @date 2020/12/21 * @author—Email liujunfirst@outlook.com * @blogURL https://blog.csdn.net/ljfirst * @description 测试案例 判断镜像二叉树 */ public class JudgeMirrorBinaryTreeTest extends BinaryTreeTestDemo { JudgeMirrorBinaryTree jmbt = new JudgeMirrorBinaryTree(); @Test public void testjudge() { BinaryTreeImpl root = gettreeMirrorDemo01(); assert jmbt.judge(root); assert jmbt.judge_Queue(root); root = gettreeMirrorDemo02(); assert jmbt.judge(root); assert jmbt.judge_Queue(root); root = gettreeMirrorDemo03(); assert !jmbt.judge(root); assert !jmbt.judge_Queue(root); assert jmbt.judge(null); assert jmbt.judge_Queue(null); root = gettreeMirrorDemo04(); assert jmbt.judge(root); assert jmbt.judge_Queue(root); } public BinaryTreeImpl gettreeMirrorDemo01() { BinaryTreeImpl binaryTree1 = new BinaryTreeImpl(1); BinaryTreeImpl binaryTree2 = new BinaryTreeImpl(2); BinaryTreeImpl binaryTree3 = new BinaryTreeImpl(2); BinaryTreeImpl binaryTree4 = new BinaryTreeImpl(4); BinaryTreeImpl binaryTree5 = new BinaryTreeImpl(5); BinaryTreeImpl binaryTree6 = new BinaryTreeImpl(5); BinaryTreeImpl binaryTree7 = new BinaryTreeImpl(4); binaryTree1.left = binaryTree3; binaryTree1.right = binaryTree2; binaryTree2.left = binaryTree5; binaryTree2.right = binaryTree4; binaryTree3.left = binaryTree7; binaryTree3.right = binaryTree6; return binaryTree1; } public BinaryTreeImpl gettreeMirrorDemo02() { BinaryTreeImpl binaryTree1 = new BinaryTreeImpl(1); BinaryTreeImpl binaryTree2 = new BinaryTreeImpl(2); BinaryTreeImpl binaryTree3 = new BinaryTreeImpl(2); binaryTree1.left = binaryTree3; binaryTree1.right = binaryTree2; return binaryTree1; } public BinaryTreeImpl gettreeMirrorDemo03() { BinaryTreeImpl binaryTree1 = new BinaryTreeImpl(1); BinaryTreeImpl binaryTree2 = new BinaryTreeImpl(2); BinaryTreeImpl binaryTree3 = new BinaryTreeImpl(3); BinaryTreeImpl binaryTree4 = new BinaryTreeImpl(4); BinaryTreeImpl binaryTree5 = new BinaryTreeImpl(5); BinaryTreeImpl binaryTree6 = new BinaryTreeImpl(4); BinaryTreeImpl binaryTree7 = new BinaryTreeImpl(5); binaryTree1.left = binaryTree3; binaryTree1.right = binaryTree2; binaryTree2.left = binaryTree5; binaryTree2.right = binaryTree4; binaryTree3.left = binaryTree7; binaryTree3.right = binaryTree6; return binaryTree1; } public BinaryTreeImpl gettreeMirrorDemo04() { BinaryTreeImpl binaryTree1 = new BinaryTreeImpl(1); return binaryTree1; } }
35.054945
79
0.697806
78d744087998a97bc9df7b8d171a13425af18666
2,636
package github.com.st235.grokkingspans.activities; import android.content.Context; import android.graphics.Rect; import android.support.annotation.NonNull; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.AppCompatTextView; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import static github.com.st235.grokkingspans.Utils.toPx; /** * Created by alexanderdadukin on 09.03.2018. */ class InterfaceBuilder { @NonNull private final LinearLayout rootContext; InterfaceBuilder(@NonNull Context context) { rootContext = new LinearLayout(context); rootContext.setOrientation(LinearLayout.VERTICAL); } InterfaceBuilder addButton(@NonNull CharSequence text, @NonNull View.OnClickListener listener) { AppCompatButton button = new AppCompatButton(rootContext.getContext()); button.setText(text); button.setOnClickListener(listener); rootContext.addView(button, layout()); return this; } InterfaceBuilder margins(@NonNull Rect margins) { FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ); params.setMargins(margins.left, margins.top, margins.right, margins.bottom); rootContext.setLayoutParams(params); return this; } InterfaceBuilder addText(@NonNull CharSequence text) { return addText(text, 14, Gravity.LEFT); } InterfaceBuilder addText(@NonNull CharSequence text, int gravity) { return addText(text, 14, Gravity.LEFT); } InterfaceBuilder addText(@NonNull CharSequence text, int textSize, int gravity) { AppCompatTextView textView = new AppCompatTextView(rootContext.getContext()); textView.setText(text); textView.setGravity(gravity); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, textSize); rootContext.addView(textView, layout()); return this; } LinearLayout build() { return rootContext; } private LinearLayout.LayoutParams layout() { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); params.gravity = Gravity.CENTER; params.topMargin = toPx(4); params.bottomMargin = toPx(4); return params; } }
32.95
109
0.700683
4ec21f3985f1b036a25d80aba88567d284da02fc
15,203
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projeto.gui.telas; import java.util.logging.Level; import java.util.logging.Logger; import projeto.erro.ConexaoException; import projeto.erro.DaoException; import projeto.erro.RegraExceptionTratamento; import projeto.negocio.classesBasicas.Tratamento; import projeto.negocio.fachada.FachadaTratamento; import projeto.util.Msg; /** * * @author daien */ public class TelaTratamento extends javax.swing.JFrame { /** * Creates new form Tratamento */ public TelaTratamento() { initComponents(); } /** * 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. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); txtNomeAnimalTratamento = new javax.swing.JTextField(); txtDataFinalTratamento = new javax.swing.JFormattedTextField(); txtDiagnostico = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); jTextAreaDescricao = new javax.swing.JTextArea(); txtDataInicialTratamento = new javax.swing.JFormattedTextField(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); btbCadastrarTramento = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Tratamento"); setResizable(false); try { txtDataFinalTratamento.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } jTextAreaDescricao.setColumns(20); jTextAreaDescricao.setRows(5); jScrollPane1.setViewportView(jTextAreaDescricao); try { txtDataInicialTratamento.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel2.setText("Nome Animal :"); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel3.setText("Data Inical :"); jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel4.setText("Data Final :"); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel6.setText("Diagnostico :"); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel5.setText("Descrição Tratamento: "); btbCadastrarTramento.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N btbCadastrarTramento.setIcon(new javax.swing.ImageIcon(getClass().getResource("/projeto/gui/icones/salvar_1.png"))); // NOI18N btbCadastrarTramento.setText("Salvar"); btbCadastrarTramento.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btbCadastrarTramentoActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(36, 36, 36) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel4) .addComponent(jLabel6)) .addGap(53, 53, 53) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtDataFinalTratamento, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtDiagnostico, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtDataInicialTratamento, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtNomeAnimalTratamento, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btbCadastrarTramento, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txtNomeAnimalTratamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(txtDataInicialTratamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(txtDataFinalTratamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(20, 20, 20) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel6) .addComponent(txtDiagnostico, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(23, 23, 23) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(btbCadastrarTramento) .addContainerGap(20, Short.MAX_VALUE)) ); jPanel2.setBackground(new java.awt.Color(0, 102, 204)); jLabel1.setFont(new java.awt.Font("Dialog", 0, 18)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Tratamento"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(167, Short.MAX_VALUE) .addComponent(jLabel1) .addContainerGap(167, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(31, 31, 31) .addComponent(jLabel1) .addContainerGap(25, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void btbCadastrarTramentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btbCadastrarTramentoActionPerformed /** * Criando o objeto tratamento. */ Tratamento tratamento = new Tratamento(); tratamento.setDiagnosticoTratamento(txtDiagnostico.getText()); tratamento.setDataInicialTratamento(txtDataInicialTratamento.getText()); tratamento.setDataFinalTratamento(txtDataFinalTratamento.getText()); tratamento.setDescricaoTratamento(jTextAreaDescricao.getText()); tratamento.setNomeAnimal(txtNomeAnimalTratamento.getText()); /** * Instanciando uma nova fachada para tratar a manipulacao dos dados. */ FachadaTratamento fachada = new FachadaTratamento(); /** * Try Catch para agendar um exame. */ try{ fachada.inserirTratamento(tratamento); }catch(RegraExceptionTratamento e){ Msg.msgErro(e.getMessage(), "Erro ao inserir"); } catch (ConexaoException | DaoException ex) { Logger.getLogger(TelaTratamento.class.getName()).log(Level.SEVERE, null, ex); } txtNomeAnimalTratamento.setText(""); txtDataInicialTratamento.setText(""); txtDataFinalTratamento.setText(""); jTextAreaDescricao.setText(""); txtDiagnostico.setText(""); }//GEN-LAST:event_btbCadastrarTramentoActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TelaTratamento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TelaTratamento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TelaTratamento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaTratamento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TelaTratamento().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btbCadastrarTramento; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextAreaDescricao; private javax.swing.JFormattedTextField txtDataFinalTratamento; private javax.swing.JFormattedTextField txtDataInicialTratamento; private javax.swing.JTextField txtDiagnostico; private javax.swing.JTextField txtNomeAnimalTratamento; // End of variables declaration//GEN-END:variables }
52.243986
179
0.653818
dd3e5d90aa0cd803fc651da4573e8a36468b1c89
1,417
package org.onap.sdnc.northbound; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.generic.resource.rev170824.PortMirrorTopologyOperationInput; import org.opendaylight.yang.gen.v1.org.onap.sdnc.northbound.generic.resource.rev170824.PortMirrorTopologyOperationOutput; import org.opendaylight.yangtools.yang.common.RpcResult; import static org.junit.Assert.assertEquals; import static org.onap.sdnc.northbound.util.MDSALUtil.*; @RunWith(MockitoJUnitRunner.class) public class PortMirrorTopologyOperationRPCTest extends GenericResourceApiProviderTest { private static final String SVC_OPERATION = "policy-update-notify-operation"; @Before public void setUp() throws Exception { super.setUp(); svcClient.setScvOperation(SVC_OPERATION); } @Test public void should_fail_when_invalid_vnf_topology() throws Exception { PortMirrorTopologyOperationInput input = build(PortMirrorTopologyOperationInput()); PortMirrorTopologyOperationOutput output = exec(genericResourceApiProvider::portMirrorTopologyOperation, input, RpcResult::getResult); assertEquals("404", output.getResponseCode()); assertEquals("invalid input, null or empty service-instance-id", output.getResponseMessage()); } }
38.297297
122
0.784757
c487559ca1393c26d79ae27d13cba868dcfa139d
2,316
/* * 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.tuscany.sca.vtest.javaapi.apis.conversation.impl; import org.apache.tuscany.sca.vtest.javaapi.apis.conversation.BComponent; import org.junit.Assert; import org.oasisopen.sca.ComponentContext; import org.oasisopen.sca.annotation.Context; import org.oasisopen.sca.annotation.ConversationID; import org.oasisopen.sca.annotation.Destroy; import org.oasisopen.sca.annotation.Init; import org.oasisopen.sca.annotation.Scope; import org.oasisopen.sca.annotation.Service; @Service(BComponent.class) @Scope("CONVERSATION") public class BComponentImpl implements BComponent { public static int customInitCount = 0; public static int customDestroyCount = 0; protected ComponentContext componentContext; @ConversationID protected String cid; @Context public void setComponentContext(ComponentContext context) { this.componentContext = context; } public String getName() { return "ComponentB"; } public void testCustomConversationID() { Assert.assertEquals("AConversationID", cid); } public void testGeneratedConversationID(Object id) { Assert.assertEquals(id.toString(), cid); } public void endsConversation() { } @Init public void initB() { if (cid.equals("AConversationID")) { customInitCount++; } } @Destroy public void destroyB() { if (cid.equals("AConversationID")) { customDestroyCount++; } } }
29.316456
73
0.716321
d8f291afe474e338c42537c6e4b1981b6138e02c
196
package com.java.proiect.exceptions; public class AlbumNotFoundError extends RuntimeException{ public AlbumNotFoundError() { super("Album not found in the database!"); } }
24.5
58
0.704082
31b609ea4fb814c3e04e2418b9bf8ecea5e19a21
3,999
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.insights; import com.netflix.netty.common.HttpLifecycleChannelHandler; import com.netflix.zuul.passport.CurrentPassport; import com.netflix.zuul.passport.PassportState; import io.netty.channel.*; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.LastHttpContent; /** * User: Mike Smith * Date: 9/24/16 * Time: 2:41 PM */ public class PassportStateHttpServerHandler extends CombinedChannelDuplexHandler { public PassportStateHttpServerHandler() { super(new InboundHandler(), new OutboundHandler()); } private static CurrentPassport passport(ChannelHandlerContext ctx) { return CurrentPassport.fromChannel(ctx.channel()); } private static class InboundHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // Get existing passport or create new if none already. CurrentPassport passport = passport(ctx); if (msg instanceof HttpRequest) { // If the current passport for this channel already contains an inbound http request, then // we know it's used, so discard and create a new one. // NOTE: we do this because we want to include the initial conn estab + ssl handshake into the passport // of the 1st request on a channel, but not on subsequent requests. if (passport.findState(PassportState.IN_REQ_HEADERS_RECEIVED) != null) { passport = CurrentPassport.createForChannel(ctx.channel()); } passport.add(PassportState.IN_REQ_HEADERS_RECEIVED); } if (msg instanceof LastHttpContent) { passport.add(PassportState.IN_REQ_LAST_CONTENT_RECEIVED); } else if (msg instanceof HttpContent) { passport.add(PassportState.IN_REQ_CONTENT_RECEIVED); } super.channelRead(ctx, msg); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { try { super.userEventTriggered(ctx, evt); } finally { if (evt instanceof HttpLifecycleChannelHandler.CompleteEvent) { CurrentPassport.clearFromChannel(ctx.channel()); } } } } private static class OutboundHandler extends ChannelOutboundHandlerAdapter { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { CurrentPassport passport = passport(ctx); // Set into the SENDING state. if (msg instanceof HttpResponse) { passport.add(PassportState.OUT_RESP_HEADERS_SENDING); promise.addListener(new PassportStateListener(passport, PassportState.OUT_RESP_HEADERS_SENT, PassportState.OUT_RESP_HEADERS_ERROR_SENDING)); } if (msg instanceof LastHttpContent) { passport.add(PassportState.OUT_RESP_LAST_CONTENT_SENDING); promise.addListener(new PassportStateListener(passport, PassportState.OUT_RESP_LAST_CONTENT_SENT, PassportState.OUT_RESP_LAST_CONTENT_ERROR_SENDING)); } else if (msg instanceof HttpContent) { passport.add(PassportState.OUT_RESP_CONTENT_SENDING); promise.addListener(new PassportStateListener(passport, PassportState.OUT_RESP_CONTENT_SENT, PassportState.OUT_RESP_CONTENT_ERROR_SENDING)); } // Continue with the write. super.write(ctx, msg, promise); } } }
36.027027
107
0.753188
d25b14a2a36d9183e1b20e5574caaaa6c4e1cef5
2,908
/** */ package fr.unice.polytech.si5.webots.polycreate.abstractsyntax.polycreate; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Distance Condition</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link fr.unice.polytech.si5.webots.polycreate.abstractsyntax.polycreate.DistanceCondition#getDistance <em>Distance</em>}</li> * <li>{@link fr.unice.polytech.si5.webots.polycreate.abstractsyntax.polycreate.DistanceCondition#getOperator <em>Operator</em>}</li> * </ul> * * @see fr.unice.polytech.si5.webots.polycreate.abstractsyntax.polycreate.PolycreatePackage#getDistanceCondition() * @model * @generated */ public interface DistanceCondition extends ObjectCondition { /** * Returns the value of the '<em><b>Distance</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Distance</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Distance</em>' attribute. * @see #setDistance(double) * @see fr.unice.polytech.si5.webots.polycreate.abstractsyntax.polycreate.PolycreatePackage#getDistanceCondition_Distance() * @model * @generated */ double getDistance(); /** * Sets the value of the '{@link fr.unice.polytech.si5.webots.polycreate.abstractsyntax.polycreate.DistanceCondition#getDistance <em>Distance</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Distance</em>' attribute. * @see #getDistance() * @generated */ void setDistance(double value); /** * Returns the value of the '<em><b>Operator</b></em>' attribute. * The literals are from the enumeration {@link fr.unice.polytech.si5.webots.polycreate.abstractsyntax.polycreate.OPERATOR}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Operator</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Operator</em>' attribute. * @see fr.unice.polytech.si5.webots.polycreate.abstractsyntax.polycreate.OPERATOR * @see #setOperator(OPERATOR) * @see fr.unice.polytech.si5.webots.polycreate.abstractsyntax.polycreate.PolycreatePackage#getDistanceCondition_Operator() * @model * @generated */ OPERATOR getOperator(); /** * Sets the value of the '{@link fr.unice.polytech.si5.webots.polycreate.abstractsyntax.polycreate.DistanceCondition#getOperator <em>Operator</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Operator</em>' attribute. * @see fr.unice.polytech.si5.webots.polycreate.abstractsyntax.polycreate.OPERATOR * @see #getOperator() * @generated */ void setOperator(OPERATOR value); } // DistanceCondition
36.810127
160
0.693948
8c230c6c8af818e938a237c82d19f9c76e0c1af5
16,958
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package agsml; import java.io.IOException; import java.io.BufferedWriter; import java.io.StringWriter; import java.io.FileWriter; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Stack; import java.util.logging.Logger; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Element; import java.util.logging.Level; import java.nio.file.Path; import java.nio.file.Paths; import javax.xml.bind.DatatypeConverter; /** * * @author thomsonsj */ class XML_Writer extends Base_Writer { public static final String AGS_STYLESHEET = "stylesheet"; public final static String AGS_HTMLPATH= "AGSMLPath"; private BufferedWriter m_bw; private StringWriter m_sw; private StringBuilder m_sb; private StringBuilder m_attrib; private final String const_Open = "<"; private final String const_Close =">"; private final String const_OpenEnd="</"; private final String const_CDATAstart="<![CDATA["; private final String const_CDATAend="]]>"; private final String const_StylesheetAttribTag = "stylesheet"; private final String const_XMLVersion = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; private final String const_SPACE = " "; private final String const_EQUALS = "="; private final String const_QUOTE = "\""; private Pattern p; private Matcher m; private Stack<String> m_open; public XML_Writer() { m_attrib = new StringBuilder(); p = Pattern.compile("[&<>]"); m_open = new Stack<String>(); m_sw = new StringWriter(); m_bw = new BufferedWriter(m_sw); } public XML_Writer(BufferedWriter bw ) { this(); m_bw = bw; } public String stylesheet() { return getProperty(AGS_STYLESHEET); } public void setStyleSheet(String s1) { setProperty(AGS_STYLESHEET,s1); } protected int openFile(Node n1) { String s1 = n1.getTextContent(); setOutputFile(s1); setStyleSheet(n1); return openFile(true, false); } // protected int openFile(String fout, Node DataStructureNode) { // setOutputFile(fout); // setAGSDataStructureNode(DataStructureNode); // return openFile(true); // } public void Process() { try { Node n1 = m_ds.RootNode(); Process(n1); } catch (Exception e) { } } protected int openFile(boolean overwrite, boolean datestamp) { try { // this.closeFile(); File file = new File(fileOut()); if (file.isDirectory()) { if (!file.exists()) { file.mkdir(); } } else { if (file.exists() && overwrite == true) { file.delete(); } if (newFile(overwrite, datestamp)>0) { AddVersionAndStyleSheet(); log.info("File " + fileOut() + " opened"); } } return 1; } catch (Exception e) { return -1; } } Node getRootNodeFirstChild(Node n1) { try { Node n2; if (isRootNode(n1) == true) { n2 = n1.getFirstChild(); while (n2.getNodeType() != Node.ELEMENT_NODE) { n2 = n2.getNextSibling(); } return n2; } else { return null; } } catch (Exception e) { return null; } } private boolean RootNodeName(Node n1) { boolean retvar = false; if (n1.getNodeType() == Node.ELEMENT_NODE) { String s1 = n1.getNodeName(); if(s1.equals (Constants.AGS_DATASTRUCTURE)) retvar = true; } else { retvar = false; } return retvar; } public boolean isRootNode(Node n1) { // boolean retvar = false; if (m_ds.RootNode().isEqualNode(n1)) { return true; } else { return false; } } public void Process(Node n1) { } private XML_Writer(String fout, boolean overwrite, boolean datestamp) { this(); setOutputFile(fout); openFile (overwrite, datestamp); } public XML_Writer(String fout) { this(); setOutputFile(fout); openFile (true, false); } public XML_Writer(String fileout, String stylesheet) { this(); setOutputFileFolder(fileout); setStyleSheet(stylesheet); openFile (true, false); } protected int newFile(boolean overwrite , boolean datestamp) { try { // Close file if alreday open' // Initialise and open new bufferwe writer and stringbuilder String newFileName = getFileName(fileOut(), overwrite, datestamp); setOutputFile(newFileName); m_bw = new BufferedWriter(new FileWriter(fileOut())); if (fieldOut().length() > 0) { m_sb = new StringBuilder(); } return 1; } catch (IOException e) { // catch possible io errors from readLine() log.log(Level.SEVERE, e.getMessage()); log.exiting("XMLWriter", fileOut()); return -1; } } private String getStyleSheetFromAGSMLDataStructure() { try { return setStyleSheet(m_ds.RootNode()); } catch (Exception e) { log.log(Level.SEVERE, e.getMessage()); return ""; } } private String setStyleSheet(Node n1 ){ Element el1 = (Element) n1; String s1 = el1.getAttribute(const_StylesheetAttribTag); setStyleSheet(s1); return stylesheet(); } protected void AddVersionAndStyleSheet() { add (const_XMLVersion,false); if (stylesheet().length()>0) { add ("<?xml-stylesheet type=\"text/xsl\" href=\"" + stylesheet() + "\"?>", false); } } public String toString(){ try { m_bw.flush(); m_sw.flush(); return m_sw.toString(); } catch ( Exception e ) { // catch possible io errors from readLine() log.severe(e.getMessage()); return null; } } public void newLine() { add("\n"); } public void add(String s){ add(s, true); } public void add(byte[] b1, boolean boolAddToString){ try { String s = DatatypeConverter.printBase64Binary(b1); m_bw.append(s); if (m_sb != null && boolAddToString == true) { m_sb.append (s); } } catch (IOException e) { // catch possible io errors from readLine() log.severe(e.getMessage()); } } public void add(String s, boolean boolAddToString){ try { m_bw.append(s); if (m_sb != null && boolAddToString == true) { m_sb.append (s); } } catch (IOException e) { // catch possible io errors from readLine() log.severe (e.getMessage()); } } public void addNodeAttrib(String elName, String elValue) { if (!elName.isEmpty() && !elValue.isEmpty()) { m_attrib.append(this.const_SPACE); m_attrib.append(elName); m_attrib.append(this.const_EQUALS); m_attrib.append (this.const_QUOTE); m_attrib.append(elValue); m_attrib.append (this.const_QUOTE); } } public void openNode (String elName) { add(const_Open + elName + m_attrib.toString() + const_Close); m_open.push(elName); m_attrib = new StringBuilder(); } public void closeNode(){ add(const_OpenEnd + m_open.pop() + const_Close); } public void openElement (String elName) { elName = removeStars (elName); add(const_Open); add(elName); add(const_Close); } private String removeStars(String s1){ String star="\\*"; s1.replaceAll(star, null); return s1; } public void addValid(String val){ m = p.matcher(val); if (m.find()!=true) { add(val); } else { add(const_CDATAstart); add(val); add(const_CDATAend); } } public void add64bit(String s1, byte[] val) { addNodeAttrib ("types:dt","bin.base64"); addNodeAttrib ("xmlns:types", "urn:schemas-microsoft-com:datatypes"); openNode(s1); add(val,false); closeNode(); // <serialized_binary types:dt="bin.base64" xmlns:types="urn:schemas-microsoft-com:datatypes"> // JVBERi0xLjMKJaqrrK0KNCAwIG9iago8PCAvVHlwZSAvSW5mbw...(plus lots more) // </serialized_binary> } public void addAttrib (String elName, String val) { elName = removeStars (elName); add(const_Open); add(elName); add(const_Close); addValid(val); add(const_OpenEnd); add(elName); add(const_Close); newLine(); } public void closeElement (String elName) { elName = removeStars (elName); add(const_OpenEnd); add(elName); add(const_Close); newLine(); } public void closeFile() { try { if (m_bw != null) { m_bw.close(); log.info("File " + fileOut() + " closed"); } } catch (IOException e) { // catch possible io errors from readLine() log.severe (e.getMessage()); } } protected Node Process(Node n1, String hole_id, Double depth_top, Double depth_base){ return null; } protected boolean IsHoleInList(String hole_id) { return IsHoleInList(hole_id,m_holeList); } protected String removeSpecialCharacters(String s1) { Pattern pattern = Pattern.compile("<>:'"); Matcher matcher = pattern.matcher(s1); if (matcher.matches()) { String s2 = matcher.replaceAll(""); return s2; } else { return s1; } } protected boolean ContainsSpecialCharacters(String s1) { Pattern p = Pattern.compile("[_a-zA-Z0-9-().\\s]+"); Matcher m = p.matcher(s1); if (!m.matches()) { log.log(Level.INFO, "string '" + s1 + "' contains special character"); return true; } else { log.log(Level.INFO, "string '" + s1 + "' doesn't contains special character"); return false; } } protected boolean IsValidFileName(String s1) { try { Path p =Paths.get(s1); return true; } catch (Exception e) { return false; } } protected String getHoleList(String delimiter) { StringBuilder sb1 = new StringBuilder(); if (m_holeList == null) { return ""; } for (int i=0; i < m_holeList.getLength(); i++) { Node n1 = m_holeList.item(i); if (n1.getNodeType() == Node.ELEMENT_NODE) { Element el1 = (Element) m_holeList.item(i); String s1 = "'" + el1.getTextContent() + "'"; if (sb1.length()>0) { sb1.append(delimiter + s1); } else { sb1.append(s1); } } } return sb1.toString(); } protected boolean IsHoleInList(String hole_id, NodeList holeList) { try { if (m_onlyHoleId != null) { if (!m_onlyHoleId.isEmpty()) { if (m_onlyHoleId.equalsIgnoreCase(hole_id)) { return true; } else { return false; } } } if (holeList == null) { return true; } else { if (holeList.getLength() == 0) { return true; } else { for (int i=0; i < holeList.getLength(); i++) { Node n1 = holeList.item(i); if (n1.getNodeType() == Node.ELEMENT_NODE) { Element el1 = (Element) holeList.item(i); String s1 = el1.getTextContent(); if (s1.equalsIgnoreCase(hole_id)) { return true; } } } return false; } } } catch (Exception e) { return false; } } //public String lookupTable2 (String t1name) { // if (m_dic.table1_name().equals(t1name)!=true) { // m_dic.find_table1(t1name); // } // return m_dic.table2_name(); //} //public String lookupField2 (String t1name, String f1name) { // if (m_dic.table1_name().equals(t1name)!=true) { // m_dic.find_table1(t1name); // } // m_dic.find_field1(f1name); // return m_dic.field2_name(); //} private boolean openIfNodeNamed(Node n1, String s1) { boolean retvar = false; if (n1.getNodeType() == Node.ELEMENT_NODE) { String s2 = n1.getNodeName(); if(s1.equals (s2)) retvar = true; openNode (s1); } else { retvar = false; } return retvar; } private boolean closeIfNodeNamed (Node n1, String s1) { boolean retvar = false; if (n1.getNodeType() == Node.ELEMENT_NODE) { String s2 = n1.getNodeName(); if(s1.equals (s2)) retvar = true; closeNode (); } else { retvar = false; } return retvar; } protected boolean IsAGSTable(String xml_tname){ return IsAGSTable(xml_tname,null); } protected boolean IsAGSTable(String xml_tname, String IgnoreTables){ try { if (IgnoreTables != null) { String[] tokens = IgnoreTables.split(";"); for(String token: tokens){ if (xml_tname == token) { return false; } } } return (m_dic.find_tableXML(xml_tname) != null); } catch (Exception e) { return false; } } //protected boolean AddXMLHeader(Row r, String tname1, AGS_Dictionary.Lang lang) { // try { // // List<String> l; // Iterator it; // String fname1; // String fname2; // boolean TableFound = false; // boolean FieldFound = false; // // l = new ArrayList<String>(); // it = header1.iterator(); // // TableFound = (m_dic.find_table(tname1, lang) != null ); // // do { // fname1 = it.next().toString(); // fname2 = fname1; // if (TableFound) { // FieldFound = (m_dic.find_field(fname1, lang) != null); // if (FieldFound) { // fname2 = m_dic.fieldXML_name(); // } else { // fname2 = m_dic.format_XMLTry(lang); // } // } // // l.add(fname2); // } while(it.hasNext()); // // return l; // } // catch (Exception e) { //// log(Level.SEVERE, e.getMessage()); // return null; // } //} protected List<String> convertHeaderXML(Collection header1, String tname1, agsml.Constants.Lang lang) { try { List<String> l; Iterator it; String fname1; String fname2; boolean foundTable; l = new ArrayList<String>(); it = header1.iterator(); foundTable = (m_dic.find_table(tname1, lang) != null); do { fname1 = it.next().toString(); fname2 = ""; if (foundTable && m_dic.find_field(fname1, lang) != null) { fname2 = m_dic.fieldXML_name(); } else { fname2 = m_dic.format_XMLTry(tname1, fname1); } l.add(fname2); } while(it.hasNext()); return l; } catch (Exception e) { // log(Level.SEVERE, e.getMessage()); return null; } } protected int addTable(String xml_tname, String xml_fname, String fvalue) { return -1; } protected int addHoles(Node n1){ return -1; } protected int processQueryNode(Node n1) { return -1; } protected int processKMLNode( Node n1) { return -1; } }
26.789889
272
0.524118
44192df9858b4a8faa0f2f1037b95c896908f20d
4,218
import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import java.io.ByteArrayOutputStream; public class DSG extends View { public boolean isSignatureDone; private Bitmap _Bitmap; private Canvas _Canvas; private Path _Path; private Paint _BitmapPaint; private Paint _paint; private float _mX; private float _mY; private float TouchTolerance = 4; private float LineThickness = 4; private Sign sign; public int canvasColor = Color.TRANSPARENT; public DSG(Context context, AttributeSet attr) { super(context, attr); _Path = new Path(); _BitmapPaint = new Paint(Paint.DITHER_FLAG); _paint = new Paint(); _paint.setAntiAlias(true); _paint.setDither(true); _paint.setColor(Color.argb(255, 0, 0, 0)); _paint.setStyle(Paint.Style.STROKE); _paint.setStrokeJoin(Paint.Join.ROUND); _paint.setStrokeCap(Paint.Cap.ROUND); _paint.setStrokeWidth(LineThickness); sign = new Sign() { @Override public void userTouch() { } @Override public void clearSign() { } }; } public void setListener(Sign listener) { if (listener != null) this.sign = listener; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); _Bitmap = Bitmap.createBitmap(w, (h > 0 ? h : ((View) this.getParent()).getHeight()), Bitmap.Config.ARGB_8888); _Canvas = new Canvas(_Bitmap); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawColor(canvasColor); canvas.drawBitmap(_Bitmap, 0, 0, _BitmapPaint); canvas.drawPath(_Path, _paint); } private void TouchStart(float x, float y) { _Path.reset(); _Path.moveTo(x, y); _mX = x; _mY = y; isSignatureDone = true; sign.userTouch(); } private void TouchMove(float x, float y) { float dx = Math.abs(x - _mX); float dy = Math.abs(y - _mY); if (dx >= TouchTolerance || dy >= TouchTolerance) { _Path.quadTo(_mX, _mY, (x + _mX) / 2, (y + _mY) / 2); _mX = x; _mY = y; } } private void TouchUp() { if (!_Path.isEmpty()) { _Path.lineTo(_mX, _mY); _Canvas.drawPath(_Path, _paint); } else { _Canvas.drawPoint(_mX, _mY, _paint); } _Path.reset(); } @Override public boolean onTouchEvent(MotionEvent e) { super.onTouchEvent(e); float x = e.getX(); float y = e.getY(); switch (e.getAction()) { case MotionEvent.ACTION_DOWN: TouchStart(x, y); invalidate(); break; case MotionEvent.ACTION_MOVE: TouchMove(x, y); invalidate(); break; case MotionEvent.ACTION_UP: TouchUp(); invalidate(); break; } return true; } public void ClearCanvas() { _Canvas.drawColor(Color.TRANSPARENT); isSignatureDone = false; sign.clearSign(); invalidate(); } public byte[] getBytes() { Bitmap b = getBitmap(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); b.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); } public Bitmap getBitmap() { View v = (View) this.getParent(); Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888); Canvas c = new Canvas(b); v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom()); v.draw(c); return b; } public interface Sign { void userTouch(); void clearSign(); } }
26.198758
119
0.568516
630f1d4e9cacf4143d0d843c8468593d86a62468
287
package ec.com.tnb.mibus.ui.main; import java.util.List; import ec.com.tnb.mibus.data.model.Ribot; import ec.com.tnb.mibus.ui.base.MvpView; public interface MainMvpView extends MvpView { void showRibots(List<Ribot> ribots); void showRibotsEmpty(); void showError(); }
16.882353
46
0.731707
2c3c7496a572db87a7a27a119aad340d28a37bee
313
package com.ats.kbsearch.data; import com.ats.kbsearch.domains.Topic; import java.util.List; import java.util.Set; /** * Created by amit on 5/15/17. */ public interface Data { Set<String> getDictionary(); Set<String> getIgnoreWords(); Set<Set> getContextMap(); List<Topic> getAllTopics(); }
17.388889
38
0.690096
3872ba76b39f14b8ee04eecd360b8026b1c14367
6,296
/* * JBoss, Home of Professional Open Source * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual contributors. * * 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.switchyard.quickstarts.demos.helpdesk; import static org.switchyard.quickstarts.demos.helpdesk.HelpDeskUserGroupCallback.USERS_GROUPS; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import javax.faces.event.ValueChangeEvent; import javax.xml.namespace.QName; import org.apache.log4j.Logger; import org.kie.api.task.model.TaskSummary; import org.switchyard.component.bpm.runtime.BPMTaskService; import org.switchyard.component.bpm.runtime.BPMTaskServiceRegistry; /** * The Class HelpDesk. * * @author David Ward &lt;<a * href="mailto:dward@jboss.org">dward@jboss.org</a>&gt; &copy; 2012 Red * Hat Inc. */ @ManagedBean(name = "helpDesk") @SessionScoped public class HelpDesk { /** The Constant LOGGER. */ private static final Logger LOGGER = Logger.getLogger(HelpDesk.class); /** The Constant TICKET. */ private static final String TICKET = "ticket"; /** The Constant EN_UK. */ private static final String EN_UK = "en-UK"; /** The _task service. */ private final BPMTaskService _taskService; /** The _user tasks. */ private final List<TaskSummary> _userTasks; /** The _user tickets. */ private final Map<Long, Ticket> _userTickets; /** The _user id. */ private String _userId = "krisv"; /** * Instantiates a new help desk. */ public HelpDesk() { _taskService = BPMTaskServiceRegistry.getTaskService(new QName(null, "helpdesk"), new QName( "urn:switchyard-quickstart-demo:helpdesk:0.1.0", "HelpDeskService")); _userTasks = Collections.synchronizedList(new ArrayList<TaskSummary>()); _userTickets = Collections.synchronizedMap(new LinkedHashMap<Long, Ticket>()); } /** * Gets the user id. * * @return the user id */ public String getUserId() { return _userId; } /** * Sets the user id. * * @param userId the new user id */ public void setUserId(String userId) { _userId = userId; } /** * Gets the group id. * * @return the group id */ public String getGroupId() { List<String> groups = USERS_GROUPS.get(_userId); return (groups != null && groups.size() > 0) ? groups.get(0) : null; } /** * Gets the users groups. * * @return the users groups */ public Map<String, String> getUsersGroups() { Map<String, String> usersGroups = new LinkedHashMap<String, String>(); for (Map.Entry<String, List<String>> entry : USERS_GROUPS.entrySet()) { String key = entry.getKey(); usersGroups.put(key + " (" + entry.getValue().get(0) + ")", key); } return usersGroups; } /** * Gets the user tasks. * * @return the user tasks */ public List<TaskSummary> getUserTasks() { return _userTasks; } /** * Gets the user tickets. * * @return the user tickets */ public Map<Long, Ticket> getUserTickets() { return _userTickets; } /** * Select user. * * @param vce the vce */ public void selectUser(ValueChangeEvent vce) { setUserId((String) vce.getNewValue()); fetchTasks(); } /** * Fetch tasks. */ private void fetchTasks() { synchronized (_userTasks) { _userTasks.clear(); _userTickets.clear(); List<TaskSummary> tasks = _taskService.getTasksAssignedAsPotentialOwner(_userId, EN_UK); for (TaskSummary task : tasks) { _userTasks.add(task); Map<String, Object> params = _taskService.getTaskContent(task.getId()); Ticket ticket = (Ticket) params.get(TICKET); _userTickets.put(task.getProcessInstanceId(), ticket); } } } /** * Complete tasks. */ private void completeTasks() { synchronized (_userTasks) { if (_userTasks.size() > 0) { for (TaskSummary task : _userTasks) { _taskService.claim(task.getId(), _userId); _taskService.start(task.getId(), _userId); Map<String, Object> results = new HashMap<String, Object>(); Ticket ticket = _userTickets.get(task.getProcessInstanceId()); results.put(TICKET, ticket); _taskService.complete(task.getId(), _userId, results); } } } } /** * Submit. */ public void submit() { try { completeTasks(); fetchTasks(); } catch (Throwable t) { StringBuilder sb = new StringBuilder(); sb.append("Problem processing tasks: "); sb.append(t.getClass().getName()); String m = t.getMessage(); if (m != null) { sb.append("("); sb.append(m); sb.append(")"); } String msg = sb.toString(); LOGGER.error(msg, t); FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(msg)); } } }
29.698113
100
0.603875
7449a01001efa960ba5c8911108cb291a8f7af18
120
package org.chess.core.domain; public interface IMouvement { Position getPosition(); boolean isAttaque(); }
12
30
0.708333
c534f160051a86f3ecaca42c3c48f310e94ff5ad
3,026
package extenreports; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.Assert; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.relevantcodes.extentreports.ExtentReports; import com.relevantcodes.extentreports.ExtentTest; import com.relevantcodes.extentreports.LogStatus; import utilities.Screenshots; public class LoginTestWithScreenshot { private WebDriver driver; private String baseUrl; ExtentReports report; ExtentTest test; @BeforeClass public void beforeClass() { baseUrl = "http://www.letskodeit.com/"; report = new ExtentReports("//Users//atomar//Desktop//logintest.html"); test = report.startTest("Verify Welcome Text"); driver = new FirefoxDriver(); test.log(LogStatus.INFO, "Browser Started..."); // Maximize the browser's window driver.manage().window().maximize(); test.log(LogStatus.INFO, "Browser Maximized"); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get(baseUrl); test.log(LogStatus.INFO, "Web application opened"); } @Test public void test1_validLoginTest() throws Exception { WebElement signupLink = driver.findElement(By.id("comp-iiqg1vggactionTitle")); signupLink.click(); test.log(LogStatus.INFO, "Clicked on signup link"); WebElement loginLink = driver.findElement(By.id("signUpDialogswitchDialogLink")); loginLink.click(); test.log(LogStatus.INFO, "Clicked on login link"); WebElement emailField = driver.findElement(By.xpath("//div[@id='memberLoginDialogemail']//input")); emailField.sendKeys("test1@email.com"); test.log(LogStatus.INFO, "Enter email"); WebElement passwordField = driver.findElement(By.xpath("//div[@id='memberLoginDialogpassword']//input")); passwordField.sendKeys("abcabc"); test.log(LogStatus.INFO, "Enter password"); WebElement goButton = driver.findElement(By.id("memberLoginDialogsubmitButton")); goButton.click(); test.log(LogStatus.INFO, "Clicked Go button"); Thread.sleep(3000); WebElement welcomeText = null; try { welcomeText = driver.findElement(By.xpath("//div[text()='Hello test@email.com']")); } catch (NoSuchElementException e) { System.out.println(e.getMessage()); } Assert.assertTrue(welcomeText != null); test.log(LogStatus.PASS, "Verified Welcome Text"); } @AfterMethod public void tearDown(ITestResult testResult) throws IOException { if (testResult.getStatus() == ITestResult.FAILURE) { String path = Screenshots.takeScreenshot(driver, testResult.getName()); String imagePath = test.addScreenCapture(path); test.log(LogStatus.FAIL, "Verify Welcome Text Failed", imagePath); } driver.quit(); report.endTest(test); report.flush(); } }
32.537634
107
0.751818
8d6444573fa7fd98c45286209f68b698c013cd3c
2,414
/* * 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.selenium2.webclient.ui; import javax.swing.Action; import org.netbeans.api.project.Project; import org.netbeans.modules.gsf.testrunner.api.Testcase; import org.netbeans.modules.gsf.testrunner.api.Trouble; import org.netbeans.modules.gsf.testrunner.ui.api.TestMethodNode; import org.netbeans.modules.selenium2.webclient.spi.JumpToCallStackCallback; /** * * @author Theofanis Oikonomou */ public class SeleniumTestMethodNode extends TestMethodNode { private final JumpToCallStackCallback callback; public SeleniumTestMethodNode(Testcase testcase, Project project, JumpToCallStackCallback callback) { super(testcase, project); this.callback = callback; } @Override public Action[] getActions(boolean context) { Action[] defaultActions = super.getActions(context); Action preferredAction = getPreferredAction(); if(preferredAction == null) { return defaultActions; } Action[] actions = new Action[defaultActions.length + 1]; actions[0] = preferredAction; System.arraycopy(defaultActions, 0, actions, 1, defaultActions.length); return actions; } @Override public Action getPreferredAction() { Trouble trouble = testcase.getTrouble(); if(trouble != null) { String[] stackTraces = trouble.getStackTrace(); if(stackTraces != null && stackTraces.length > 0) { return new JumpToCallStackAction(stackTraces, callback); } } return super.getPreferredAction(); } }
36.029851
105
0.709611
accb2facd653ac44c92542b788b6d99089107820
50,595
package com.miniorange.oauth.bamboo; import java.io.IOException; import java.util.*; import com.miniorange.oauth.utils.MoOAuthHttpUtils; import com.atlassian.bamboo.util.BuildUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.atlassian.bamboo.configuration.AdministrationConfigurationAccessor; import com.atlassian.sal.api.pluginsettings.PluginSettings; import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory; import com.atlassian.upm.api.license.PluginLicenseManager; import com.atlassian.upm.api.license.entity.PluginLicense; import com.atlassian.user.Group; import com.atlassian.user.search.page.Pager; import com.atlassian.bamboo.user.BambooUserManager; import com.atlassian.plugin.PluginAccessor; import com.atlassian.plugin.Plugin; import javax.servlet.http.HttpServletRequest; import com.atlassian.bamboo.security.BambooPermissionManager; public class MoOAuthSettings { private static Log LOGGER = LogFactory.getLog(MoOAuthSettings.class); private PluginSettings pluginSettings; private PluginSettingsFactory pluginSettingsFactory; private PluginLicenseManager pluginLicenseManager; private AdministrationConfigurationAccessor administrationConfigurationAccessor; private BambooUserManager bambooUserManager; private PluginAccessor pluginAccessor; private BambooPermissionManager bambooPermissionManager; public static String LOGIN_TEMPLATE = ""; private static String LOGOUT_TEMPLATE = ""; private static String ERRORMSG_TEMPLATE = ""; static{ try{ final String ERRORMSG_TEMPLATE_PATH = "/templates/errorMsgTemplate.ftl"; ERRORMSG_TEMPLATE = IOUtils.toString(MoOAuthSettings.class.getResourceAsStream(ERRORMSG_TEMPLATE_PATH), "UTF-8"); final String LOGIN_TEMPLATE_PATH = "/templates/loginTemplate.ftl"; final String LOGOUT_TEMPLATE_PATH = "/templates/logoutTemplate.ftl"; LOGIN_TEMPLATE = IOUtils.toString(MoOAuthSettings.class.getResourceAsStream(LOGIN_TEMPLATE_PATH), "UTF-8"); LOGOUT_TEMPLATE = IOUtils.toString(MoOAuthSettings.class.getResourceAsStream(LOGOUT_TEMPLATE_PATH), "UTF-8"); } catch (IOException e) { LOGGER.error("An I/O error occurred while initializing the Settings.", e); } } public static Boolean isPluginConfigurationFileUploaded = Boolean.FALSE; public MoOAuthSettings(PluginLicenseManager pluginLicenseManager, PluginSettingsFactory pluginSettingsFactory, AdministrationConfigurationAccessor administrationConfigurationAccessor, BambooUserManager bambooUserManager, PluginAccessor pluginAccessor, BambooPermissionManager bambooPermissionManager) { super(); this.pluginSettings = pluginSettingsFactory.createGlobalSettings(); this.pluginSettingsFactory = pluginSettingsFactory; this.pluginLicenseManager = pluginLicenseManager; this.administrationConfigurationAccessor = administrationConfigurationAccessor; this.bambooUserManager = bambooUserManager; this.pluginAccessor = pluginAccessor; this.bambooPermissionManager = bambooPermissionManager; } public String getCallBackUrl() { return getBaseUrl().concat("/plugins/servlet/oauth/callback"); } public String getCreateUserUrl(){ return getBaseUrl().concat("/plugins/servlet/oauth/createuser");} public Boolean isLicenseDefine(){ if (pluginLicenseManager.getLicense().isDefined()) { return true; } return false; } public Boolean isEvaluationOrSubscriptionLicense() { if (!isLicenseValid()) { PluginLicense pluginLicense = pluginLicenseManager.getLicense().get(); if (pluginLicense.isEvaluation() || pluginLicense.isSubscription()) { return Boolean.TRUE; } } return Boolean.FALSE; } public String getBaseUrl() { String baseURL = administrationConfigurationAccessor.getAdministrationConfiguration().getBaseUrl(); return baseURL; } public String getLoginPageUrl() { return getBaseUrl().concat("/userlogin!doDefault.action"); } public String getAdminSessionUrl() { return getBaseUrl().concat("/authenticate"); } public String getLogoutPageUrl() { return getBaseUrl().concat("?logout=true"); } public String getDashboardUrl() { return getBaseUrl().concat("/"); } public int getMaxUsers() { int t = 0; try { if (pluginLicenseManager.getLicense().isDefined()) { t = pluginLicenseManager.getLicense().get().getEdition().get(); } } catch (Exception e) { return -1; } return t; } public Boolean isLicenseValid() { if (pluginLicenseManager.getLicense().isDefined()) { if((!(pluginLicenseManager.getLicense().get().isValid())) || (pluginLicenseManager.getLicense().get().getError().isDefined())){ LOGGER.debug("Invalid License"); return Boolean.FALSE; } } return Boolean.TRUE; } public String getManageAddOnURL() { return getBaseUrl().concat("/plugins/servlet/upm"); } public static String generateRandomAlphaNumericKey(int bytes) { String randomString = RandomStringUtils.random(bytes, true, true); return randomString; } public boolean isVerifyCredentialsInUse(HttpServletRequest request) { return MoOAuthHttpUtils.getCookie("verify_credentials_in_use",request) != null; } public boolean isTestIDPConfigurationInUse(HttpServletRequest request) { return MoOAuthHttpUtils.getCookie("test_configuration_in_use",request) != null; } public void setBambooUserManager(BambooUserManager bambooUserManager) { this.bambooUserManager = bambooUserManager; } public Integer getCurrentBuildNumber() { String buildNumber = BuildUtils.getCurrentBuildNumber(); return Integer.parseInt(buildNumber); } public Boolean isLowerBuild(){ if(getCurrentBuildNumber() < 60604){ return true; } return false; } public String getImportExportPageUrl() { return getBaseUrl().concat("/plugins/servlet/bamboo-oauth/importexport.action"); } //OAuth Provider Configurations public String getCustomAppName() { String appName = StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.OAuthConfiguration.CUSTOM_APP_NAME.getKey()), StringUtils.EMPTY); return appName; } public void setCustomAppName(String customAppName) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.CUSTOM_APP_NAME.getKey(), StringUtils.trimToEmpty(StringUtils .defaultIfBlank(customAppName, StringUtils.EMPTY))); } public Boolean getRememberMeCookieEnabled() { return BooleanUtils.toBooleanDefaultIfNull( BooleanUtils.toBoolean((String) this.pluginSettings.get(MoOAuthPluginConstants.REMEMBERME_COOKIE)), false); } public void setRememberMeCookieEnabled(Boolean isRememberMeCookieEnabled) { LOGGER.debug("is cookie enabled?:" + isRememberMeCookieEnabled); this.pluginSettings.put(MoOAuthPluginConstants.REMEMBERME_COOKIE, BooleanUtils.toString(isRememberMeCookieEnabled, "true", "false", "false")); } public String getAppName() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.OAuthConfiguration.DEFAULT_APP_NAME.getKey()), StringUtils.EMPTY); } public String getAppHostedOn(){ return StringUtils.defaultIfBlank((String)this.pluginSettings.get(MoOAuthPluginConstants.OAuthConfiguration.APP_HOSTED_ON.getKey()), MoOAuthPluginConstants.CLOUD_HOSTING); } public void setAppHostedOn(String appHostedOn){ this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.APP_HOSTED_ON.getKey(), StringUtils.trimToEmpty(StringUtils.defaultIfBlank(appHostedOn, MoOAuthPluginConstants.CLOUD_HOSTING))); } public void setAppName(String appName) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.DEFAULT_APP_NAME.getKey(), StringUtils.trimToEmpty(StringUtils .defaultIfBlank(appName, StringUtils.EMPTY))); } public String getClientID() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.OAuthConfiguration.CLIENT_ID.getKey()), StringUtils.EMPTY); } public void setClientID(String clientID) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.CLIENT_ID.getKey(), StringUtils.trimToEmpty(StringUtils .defaultIfBlank(clientID, StringUtils.EMPTY))); } public String getClientSecret() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.OAuthConfiguration.CLIENT_SECRET.getKey()), StringUtils.EMPTY); } public void setClientSecret(String clientSecret) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.CLIENT_SECRET.getKey(), StringUtils.trimToEmpty(StringUtils .defaultIfBlank(clientSecret, StringUtils.EMPTY))); } public void setCustomizableCallbackURL(String customizableCallbackURL) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.CUSTOMIZABLE_CALLBACK_URL.getKey(), StringUtils.trimToEmpty(StringUtils .defaultIfBlank(customizableCallbackURL, StringUtils.EMPTY))); } public String getCustomizableCallbackURL() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.OAuthConfiguration.CUSTOMIZABLE_CALLBACK_URL.getKey()), StringUtils.EMPTY); } public String getScope() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.OAuthConfiguration.SCOPE.getKey()), StringUtils.EMPTY); } public void setScope(String scope) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.SCOPE.getKey(), StringUtils.trimToEmpty(StringUtils .defaultIfBlank(scope, StringUtils.EMPTY))); } public String getAuthorizeEndpoint() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.OAuthConfiguration.AUTHORIZE_END_POINT.getKey()), StringUtils.EMPTY); } public void setAuthorizeEndpoint(String authorizeEndpoint) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.AUTHORIZE_END_POINT.getKey(), StringUtils.trimToEmpty(StringUtils .defaultIfBlank(authorizeEndpoint, StringUtils.EMPTY))); } public String getAccessTokenEndpoint() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.OAuthConfiguration.ACCESS_TOKEN_END_POINT.getKey()), StringUtils.EMPTY); } public void setAccessTokenEndpoint(String accessTokenEndpoint) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.ACCESS_TOKEN_END_POINT.getKey(), StringUtils.trimToEmpty(StringUtils .defaultIfBlank(accessTokenEndpoint, StringUtils.EMPTY))); } public String getUserInfoEndpoint() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.OAuthConfiguration.USER_INFO_END_POINT.getKey()), StringUtils.EMPTY); } public void setUserInfoEndpoint(String userInfoEndpoint) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.USER_INFO_END_POINT.getKey(), StringUtils.trimToEmpty(StringUtils .defaultIfBlank(userInfoEndpoint, StringUtils.EMPTY))); } public String getFetchGroupsEndpoint() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.OAuthConfiguration.FETCH_GROUPS_ENDPOINT.getKey()), StringUtils.EMPTY); } public void setOauth_request_parameters(HashMap<String, String> oauth_request_parameters) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.OAUTH_REQUEST_PARAMETERS.getKey(), oauth_request_parameters); } public HashMap<String, String> getOauth_request_parameters() { Object oauth_request_parameters = this.pluginSettings.get(MoOAuthPluginConstants.OAuthConfiguration.OAUTH_REQUEST_PARAMETERS.getKey()); if (oauth_request_parameters != null) { return (HashMap) oauth_request_parameters; } return new HashMap<String, String>(); } public void setFetchGroupsEndpoint(String groupApi) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.FETCH_GROUPS_ENDPOINT.getKey(), StringUtils.trimToEmpty(StringUtils.defaultIfBlank(groupApi, StringUtils.EMPTY))); } public void setDomainName(String domainName) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.DOMAIN_NAME.getKey(), StringUtils.trimToEmpty(StringUtils.defaultIfBlank(domainName, StringUtils.EMPTY))); } public String getDomainName() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.OAuthConfiguration.DOMAIN_NAME.getKey()), StringUtils.EMPTY); } public void setHostName(String hostName) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.HOST_NAME.getKey(), StringUtils.trimToEmpty(StringUtils.defaultIfBlank(hostName, StringUtils.EMPTY))); } public String getHostName() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.OAuthConfiguration.HOST_NAME.getKey()), StringUtils.EMPTY); } public void setRealmName(String realmName) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.REALM_NAME.getKey(), StringUtils.trimToEmpty(StringUtils.defaultIfBlank(realmName, StringUtils.EMPTY))); } public String getRealmName() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.OAuthConfiguration.REALM_NAME.getKey()), StringUtils.EMPTY); } public Boolean getUseStateParameter() { return BooleanUtils.toBooleanDefaultIfNull(BooleanUtils.toBoolean((String) this.pluginSettings.get (MoOAuthPluginConstants.OAuthConfiguration.USE_STATE_PARAMETER.getKey())), false); } public void setUseStateParameter(Boolean useStateParameter) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.USE_STATE_PARAMETER.getKey(), BooleanUtils.toString(useStateParameter, "true", "false", "false")); } public String getCheckIssuerFor() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.OAuthConfiguration.CHECK_ISSUER_FOR.getKey()), "Default"); } public void setCheckIssuerFor(String checkIssuerFor) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.CHECK_ISSUER_FOR.getKey(), StringUtils.trimToEmpty(StringUtils.defaultIfBlank(checkIssuerFor, "Default"))); } public String getCustomIssuerValue() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.OAuthConfiguration.CUSTOM_ISSUER_VALUE.getKey()), StringUtils.EMPTY); } public void setCustomIssuerValue(String customIssuerValue) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.CUSTOM_ISSUER_VALUE.getKey(), StringUtils.trimToEmpty(StringUtils.defaultIfBlank(customIssuerValue, StringUtils.EMPTY))); } public Boolean getEnableCheckIssuerFor() { return BooleanUtils.toBooleanDefaultIfNull(BooleanUtils .toBoolean((String) this.pluginSettings.get(MoOAuthPluginConstants.OAuthConfiguration.ENABLE_CHECK_ISSUER_FOR.getKey())), false); } public void setEnableCheckIssuerFor(Boolean enableCheckIssuerFor) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.ENABLE_CHECK_ISSUER_FOR.getKey(), BooleanUtils.toString(enableCheckIssuerFor, "true", "false", "false")); } public String getGoogleRefreshToken() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.GOOGLE_REFRESH_TOKEN), StringUtils.EMPTY); } public void setGoogleRefreshToken(String refreshToken) { this.pluginSettings.put(MoOAuthPluginConstants.GOOGLE_REFRESH_TOKEN, StringUtils.trimToEmpty(StringUtils.defaultIfBlank(refreshToken, StringUtils.EMPTY))); } public Boolean getResetSettings() { return BooleanUtils.toBooleanDefaultIfNull( BooleanUtils.toBoolean((String) this.pluginSettings.get(MoOAuthPluginConstants.RESET_SETTINGS)), false); } public void setResetSettings(Boolean resetSettings) { this.pluginSettings.put(MoOAuthPluginConstants.RESET_SETTINGS, BooleanUtils.toString(resetSettings, "true", "false", "false")); } public Boolean getIsTestIDPConfigurationClicked() { String isTestIDPConfigurationClicked = (String) this.pluginSettings.get(MoOAuthPluginConstants.IS_TEST_CONFIGURATION_CLICKED); if (BooleanUtils.toBoolean(isTestIDPConfigurationClicked)) { return Boolean.TRUE; } else { return Boolean.FALSE; } } public void setIsTestIDPConfigurationClicked(Boolean isTestIDPConfigurationClicked) { this.pluginSettings.put(MoOAuthPluginConstants.IS_TEST_CONFIGURATION_CLICKED, BooleanUtils.toString(isTestIDPConfigurationClicked, "true", "false", "false")); } public Boolean getIsVerifyCredentialsClicked() { String isVerifyCredentialsClicked = (String) this.pluginSettings.get(MoOAuthPluginConstants.IS_VERIFY_CREDENTIALS_CLICKED); if (BooleanUtils.toBoolean(isVerifyCredentialsClicked)) { return Boolean.TRUE; } else { return Boolean.FALSE; } } public void setIsVerifyCredentialsClicked(Boolean isVerifyCredentialsClicked) { this.pluginSettings.put(MoOAuthPluginConstants.IS_VERIFY_CREDENTIALS_CLICKED, BooleanUtils.toString(isVerifyCredentialsClicked, "true", "false", "false")); } public Boolean getIsCredentialsVerified() { return BooleanUtils.toBooleanDefaultIfNull(BooleanUtils .toBoolean((String) this.pluginSettings.get(MoOAuthPluginConstants.IS_CREDENTIALS_VERIFIED)), false); } public void setIsCredentialsVerified(Boolean isCredentialsVerified) { this.pluginSettings.put(MoOAuthPluginConstants.IS_CREDENTIALS_VERIFIED, BooleanUtils.toString(isCredentialsVerified, "true", "false", "false")); } //Attribute Mapping public Boolean getKeepExistingUserAttributes() { if(this.pluginSettings.get(MoOAuthPluginConstants.AttributeMapping.DISABLE_ATTRIBUTE_MAPPING.getKey())==null) return true; return BooleanUtils.toBooleanDefaultIfNull(BooleanUtils .toBoolean((String) this.pluginSettings.get(MoOAuthPluginConstants.AttributeMapping.DISABLE_ATTRIBUTE_MAPPING.getKey())), true); } public void setKeepExistingUserAttributes(Boolean keepExistingUserAttributes) { this.pluginSettings.put(MoOAuthPluginConstants.AttributeMapping.DISABLE_ATTRIBUTE_MAPPING.getKey(), BooleanUtils.toString(keepExistingUserAttributes, "true", "false", "false")); } public void setLoginUserAttribute(String loginUserAttribute) { this.pluginSettings.put(MoOAuthPluginConstants.AttributeMapping.LOGIN_USER_BY_ATTRIBUTE.getKey(), StringUtils.trimToEmpty(StringUtils.defaultIfBlank(loginUserAttribute, "username"))); } public String getLoginUserAttribute() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.AttributeMapping.LOGIN_USER_BY_ATTRIBUTE.getKey()), "username"); } public String getUsernameAttribute() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.AttributeMapping.USERNAME_ATTRIBUTE.getKey()), StringUtils.EMPTY); } public void setUsernameAttribute(String usernameAttribute) { this.pluginSettings.put(MoOAuthPluginConstants.AttributeMapping.USERNAME_ATTRIBUTE.getKey(), StringUtils.trimToEmpty(StringUtils.defaultIfBlank(usernameAttribute, StringUtils.EMPTY))); } public Boolean getRegexPatternEnabled() { return BooleanUtils.toBooleanDefaultIfNull( BooleanUtils.toBoolean((String) this.pluginSettings.get(MoOAuthPluginConstants.AttributeMapping.ENABLE_REGEX_PATTERN.getKey())), false); } public void setRegexPatternEnabled(Boolean regexPatternEnabled) { this.pluginSettings.put(MoOAuthPluginConstants.AttributeMapping.ENABLE_REGEX_PATTERN.getKey(), BooleanUtils.toString(regexPatternEnabled, "true", "false", "false")); } public String getRegexPattern() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.AttributeMapping.REGEX_PATTERN.getKey()), ""); } public void setRegexPattern(String regexPattern) { this.pluginSettings.put(MoOAuthPluginConstants.AttributeMapping.REGEX_PATTERN.getKey(), StringUtils.trimToEmpty(StringUtils.defaultIfBlank(regexPattern, ""))); } public String getEmailAttribute() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.AttributeMapping.EMAIL_ATTRIBUTE.getKey()), StringUtils.EMPTY); } public void setEmailAttribute(String emailAttribute) { this.pluginSettings.put(MoOAuthPluginConstants.AttributeMapping.EMAIL_ATTRIBUTE.getKey(), StringUtils.trimToEmpty(StringUtils.defaultIfBlank(emailAttribute, StringUtils.EMPTY))); } public String getFullNameAttribute() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.AttributeMapping.FULL_NAME_ATTRIBUTE.getKey()), StringUtils.EMPTY); } public void setFullNameAttribute(String fullNameAttribute) { this.pluginSettings.put(MoOAuthPluginConstants.AttributeMapping.FULL_NAME_ATTRIBUTE.getKey(), StringUtils.trimToEmpty(StringUtils.defaultIfBlank(fullNameAttribute, StringUtils.EMPTY))); } public Boolean getUseSeparateNameAttributes() { return BooleanUtils.toBooleanDefaultIfNull( BooleanUtils.toBoolean((String) this.pluginSettings.get(MoOAuthPluginConstants.AttributeMapping.USE_SEPARATE_NAME_ATTRIBUTE.getKey())), false); } public void setUseSeparateNameAttributes(Boolean useSeparateNameAttributes) { this.pluginSettings.put(MoOAuthPluginConstants.AttributeMapping.USE_SEPARATE_NAME_ATTRIBUTE.getKey(), BooleanUtils.toString(useSeparateNameAttributes, "true", "false", "false")); } public String getFirstNameAttribute() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.AttributeMapping.FIRST_NAME_ATTRIBUTE.getKey()), StringUtils.EMPTY); } public void setFirstNameAttribute(String firstNameAttribute) { this.pluginSettings.put(MoOAuthPluginConstants.AttributeMapping.FIRST_NAME_ATTRIBUTE.getKey(), StringUtils.trimToEmpty(StringUtils.defaultIfBlank(firstNameAttribute, StringUtils.EMPTY))); } public String getLastNameAttribute() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.AttributeMapping.LAST_NAME_ATTRIBUTE.getKey()), StringUtils.EMPTY); } public void setLastNameAttribute(String lastNameAttribute) { this.pluginSettings.put(MoOAuthPluginConstants.AttributeMapping.LAST_NAME_ATTRIBUTE.getKey(), StringUtils.trimToEmpty(StringUtils.defaultIfBlank(lastNameAttribute, StringUtils.EMPTY))); } //Group Mapping public void setRestrictUserCreation(Boolean restrictUserCreation) { this.pluginSettings .put(MoOAuthPluginConstants.GroupMapping.DISABLE_USER_CREATION.getKey(), BooleanUtils.toString(restrictUserCreation, "true", "false", "false")); } public Boolean getRestrictUserCreation() { return BooleanUtils.toBooleanDefaultIfNull(BooleanUtils.toBoolean((String) this.pluginSettings.get (MoOAuthPluginConstants.GroupMapping.DISABLE_USER_CREATION.getKey())), false); } public String getDefaultGroup() { // LOGGER.info("OAuth Settings getDefaultGroup Called.."); String defaultGroup = (String)this.pluginSettings.get(MoOAuthPluginConstants.GroupMapping.DEFAULT_GROUP.getKey()); if(StringUtils.isBlank(defaultGroup)) { defaultGroup = StringUtils.EMPTY; List<String> existingGroups = new ArrayList(); Pager groupObjects = bambooUserManager.getGroups(); Iterator<Group> itr = groupObjects.iterator(); while (itr.hasNext()) { Group group = itr.next(); existingGroups.add(group.getName()); } if (existingGroups.contains(bambooPermissionManager.getDefaultUsersGroup())) { defaultGroup = bambooPermissionManager.getDefaultUsersGroup(); } else { if (existingGroups.size() > 1) defaultGroup = existingGroups.get(1); else defaultGroup = existingGroups.get(0); } LOGGER.debug("Default Group is " + defaultGroup); } return StringUtils.defaultString(defaultGroup,StringUtils.EMPTY); } public void setDefaultGroup(String defaultGroup) { this.pluginSettings.put(MoOAuthPluginConstants.GroupMapping.DEFAULT_GROUP.getKey(), StringUtils.trimToEmpty(StringUtils .defaultIfBlank(defaultGroup, "bamboo-admin"))); } public List<String> getDefaultGroupsList() { LOGGER.info("OAuth Settings getDefaultGroupsList Called.."); List<String> defaultGroups = (List<String>)this.pluginSettings.get(MoOAuthPluginConstants.GroupMapping.DEFAULT_GROUPS.getKey()); if((defaultGroups == null) || (defaultGroups.isEmpty())) { defaultGroups = new ArrayList<String>(); ArrayList<Group> existingGroups = new ArrayList<Group>(); Pager groupObjects = bambooUserManager.getGroups(); Iterator<Group> itr = groupObjects.iterator(); while (itr.hasNext()) { Group group = itr.next(); existingGroups.add(group); if (StringUtils.containsIgnoreCase(group.getName(), "bamboo")) defaultGroups.add(group.getName()); } if (defaultGroups.size() == 0) { if (existingGroups.size() > 1) defaultGroups.add(existingGroups.get(1).getName()); else defaultGroups.add(existingGroups.get(0).getName()); } LOGGER.debug("Default Groups are " + defaultGroups.toString()); } return defaultGroups; } public void setDefaultGroupsList(List<String> defaultGroups) { this.pluginSettings.put(MoOAuthPluginConstants.GroupMapping.DEFAULT_GROUPS.getKey(), defaultGroups); } public void setEnableDefaultGroupsFor(String enableDefaultGroupsFor) { this.pluginSettings.put(MoOAuthPluginConstants.GroupMapping.ASSIGN_DEFAULT_GROUP_TO.getKey(), StringUtils .defaultIfEmpty(enableDefaultGroupsFor, MoOAuthPluginConstants.ENABLE_DEFAULT_GROUPS_FOR_NEW_USERS)); } public String getEnableDefaultGroupsFor() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.GroupMapping.ASSIGN_DEFAULT_GROUP_TO.getKey()), MoOAuthPluginConstants.ENABLE_DEFAULT_GROUPS_FOR_NEW_USERS); } public void setOnTheFlyGroupMapping(Boolean createUsersIfRoleMapped) { this.pluginSettings.put(MoOAuthPluginConstants.GroupMapping.ON_THE_FLY_GROUP_MAPPING.getKey(), BooleanUtils.toString(createUsersIfRoleMapped, "true", "false", "false")); } public Boolean getOnTheFlyGroupMapping() { return BooleanUtils.toBooleanDefaultIfNull( BooleanUtils.toBoolean((String) this.pluginSettings.get(MoOAuthPluginConstants.GroupMapping.ON_THE_FLY_GROUP_MAPPING.getKey())), false); } public Boolean getKeepExistingUserRoles() { if(this.pluginSettings.get(MoOAuthPluginConstants.GroupMapping.DISABLE_GROUP_MAPPING.getKey()) == null) return true; return BooleanUtils.toBooleanDefaultIfNull(BooleanUtils.toBoolean((String) this.pluginSettings.get (MoOAuthPluginConstants.GroupMapping.DISABLE_GROUP_MAPPING.getKey())), true); } public void setKeepExistingUserRoles(Boolean keepExistingUserRoles) { this.pluginSettings .put(MoOAuthPluginConstants.GroupMapping.DISABLE_GROUP_MAPPING.getKey(), BooleanUtils.toString(keepExistingUserRoles, "true", "false", "false")); } public String getRoleAttribute() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.GroupMapping .GROUP_ATTRIBUTE.getKey()), StringUtils.EMPTY); } public void setRoleAttribute(String roleAttribute) { this.pluginSettings.put(MoOAuthPluginConstants.GroupMapping.GROUP_ATTRIBUTE.getKey(), StringUtils.trimToEmpty(StringUtils .defaultIfBlank(roleAttribute, StringUtils.EMPTY))); } public String getOnTheFlyFilterIDPGroupsOption() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.GroupMapping .ON_THE_FLY_FILTER_IDP_GROUPS_OPTION.getKey()), MoOAuthPluginConstants.ON_THE_FLY_NO_GROUP_FILTER); } public void setOnTheFlyFilterIDPGroupsOption(String onTheFlyFilterIDPGroupsOption) { this.pluginSettings.put(MoOAuthPluginConstants.GroupMapping.ON_THE_FLY_FILTER_IDP_GROUPS_OPTION.getKey(), StringUtils.trimToEmpty(StringUtils .defaultIfBlank(onTheFlyFilterIDPGroupsOption, MoOAuthPluginConstants.ON_THE_FLY_NO_GROUP_FILTER))); } public String getOnTheFlyFilterIDPGroupsKey() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.GroupMapping .ON_THE_FLY_FILTER_IDP_GROUPS_KEY.getKey()), StringUtils.EMPTY); } public void setOnTheFlyFilterIDPGroupsKey(String onTheFlyFilterIDPGroupsKey) { this.pluginSettings.put(MoOAuthPluginConstants.GroupMapping.ON_THE_FLY_FILTER_IDP_GROUPS_KEY.getKey(), StringUtils.trimToEmpty(StringUtils .defaultIfBlank(onTheFlyFilterIDPGroupsKey, StringUtils.EMPTY))); } public Boolean getCreateUsersIfRoleMapped() { return BooleanUtils.toBooleanDefaultIfNull(BooleanUtils.toBoolean((String) this.pluginSettings.get (MoOAuthPluginConstants.GroupMapping.CREATE_USER_IF_ROLE_MAPPED.getKey())), false); } public void setCreateUsersIfRoleMapped(Boolean createUsersIfRoleMapped) { this.pluginSettings .put(MoOAuthPluginConstants.GroupMapping.CREATE_USER_IF_ROLE_MAPPED.getKey(), BooleanUtils.toString(createUsersIfRoleMapped, "true", "false", "false")); } public void setRoleMapping(HashMap<String, String> roleMapping) { this.pluginSettings.put(MoOAuthPluginConstants.GroupMapping.ROLE_MAPPING.getKey(), roleMapping); } public HashMap<String, String> getRoleMapping() { Object roleMapping = this.pluginSettings.get(MoOAuthPluginConstants.GroupMapping.ROLE_MAPPING.getKey()); if (roleMapping != null) { return (HashMap) roleMapping; } return new HashMap<>(); } public void setOnTheFlyCreateNewGroups(Boolean onTheFlyCreateNewGroups) { this.pluginSettings.put(MoOAuthPluginConstants.GroupMapping.ON_THE_FLY_CREATE_NEW_GROUPS.getKey(), BooleanUtils.toString(onTheFlyCreateNewGroups, "true", "false", "false")); } public Boolean getOnTheFlyCreateNewGroups() { String onTheFlyCreateNewGroups = (String) this.pluginSettings.get(MoOAuthPluginConstants.GroupMapping.ON_THE_FLY_CREATE_NEW_GROUPS.getKey()); if (StringUtils.isBlank(onTheFlyCreateNewGroups)) { return Boolean.TRUE; } else { return BooleanUtils.toBoolean(onTheFlyCreateNewGroups); } } public void setOnTheFlyAssignNewGroupsOnly(Boolean onTheFlyAssignNewGroupsOnly) { this.pluginSettings.put(MoOAuthPluginConstants.GroupMapping.ON_THE_FLY_KEEP_EXISTING_USERS_GROUPS.getKey(), BooleanUtils.toString(onTheFlyAssignNewGroupsOnly, "true", "false", "false")); } public Boolean getOnTheFlyAssignNewGroupsOnly() { String onTheFlyAssignNewGroupsOnly = (String) this.pluginSettings .get(MoOAuthPluginConstants.GroupMapping.ON_THE_FLY_KEEP_EXISTING_USERS_GROUPS.getKey()); if (StringUtils.isBlank(onTheFlyAssignNewGroupsOnly)) { return Boolean.TRUE; } else { return BooleanUtils.toBoolean(onTheFlyAssignNewGroupsOnly); } } public Object getOnTheFlyDoNotRemoveGroups() { if (this.pluginSettings.get(MoOAuthPluginConstants.GroupMapping.ON_THE_FLY_EXCLUDE_GROUPS.getKey()) != null) { return this.pluginSettings.get(MoOAuthPluginConstants.GroupMapping.ON_THE_FLY_EXCLUDE_GROUPS.getKey()); } return new ArrayList<String>(); } public void setOnTheFlyDoNotRemoveGroups(List<String> groups) { this.pluginSettings.put(MoOAuthPluginConstants.GroupMapping.ON_THE_FLY_EXCLUDE_GROUPS.getKey(), groups); } //Sign In Settings public Boolean getDefaultLoginDisabled() { return BooleanUtils.toBoolean((String) this.pluginSettings.get(MoOAuthPluginConstants.SignInSettings.DISABLE_DEFAULT_LOGIN.getKey())); } public void setDefaultLoginDisabled(Boolean defaultLoginDisabled) { this.pluginSettings.put(MoOAuthPluginConstants.SignInSettings.DISABLE_DEFAULT_LOGIN.getKey(), BooleanUtils.toString(defaultLoginDisabled, "true", "false", "false")); } public String getLoginButtonText() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.SignInSettings.LOGIN_BUTTON_TEXT.getKey()), "Use OAuth Login"); } public void setLoginButtonText(String loginButtonText) { this.pluginSettings.put(MoOAuthPluginConstants.SignInSettings.LOGIN_BUTTON_TEXT.getKey(), StringUtils.trimToEmpty(StringUtils .defaultIfBlank(loginButtonText, "Use OAuth Login"))); } public String getSsoButtonLocation() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.SignInSettings.SSO_BUTTON_LOCATION.getKey()), "After Login Button"); } public void setSsoButtonLocation(String ssoButtonLocation) { this.pluginSettings.put(MoOAuthPluginConstants.SignInSettings.SSO_BUTTON_LOCATION.getKey(), StringUtils.trimToEmpty(StringUtils.defaultIfBlank(ssoButtonLocation, "After Login Button"))); } public void setRelayState(String relayState) { this.pluginSettings.put(MoOAuthPluginConstants.SignInSettings.RELAY_STATE.getKey(), StringUtils.trimToEmpty(StringUtils .defaultIfBlank(relayState, StringUtils.EMPTY))); } public String getRelayState( ) { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.SignInSettings.RELAY_STATE.getKey()),StringUtils.EMPTY); } public Boolean getBackdoorEnabled() { return BooleanUtils.toBoolean((String) this.pluginSettings.get(MoOAuthPluginConstants.SignInSettings.ENABLE_BACKDOOR.getKey())); } public void setBackdoorEnabled(Boolean backdoorEnabled) { this.pluginSettings.put(MoOAuthPluginConstants.SignInSettings.ENABLE_BACKDOOR.getKey(), BooleanUtils.toString(backdoorEnabled, "true", "false", "false")); } public Boolean getRestrictBackdoor() { return BooleanUtils.toBoolean((String) this.pluginSettings.get(MoOAuthPluginConstants.SignInSettings.RESTRICT_BACKDOOR.getKey())); } public void setRestrictBackdoor(Boolean restrictBackdoor) { this.pluginSettings.put(MoOAuthPluginConstants.SignInSettings.RESTRICT_BACKDOOR.getKey(), BooleanUtils.toString(restrictBackdoor, "true", "false", "false")); } public List<String> getBackdoorGroups() { List<String> backdoorGroups = (List<String>) this.pluginSettings.get(MoOAuthPluginConstants.SignInSettings.BACKDOOR_GROUPS.getKey()); if (backdoorGroups == null) { backdoorGroups = new ArrayList<>(); backdoorGroups.addAll(bambooPermissionManager.getAdminGroups()); } else if (backdoorGroups.size() == 0) { backdoorGroups.addAll(bambooPermissionManager.getAdminGroups()); } return backdoorGroups; } public void setBackdoorGroups(List<String> backdoorGroups) { this.pluginSettings.put(MoOAuthPluginConstants.SignInSettings.BACKDOOR_GROUPS.getKey(), backdoorGroups); } public List<String> convertArrayToList(String[] agentGroups) { List<String> agentGroupsList = new ArrayList<>(); if (agentGroups != null) { for (String agentGroup : agentGroups) { agentGroupsList.add(agentGroup); } } return agentGroupsList; } public void setBackdoorKey(String backdoorKey) { this.pluginSettings.put(MoOAuthPluginConstants.SignInSettings.BACKDOOR_KEY.getKey(), StringUtils.defaultIfBlank(backdoorKey, "oauth_sso")); } public String getBackdoorKey() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.SignInSettings.BACKDOOR_KEY.getKey()), "oauth_sso"); } public void setBackdoorValue(String backdoorValue) { this.pluginSettings.put(MoOAuthPluginConstants.SignInSettings.BACKDOOR_VALUE.getKey(), StringUtils.defaultIfBlank(backdoorValue, "false")); } public String getBackdoorValue() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.SignInSettings.BACKDOOR_VALUE.getKey()), "false"); } public Boolean getEnableAutoRedirectDelay() { return BooleanUtils.toBooleanDefaultIfNull( BooleanUtils.toBoolean((String) this.pluginSettings.get(MoOAuthPluginConstants.SignInSettings.ENABLE_AUTO_REDIRECT_DELAY.getKey())), false); } public void setEnableAutoRedirectDelay(Boolean enableAutoRedirectDelay) { this.pluginSettings.put(MoOAuthPluginConstants.SignInSettings.ENABLE_AUTO_REDIRECT_DELAY.getKey(), BooleanUtils.toString(enableAutoRedirectDelay, "true", "false", "false")); } public String getAutoRedirectDelayInterval() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.SignInSettings.AUTO_REDIRECT_DELAY_INTERVAL.getKey()), "5"); } public void setAutoRedirectDelayInterval(String autoRedirectDelayInterval) { this.pluginSettings.put(MoOAuthPluginConstants.SignInSettings.AUTO_REDIRECT_DELAY_INTERVAL.getKey(), StringUtils.trimToEmpty(StringUtils.defaultIfBlank(autoRedirectDelayInterval, StringUtils.EMPTY))); } public Boolean getEnableLoginTemplate() { return BooleanUtils.toBooleanDefaultIfNull(BooleanUtils.toBoolean((String) this.pluginSettings.get(MoOAuthPluginConstants.SignInSettings.ENABLE_LOGIN_TEMPLATE.getKey())), false); } public void setEnableLoginTemplate(Boolean enableLoginTemplate) { this.pluginSettings.put(MoOAuthPluginConstants.SignInSettings.ENABLE_LOGIN_TEMPLATE.getKey(), BooleanUtils.toString(enableLoginTemplate, "true", "false", "false")); } public String getLoginTemplate() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.SignInSettings.LOGIN_TEMPLATE.getKey()), LOGIN_TEMPLATE); } public void setLoginTemplate(String loginTemplate) { this.pluginSettings.put(MoOAuthPluginConstants.SignInSettings.LOGIN_TEMPLATE.getKey(), StringUtils.trimToEmpty(StringUtils.defaultIfBlank(loginTemplate, LOGIN_TEMPLATE))); } public void setEnableLogoutTemplate(Boolean enableLogoutTemplate){ this.pluginSettings.put(MoOAuthPluginConstants.SignInSettings.ENABLE_LOGOUT_TEMPLATE.getKey(), BooleanUtils.toString(enableLogoutTemplate, "true","false", "false")); } public Boolean getEnableLogoutTemplate(){ return BooleanUtils.toBooleanDefaultIfNull(BooleanUtils.toBoolean((String) this.pluginSettings.get(MoOAuthPluginConstants.SignInSettings.ENABLE_LOGOUT_TEMPLATE.getKey())), false); } public void setPluginApiAccessRestriction(Boolean pluginApiAccessRestriction){ this.pluginSettings.put(MoOAuthPluginConstants.SignInSettings.PLUGIN_API_ACCESS_RESTRICTION.getKey(), BooleanUtils.toString(pluginApiAccessRestriction, "true", "false", "false")); } public Boolean getPluginApiAccessRestriction(){ return BooleanUtils.toBooleanDefaultIfNull(BooleanUtils.toBoolean((String)this.pluginSettings.get(MoOAuthPluginConstants.SignInSettings.PLUGIN_API_ACCESS_RESTRICTION.getKey())), false); } public void setEnableErrorMsgTemplate(Boolean enableErrorMsgTemplate){ this.pluginSettings.put(MoOAuthPluginConstants.SignInSettings.ENABLE_ERROR_MSG_TEMPLATE.getKey(), BooleanUtils.toString(enableErrorMsgTemplate, "true","false", "false")); } public Boolean getEnableErrorMsgTemplate(){ return BooleanUtils.toBooleanDefaultIfNull(BooleanUtils.toBoolean((String) this.pluginSettings.get(MoOAuthPluginConstants.SignInSettings.ENABLE_ERROR_MSG_TEMPLATE.getKey())), false); } public String getAllowedDomains() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.SignInSettings.ALLOWED_DOMAINS.getKey()), StringUtils.EMPTY); } public void setAllowedDomains(String allowedDomains) { this.pluginSettings.put(MoOAuthPluginConstants.SignInSettings.ALLOWED_DOMAINS.getKey(), StringUtils.trimToEmpty(StringUtils .defaultIfBlank(allowedDomains, StringUtils.EMPTY))); } public void setLogoutTemplate(String logoutTemplate){ String encodedLogoutTemplate = Base64.getEncoder().encodeToString(logoutTemplate.getBytes()); this.pluginSettings.put(MoOAuthPluginConstants.SignInSettings.LOGOUT_TEMPLATE.getKey(), StringUtils.trimToEmpty(StringUtils .defaultIfBlank(encodedLogoutTemplate, StringUtils.EMPTY))); } public String getLogoutTemplate(){ String encodedLogoutTemplate = (String) this.pluginSettings.get(MoOAuthPluginConstants.SignInSettings.LOGOUT_TEMPLATE.getKey()); if(StringUtils.isNotBlank(encodedLogoutTemplate)){ encodedLogoutTemplate = new String(Base64.getDecoder().decode(encodedLogoutTemplate)); } return StringUtils.defaultIfBlank(encodedLogoutTemplate, LOGOUT_TEMPLATE); } public void setCustomLogoutURL(String customLogoutURL){ this.pluginSettings.put(MoOAuthPluginConstants.SignInSettings.CUSTOM_LOGOUT_URL.getKey(), StringUtils.trimToEmpty(StringUtils .defaultIfBlank(customLogoutURL, StringUtils.EMPTY))); } public String getCustomLogoutURL(){ return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.SignInSettings.CUSTOM_LOGOUT_URL.getKey()), StringUtils.EMPTY); } public void setErrorMsgTemplate(String errorMsgTemplate){ String encodedErrorMsgTemplate = Base64.getEncoder().encodeToString(errorMsgTemplate.getBytes()); this.pluginSettings.put(MoOAuthPluginConstants.SignInSettings.ERROR_MSG_TEMPLATE.getKey(), StringUtils.trimToEmpty(StringUtils .defaultIfBlank(encodedErrorMsgTemplate, StringUtils.EMPTY))); } public String getErrorMsgTemplate(){ String encodedLogoutTemplate = (String) this.pluginSettings.get(MoOAuthPluginConstants.SignInSettings.ERROR_MSG_TEMPLATE.getKey()); if(StringUtils.isNotBlank(encodedLogoutTemplate)){ encodedLogoutTemplate = new String(Base64.getDecoder().decode(encodedLogoutTemplate)); } return StringUtils.defaultIfBlank(encodedLogoutTemplate, ERRORMSG_TEMPLATE); } public void setAccessToken(String accessToken) { this.pluginSettings.put(MoOAuthPluginConstants.ACCESS_TOKEN, StringUtils.trimToEmpty(StringUtils .defaultIfBlank(accessToken, StringUtils.EMPTY))); } public void setConfigurationStatus(String status){ this.pluginSettings.put(MoOAuthPluginConstants.CONFIGURATION_STATUS, StringUtils.defaultIfBlank(status, StringUtils.EMPTY)); } public String getConfigurationStatus(){ return (String)this.pluginSettings.get(MoOAuthPluginConstants.CONFIGURATION_STATUS); } public String getAccessToken() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.ACCESS_TOKEN), StringUtils.EMPTY); } public String getRefreshToken() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.REFRESH_TOKEN), StringUtils.EMPTY); } public void setRefreshToken(String refreshToken) { this.pluginSettings.put(MoOAuthPluginConstants.REFRESH_TOKEN, StringUtils.trimToEmpty(StringUtils .defaultIfBlank(refreshToken, StringUtils.EMPTY))); } public void setReturnUrl(String returnUrl) { this.pluginSettings.put(MoOAuthPluginConstants.RETURN_URL, StringUtils.trimToEmpty(StringUtils .defaultIfBlank(returnUrl, StringUtils.EMPTY))); } public String getReturnUrl() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.RETURN_URL), StringUtils.EMPTY); } public void setTenantID(String tenantID) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.TENANT_ID.getKey(), StringUtils.trimToEmpty(StringUtils .defaultIfBlank(tenantID, StringUtils.EMPTY))); } public String getTenantID() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.OAuthConfiguration.TENANT_ID.getKey()), StringUtils.EMPTY); } public void setUserInfoMap(HashMap<String, String> userInfoMap) { this.pluginSettings.put(MoOAuthPluginConstants.USER_INFO_MAP, userInfoMap); } public HashMap<String, String> getUserInfoMap() { Object userInfoMap = this.pluginSettings.get(MoOAuthPluginConstants.USER_INFO_MAP); if (userInfoMap != null) { return (HashMap) userInfoMap; } return new HashMap<>(); } public String getSingleLogoutURL() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.SINGLE_LOGOUT_URL), StringUtils.EMPTY); } public void setSingleLogoutURL(String singleLogoutURL) { this.pluginSettings.put(MoOAuthPluginConstants.SINGLE_LOGOUT_URL, StringUtils.trimToEmpty(StringUtils.defaultIfBlank(singleLogoutURL, StringUtils.EMPTY))); } public String getPublicKey() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.OAuthConfiguration.PUBLIC_KEY.getKey()), StringUtils.EMPTY); } public void setPublicKey(String publicKey) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.PUBLIC_KEY.getKey(), StringUtils.trimToEmpty(StringUtils.defaultIfBlank(publicKey, StringUtils.EMPTY))); } public Boolean getNonceCheck() { return BooleanUtils.toBooleanDefaultIfNull(BooleanUtils.toBoolean((String) this.pluginSettings.get (MoOAuthPluginConstants.OAuthConfiguration.NONCE_VALIDATION.getKey())), false); } public void setNonceCheck(Boolean nonceCheck) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.NONCE_VALIDATION.getKey(), BooleanUtils.toString(nonceCheck, "true", "false", "false")); } public Boolean getACRValueCheck() { return BooleanUtils.toBooleanDefaultIfNull(BooleanUtils.toBoolean((String) this.pluginSettings.get (MoOAuthPluginConstants.OAuthConfiguration.ACR_VALUE_CHECK.getKey())), false); } public void setACRValueCheck(Boolean acrValueCheck) { this.pluginSettings.put(MoOAuthPluginConstants.OAuthConfiguration.ACR_VALUE_CHECK.getKey(), BooleanUtils.toString(acrValueCheck , "true", "false", "false")); } public AdministrationConfigurationAccessor getAdministrationConfigurationAccessor() { return administrationConfigurationAccessor; } public void setAdministrationConfigurationAccessor( AdministrationConfigurationAccessor administrationConfigurationAccessor) { this.administrationConfigurationAccessor = administrationConfigurationAccessor; } public PluginLicenseManager getPluginLicenseManager() { return pluginLicenseManager; } public void setPluginLicenseManager(PluginLicenseManager pluginLicenseManager) { this.pluginLicenseManager = pluginLicenseManager; } public void setPluginSettingsFactory(PluginSettingsFactory pluginSettingsFactory) { this.pluginSettings = pluginSettingsFactory.createGlobalSettings(); } public PluginSettings getPluginSettings() { return pluginSettings; } public void setPluginSettings(PluginSettings pluginSettings) { this.pluginSettings = pluginSettings; } public PluginAccessor getPluginAccessor() { return pluginAccessor; } public void setPluginAccessor(PluginAccessor pluginAccessor) { this.pluginAccessor = pluginAccessor; } public BambooPermissionManager getBambooPermissionManager() { return bambooPermissionManager; } public void setBambooPermissionManager(BambooPermissionManager bambooPermissionManager) { this.bambooPermissionManager = bambooPermissionManager; } public String getPluginVersion(){ String pluginKey = pluginLicenseManager.getPluginKey(); Plugin plugin = pluginAccessor.getPlugin(pluginKey); return plugin.getPluginInformation().getVersion(); } public String getPluginName(){ String pluginKey = pluginLicenseManager.getPluginKey(); Plugin plugin = pluginAccessor.getPlugin(pluginKey); return plugin.getName(); } public String getServerVersion(){ return BuildUtils.getCurrentVersion(); } public void deleteKey(String constantKey) { this.pluginSettings.remove(constantKey); } public void clearPluginSettings() { this.pluginSettings.remove(MoOAuthPluginConstants.USER_INFO_MAP); this.pluginSettings.remove(MoOAuthPluginConstants.IS_TEST_CONFIGURATION_CLICKED); this.pluginSettings.remove(MoOAuthPluginConstants.IS_VERIFY_CREDENTIALS_CLICKED); this.pluginSettings.remove(MoOAuthPluginConstants.REFRESH_TOKEN); this.pluginSettings.remove(MoOAuthPluginConstants.ACCESS_TOKEN); this.pluginSettings.remove(MoOAuthPluginConstants.IS_CREDENTIALS_VERIFIED); this.pluginSettings.remove(MoOAuthPluginConstants.RETURN_URL); this.pluginSettings.remove(MoOAuthPluginConstants.GOOGLE_REFRESH_TOKEN); resetOAuthConfig(); resetAttributeMapping(); resetGroupMapping(); resetSignOnSettings(); } public void resetOAuthConfig() { LOGGER.debug("resetOAuthConfig called "); for(MoOAuthPluginConstants.OAuthConfiguration constant : MoOAuthPluginConstants.OAuthConfiguration.values()) { resetConfig(constant.getKey()); } } public void resetAttributeMapping() { LOGGER.debug("resetAttributeMapping called "); for(MoOAuthPluginConstants.AttributeMapping constant : MoOAuthPluginConstants.AttributeMapping.values()) { resetConfig(constant.getKey()); } } public void resetGroupMapping() { LOGGER.debug("resetGroupMapping called "); for(MoOAuthPluginConstants.GroupMapping constant : MoOAuthPluginConstants.GroupMapping.values()) { resetConfig(constant.getKey()); } } public void resetSignOnSettings() { LOGGER.debug("resetSignOnSettings called "); for(MoOAuthPluginConstants.SignInSettings constant : MoOAuthPluginConstants.SignInSettings.values()) { resetConfig(constant.getKey()); } } public void resetConfig(String constantKey){ this.pluginSettings.remove(constantKey); } //group regex public Boolean getGroupRegexPatternEnabled() { return BooleanUtils.toBoolean( StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.GroupMapping.GROUP_REGEX_PATTERN_ENABLED.getKey()),"false")); } public void setGroupRegexPatternEnabled(Boolean groupRegexPatternEnabled) { this.pluginSettings.put(MoOAuthPluginConstants.GroupMapping.GROUP_REGEX_PATTERN_ENABLED.getKey(), BooleanUtils.toString(groupRegexPatternEnabled, "true", "false", "false")); } public String getRegexPatternForGroup() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.GroupMapping.REGEX_PATTERN_FOR_GROUP.getKey()), ""); } public void setRegexPatternForGroup(String regexPatternForGroup) { this.pluginSettings.put(MoOAuthPluginConstants.GroupMapping.REGEX_PATTERN_FOR_GROUP.getKey(), StringUtils.trimToEmpty(StringUtils.defaultIfBlank(regexPatternForGroup, ""))); } public String getRegexGroups() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.GroupMapping.REGEX_GROUPS.getKey()), ""); } public void setRegexGroups(String regexGroups) { this.pluginSettings.put(MoOAuthPluginConstants.GroupMapping.REGEX_GROUPS.getKey(), StringUtils.trimToEmpty(StringUtils.defaultIfBlank(regexGroups, ""))); } public String getTestRegex() { return StringUtils.defaultIfBlank((String) this.pluginSettings.get(MoOAuthPluginConstants.GroupMapping.TEST_REGEX.getKey()), ""); } public void setTestRegex(String testRegex) { this.pluginSettings.put(MoOAuthPluginConstants.GroupMapping.TEST_REGEX.getKey(), StringUtils.trimToEmpty(StringUtils.defaultIfBlank(testRegex, ""))); } }
42.660202
188
0.806957
c0a7d9e674314a69cacb20f7ee8922fd22600545
373
package edu.southwestern.util.search; import java.util.ArrayList; public interface Search<A extends Action, S extends State<A>> { /** * Given a start State, return a list of actions that reaches a goal state * @param start Start State * @return List of Actions that an agent can perform to reach a goal from the start */ public ArrayList<A> search(S start); }
28.692308
84
0.731903
2db656bd1fee7e3d4bf776beb1f4db0b37a55ff5
234
package com.glacier.common.core.utils; import org.junit.jupiter.api.Test; /** * @author glacier * @version 1.0 * date 2020-08-10 20:05 */ public class TreeBuildFactoryTest { @Test public void buildMenuTree() { } }
13.764706
38
0.666667
1db528cb1a523731ae911906ad39b948fafa619e
939
package io.vertx.tp.is.init; import io.vertx.core.json.JsonObject; import io.vertx.tp.is.atom.IsConfig; import io.vertx.tp.is.cv.IsFolder; import io.vertx.tp.is.refine.Is; import io.vertx.up.util.Ut; import java.util.Objects; /** * @author <a href="http://www.origin-x.cn">Lang</a> */ final class IsConfiguration { private static IsConfig CONFIG = null; static void init() { if (Objects.isNull(CONFIG)) { final JsonObject configData = Ut.ioJObject(IsFolder.CONFIG_FILE); Is.Log.infoInit(IsConfiguration.class, "Is Json Data: {0}", configData.encode()); CONFIG = Ut.deserialize(configData, IsConfig.class); Is.Log.infoInit(IsConfiguration.class, "Is Configuration: {0}", CONFIG.toString()); Is.Log.infoInit(IsConfiguration.class, "Is StoreRoot = {0}", CONFIG.getStoreRoot()); } } static IsConfig getConfig() { return CONFIG; } }
30.290323
96
0.657082
eb84fa8ee36d20cf1697d5bf5caa8a583aac6736
24,028
package com.refinitiv.ema.perftools.common; import com.refinitiv.ema.perftools.emajniprovperf.NIProviderPerfConfig; import com.refinitiv.ema.perftools.emajniprovperf.NIProviderThread; import com.refinitiv.ema.perftools.emajprovperf.IProviderPerfConfig; import com.refinitiv.ema.perftools.emajprovperf.IProviderThread; import java.io.PrintWriter; import java.util.Calendar; import java.util.TimeZone; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; public class ProviderStats { private final ProviderThreadStats totalStats; private final ValueStatistics cpuUsageStatistics; private final ValueStatistics memUsageStatistics; private BaseProviderPerfConfig config; private ProviderThread[] providerThreads; private LogFileInfo summaryFile; private AtomicBoolean _stop = new AtomicBoolean(true); private volatile boolean _exitApp; private CountDownLatch _loopExited = new CountDownLatch(1); private CountDownLatch _stopped = new CountDownLatch(1); public ProviderStats() { this.totalStats = new ProviderThreadStats(); this.cpuUsageStatistics = new ValueStatistics(); this.memUsageStatistics = new ValueStatistics(); } public void initialize(XmlMsgData xmlMsgData, BaseProviderPerfConfig config) { this.config = config; cpuUsageStatistics.clear(); memUsageStatistics.clear(); this.providerThreads = new ProviderThread[config.threadCount()]; for (int i = 0; i < config.threadCount(); i++) { if (config instanceof NIProviderPerfConfig) { providerThreads[i] = new NIProviderThread((NIProviderPerfConfig) this.config, xmlMsgData); } else { providerThreads[i] = new IProviderThread(this.config, xmlMsgData); } providerThreads[i].initialize(i); } System.out.println(config.toString()); if (config.summaryFilename() != null && !config.summaryFilename().isEmpty()) { this.summaryFile = LogFileHelper.initFile(config.summaryFilename()); } LogFileHelper.writeFile(summaryFile, config.toString()); } public void run() { registerShutdownHook(); startThreads(); long nextTime = System.currentTimeMillis() + 1000L; int intervalSeconds = 0; int currentRuntimeSec = 0; int writeStatsInterval = config.writeStatsInterval(); int runTime = config.runTime(); boolean displayStats = config.displayStats(); do { if (System.currentTimeMillis() >= nextTime) { nextTime += 1000; ++intervalSeconds; ++currentRuntimeSec; // Check if it's time to print stats if (intervalSeconds >= writeStatsInterval) { this.collectStats(true, displayStats, currentRuntimeSec, writeStatsInterval); intervalSeconds = 0; } } try { long sleepTime = nextTime - System.currentTimeMillis(); if (sleepTime > 0) { Thread.sleep(sleepTime); } } catch (InterruptedException e) { e.printStackTrace(); } } while (currentRuntimeSec < runTime && !_exitApp); System.out.printf("\nRun time of %d seconds has expired.\n\n", runTime); _loopExited.countDown(); if (_stop.getAndSet(false)) { stop(); _stopped.countDown(); } } public void startThreads() { for (ProviderThread thread : providerThreads) { thread.start(); } } public void stopThreads() { for (ProviderThread providerThread : providerThreads) { providerThread.shutdown(true); } for (ProviderThread providerThread : providerThreads) { int shutdownCount = 0; while (!providerThread.shutdownAck() && shutdownCount < 3) { try { Thread.sleep(1000); shutdownCount++; } catch (InterruptedException e) { System.err.println("Thread.sleep(1000) failed"); System.exit(-1); } } } System.out.println("Shutting down."); } public void clear() { for (ProviderThread thread : providerThreads) { thread.clear(); } } /** * Collects and writes provider statistics. Stats will reflect changes from the previous * call to this method. * * @param writeStats - if true, writes statistics to provider stats file * @param displayStats - if true, writes stats to stdout. * @param currentRuntimeSec - current time * @param timePassedSec - time passed since last stats collection, used to calculate message rates. */ public void collectStats(boolean writeStats, boolean displayStats, long currentRuntimeSec, long timePassedSec) { long refreshCount, updateCount, requestCount, closeCount, postCount, statusCount, genMsgSentCount, genMsgRecvCount, latencyGenMsgSentCount, latencyGenMsgRecvCount, outOfBuffersCount, msgSentCount, bufferSentCount; double processCpuLoad = ResourceUsageStats.currentProcessCpuLoad(); double memoryUsage = ResourceUsageStats.currentMemoryUsage(); if (timePassedSec != 0) { cpuUsageStatistics.update(processCpuLoad); memUsageStatistics.update(memoryUsage); } for (int i = 0; i < config.threadCount(); ++i) { ProviderThread providerThread = providerThreads[i]; collectGenMsgStats(providerThread.providerThreadStats(), providerThread); ProviderThreadStats stats = providerThread.providerThreadStats(); requestCount = stats.requestCount().getChange(); refreshCount = stats.refreshCount().getChange(); updateCount = stats.updateCount().getChange(); closeCount = stats.closeCount().getChange(); postCount = stats.postCount().getChange(); statusCount = stats.statusCount().getChange(); genMsgSentCount = stats.genMsgSentCount().getChange(); genMsgRecvCount = stats.genMsgRecvCount().getChange(); latencyGenMsgSentCount = stats.latencyGenMsgSentCount().getChange(); latencyGenMsgRecvCount = stats.intervalGenMsgLatencyStats().count(); outOfBuffersCount = stats.outOfBuffersCount().getChange(); if (writeStats) { // Write stats to the stats file. Calendar rightNow = Calendar.getInstance(TimeZone.getTimeZone("GMT")); LogFileHelper.writeFile(providerThread.statsFile(), String.format("%d-%02d-%02d %02d:%02d:%02d", rightNow.get(Calendar.YEAR), rightNow.get(Calendar.MONTH), rightNow.get(Calendar.DAY_OF_MONTH), rightNow.get(Calendar.HOUR_OF_DAY), rightNow.get(Calendar.MINUTE), rightNow.get(Calendar.SECOND)) ); if (providerThread instanceof IProviderThread) { LogFileHelper.writeFile(providerThread.statsFile(), String.format( ", %d, %d, %d, %d, %d, %d, %d, %d, %.1f, %.1f, %.1f, %.1f, %.2f, %.2f\n", requestCount, refreshCount, updateCount, postCount, genMsgSentCount, genMsgRecvCount, latencyGenMsgSentCount, latencyGenMsgRecvCount, stats.intervalGenMsgLatencyStats().average(), Math.sqrt(stats.intervalGenMsgLatencyStats().variance()), ((stats.intervalGenMsgLatencyStats().count() > 0) ? stats.intervalGenMsgLatencyStats().maxValue() : 0.0), ((stats.intervalGenMsgLatencyStats().count() > 0) ? stats.intervalGenMsgLatencyStats().minValue() : 0.0), processCpuLoad, memoryUsage)); } else { LogFileHelper.writeFile(providerThread.statsFile(), String.format( ", %d, %d, %d, %.2f, %.2f\n", requestCount, refreshCount, updateCount, processCpuLoad, memoryUsage)); } } //Add the new counts to the provider's total. totalStats.requestCount().add(requestCount); totalStats.updateCount().add(updateCount); totalStats.refreshCount().add(refreshCount); totalStats.closeCount().add(closeCount); totalStats.postCount().add(postCount); totalStats.statusCount().add(statusCount); totalStats.genMsgSentCount().add(genMsgSentCount); totalStats.genMsgRecvCount().add(genMsgRecvCount); totalStats.latencyGenMsgSentCount().add(latencyGenMsgSentCount); totalStats.outOfBuffersCount().add(outOfBuffersCount); if (displayStats) { //Print screen stats. if (config.threadCount() == 1) { System.out.printf("%03d: ", currentRuntimeSec); } else { System.out.printf("%03d: Thread %d:\n ", currentRuntimeSec, i + 1); } System.out.printf("UpdRate: %8d, CPU: %6.2f%%, Mem: %6.2fMB\n", updateCount / timePassedSec, processCpuLoad, memoryUsage); if (requestCount > 0 || refreshCount > 0) { if (providerThread instanceof IProviderThread) { System.out.printf(" - Received %d item requests (total: %d), sent %d images (total: %d)\n", requestCount, totalStats.requestCount().getTotal(), refreshCount, totalStats.refreshCount().getTotal() ); } else { System.out.printf(" - Sent %d images (total: %d)\n", refreshCount, totalStats.refreshCount().getTotal()); } } if (postCount > 0) { System.out.printf(" Posting: received %d, reflected %d\n", postCount, postCount); } if (genMsgRecvCount > 0 || genMsgSentCount > 0) { System.out.printf(" GenMsgs: sent %d, received %d, latencies sent %d, latencies received %d\n", genMsgSentCount, genMsgRecvCount, latencyGenMsgSentCount, latencyGenMsgRecvCount); } if (stats.intervalGenMsgLatencyStats().count() > 0) { stats.intervalGenMsgLatencyStats().print(" GenMsgLat(usec)", "Msgs", false); stats.intervalGenMsgLatencyStats().clear(); } closeCount = totalStats.closeCount().getChange(); if (closeCount > 0) { System.out.printf(" - Received %d closes.\n", closeCount); } outOfBuffersCount = totalStats.outOfBuffersCount().getChange(); if (outOfBuffersCount > 0) { System.out.printf(" - Stopped %d updates due to lack of output buffers.\n", outOfBuffersCount); } } } } /** * Prints summary stats to the summary file. * * @param fileWriter - file to write summary stats to. */ public void printSummaryStats(PrintWriter fileWriter) { long statsTime = 0; long currentTime = System.nanoTime(); if (config.threadCount() > 1) { totalStats.inactiveTime(providerThreads[0].providerThreadStats().inactiveTime()); totalStats.firstGenMsgSentTime(providerThreads[0].providerThreadStats().firstGenMsgSentTime()); totalStats.firstGenMsgRecvTime(providerThreads[0].providerThreadStats().firstGenMsgRecvTime()); for (int i = 0; i < config.threadCount(); ++i) { ProviderThread providerThread = providerThreads[i]; ProviderThreadStats stats = providerThread.providerThreadStats(); statsTime = (stats.inactiveTime() > 0 && stats.inactiveTime() < currentTime) ? stats.inactiveTime() : currentTime; if (stats.inactiveTime() > 0 && stats.inactiveTime() < totalStats.inactiveTime()) { totalStats.inactiveTime(stats.inactiveTime()); } fileWriter.printf("\n--- THREAD %d SUMMARY ---\n\n", i + 1); fileWriter.printf("Overall Statistics: \n"); if (config instanceof IProviderPerfConfig) { IProviderPerfConfig ippConfig = (IProviderPerfConfig) config; if (stats.firstGenMsgSentTime() != 0 && stats.firstGenMsgSentTime() < totalStats.firstGenMsgSentTime()) { totalStats.firstGenMsgSentTime(stats.firstGenMsgSentTime()); } if (stats.firstGenMsgRecvTime() != 0 && stats.firstGenMsgRecvTime() < totalStats.firstGenMsgRecvTime()) { totalStats.firstGenMsgSentTime(stats.firstGenMsgRecvTime()); } if (totalStats.genMsgLatencyStats().count() > 0) { fileWriter.printf(" GenMsg latency avg (usec): %.1f\n" + " GenMsg latency std dev (usec): %.1f\n" + " GenMsg latency max (usec): %.1f\n" + " GenMsg latency min (usec): %.1f\n", stats.genMsgLatencyStats().average(), Math.sqrt(stats.genMsgLatencyStats().variance()), stats.genMsgLatencyStats().count() > 0 ? stats.genMsgLatencyStats().maxValue() : 0, stats.genMsgLatencyStats().count() > 0 ? stats.genMsgLatencyStats().minValue() : 0); } else { fileWriter.printf(" No GenMsg latency information was received.\n"); } if (ippConfig.genMsgsPerSec() > 0) { fileWriter.printf(" GenMsgs sent: %d\n", stats.genMsgSentCount().getTotal()); } if (stats.genMsgRecvCount().getTotal() > 0) { fileWriter.printf(" GenMsgs received: %d\n", stats.genMsgRecvCount().getTotal()); } if (ippConfig.latencyGenMsgRate() > 0) { fileWriter.printf(" GenMsg latencies sent: %d\n", stats.latencyGenMsgSentCount().getTotal()); } if (stats.genMsgLatencyStats().count() > 0) { fileWriter.printf(" GenMsg latencies received: %d\n", stats.genMsgLatencyStats().count()); } if (ippConfig.genMsgsPerSec() > 0) { fileWriter.printf(" Avg GenMsg send rate: %.0f\n", stats.genMsgSentCount().getTotal() / ((statsTime - stats.firstGenMsgSentTime()) / 1000000000.0)); } if (stats.genMsgRecvCount().getTotal() > 0) { fileWriter.printf(" Avg GenMsg receive rate: %.0f\n", stats.genMsgRecvCount().getTotal() / ((statsTime - stats.firstGenMsgRecvTime()) / 1000000000.0)); } if (ippConfig.latencyGenMsgRate() > 0) { fileWriter.printf(" Avg GenMsg latency send rate: %.0f\n", stats.latencyGenMsgSentCount().getTotal() / ((statsTime - stats.firstGenMsgSentTime()) / 1000000000.0)); } if (stats.genMsgLatencyStats().count() > 0) { fileWriter.printf(" Avg GenMsg latency receive rate: %.0f\n", stats.genMsgLatencyStats().count() / ((statsTime - stats.firstGenMsgRecvTime()) / 1000000000.0)); } } fileWriter.printf(" Image requests received: %d\n", stats.requestCount().getTotal()); if (providerThread instanceof NIProviderThread) { fileWriter.printf(" Images sent: %d\n", stats.refreshCount().getTotal()); } if (config.updatesPerSec() > 0) { fileWriter.printf(" Updates sent: %d\n", stats.updateCount().getTotal()); } if (stats.postCount().getTotal() > 0) { fileWriter.printf(" Posts received: %d\n", stats.postCount().getTotal()); fileWriter.printf(" Posts reflected: %d\n", stats.postCount().getTotal()); } break; } } else { ProviderThreadStats totalStats = providerThreads[0].providerThreadStats(); statsTime = (totalStats.inactiveTime() != 0 && totalStats.inactiveTime() < currentTime) ? totalStats.inactiveTime() : currentTime; } fileWriter.printf("\n--- OVERALL SUMMARY ---\n\n"); fileWriter.printf("Overall Statistics: \n"); if (this.totalStats.genMsgLatencyStats().count() > 0) { fileWriter.printf(" GenMsg latency avg (usec): %.1f\n" + " GenMsg latency std dev (usec): %.1f\n" + " GenMsg latency max (usec): %.1f\n" + " GenMsg latency min (usec): %.1f\n", this.totalStats.genMsgLatencyStats().average(), Math.sqrt(this.totalStats.genMsgLatencyStats().variance()), this.totalStats.genMsgLatencyStats().maxValue(), this.totalStats.genMsgLatencyStats().minValue()); } else { fileWriter.printf(" No GenMsg latency information was received.\n"); } if (config instanceof IProviderPerfConfig) { IProviderPerfConfig ippConfig = (IProviderPerfConfig) config; if (ippConfig.genMsgsPerSec() > 0) { fileWriter.printf(" GenMsgs sent: %d\n", totalStats.genMsgSentCount().getTotal()); } if (this.totalStats.genMsgRecvCount().getTotal() > 0) { fileWriter.printf(" GenMsgs received: %d\n", totalStats.genMsgRecvCount().getTotal()); } if (ippConfig.latencyGenMsgRate() > 0) { fileWriter.printf(" GenMsg latencies sent: %d\n", totalStats.latencyGenMsgSentCount().getTotal()); } if (totalStats.genMsgLatencyStats().count() > 0) { fileWriter.printf(" GenMsg latencies received: %d\n", totalStats.genMsgLatencyStats().count()); } if (ippConfig.genMsgsPerSec() > 0) { fileWriter.printf(" Avg GenMsg send rate: %.0f\n", totalStats.genMsgSentCount().getTotal() / ((statsTime - totalStats.firstGenMsgSentTime()) / 1000000000.0)); } if (this.totalStats.genMsgRecvCount().getTotal() > 0) { fileWriter.printf(" Avg GenMsg receive rate: %.0f\n", totalStats.genMsgRecvCount().getTotal() / ((statsTime - totalStats.firstGenMsgRecvTime()) / 1000000000.0)); } if (ippConfig.latencyGenMsgRate() > 0) { fileWriter.printf(" Avg GenMsg latency send rate: %.0f\n", totalStats.latencyGenMsgSentCount().getTotal() / ((statsTime - totalStats.firstGenMsgSentTime()) / 1000000000.0)); } } if (totalStats.genMsgLatencyStats().count() > 0) { fileWriter.printf(" Avg GenMsg latency receive rate: %.0f\n", totalStats.genMsgLatencyStats().count() / ((statsTime - totalStats.firstGenMsgRecvTime()) / 1000000000.0)); } fileWriter.printf(" Image requests received: %d\n", totalStats.requestCount().getTotal()); if (config.updatesPerSec() > 0) { fileWriter.printf(" Updates sent: %d\n", totalStats.updateCount().getTotal()); } if (totalStats.postCount().getTotal() > 0) { fileWriter.printf(" Posts received: %d\n", totalStats.postCount().getTotal()); fileWriter.printf(" Posts reflected: %d\n", totalStats.postCount().getTotal()); } if (cpuUsageStatistics.count() > 0) { fileWriter.printf(" CPU/Memory Samples: %d\n", cpuUsageStatistics.count()); fileWriter.printf(" CPU Usage max (%%): %.2f\n", cpuUsageStatistics.maxValue()); fileWriter.printf(" CPU Usage min (%%): %.2f\n", cpuUsageStatistics.minValue()); fileWriter.printf(" CPU Usage avg (%%): %.2f\n", cpuUsageStatistics.average()); fileWriter.printf(" Memory Usage max (MB): %.2f\n", memUsageStatistics.maxValue()); fileWriter.printf(" Memory Usage min (MB): %.2f\n", memUsageStatistics.minValue()); fileWriter.printf(" Memory Usage avg (MB): %.2f\n", memUsageStatistics.average()); } fileWriter.printf("\n"); } private void collectGenMsgStats(ProviderThreadStats threadStats, ProviderThread providerThread) { if (providerThread instanceof IProviderThread) { IProviderThread ippThread = (IProviderThread) providerThread; TimeRecordQueue latencyRecords = threadStats.genMsgLatencyRecords(); while (!latencyRecords.records().isEmpty()) { TimeRecord record = latencyRecords.records().poll(); double latency = (double) (record.endTime() - record.startTime()) / (double) record.ticks(); threadStats.intervalGenMsgLatencyStats().update(latency); threadStats.genMsgLatencyStats().update(latency); if (config.threadCount() > 1) { totalStats.genMsgLatencyStats().update(latency); } LogFileHelper.writeFile(ippThread.latencyFile(), String.format("Gen, %d, %d, %d\n", record.startTime(), record.endTime(), (record.endTime() - record.startTime()))); latencyRecords.pool().add(record); } } } /** * Prints the final stats. */ public void printFinalStats() { PrintWriter printWriter = new PrintWriter(System.out); printSummaryStats(printWriter); printWriter.flush(); printSummaryStats(summaryFile.writer()); summaryFile.writer().close(); } private void stop() { try { stopThreads(); printFinalStats(); clear(); } finally { _stopped.countDown(); } } private void registerShutdownHook() { Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { if (_stop.getAndSet(false)) { _exitApp = true; _loopExited.await(1000, TimeUnit.MILLISECONDS); stop(); } else { _stopped.await(providerThreads.length * 5000, TimeUnit.MILLISECONDS); } } catch (Exception e) { e.printStackTrace(); } })); } public ProviderThread[] providerThreads() { return providerThreads; } }
45.767619
221
0.556309
1468834220e8157bdef9e6d995bcfbd7a81a34aa
5,433
package controllers; import java.util.List; import java.util.ArrayList; import play.mvc.Result; import models.Categoria; import models.Carrinho; import models.FormaPagamento; import models.Transportadora; import models.ItensCarrinho; import models.Produto; import play.mvc.Controller; import play.api.libs.json.Reads; import org.json.*; import org.json.JSONException; import play.data.Form; import play.data.DynamicForm; public class CarrinhoController extends Controller{ private final Form<Carrinho> formCarrinho = Form.form(Carrinho.class); public Result listaCarrinho() { String carrinho = session("carrinho"); List<ItensCarrinho> listaItens = new ArrayList<ItensCarrinho>(); try { if(carrinho != null) { JSONArray jsa = new JSONArray(carrinho); for(int i = 0; i < jsa.length(); i++) { JSONObject jsoItem = jsa.getJSONObject(i); ItensCarrinho item = new ItensCarrinho(); item.Produto = Produto.find.byId(jsoItem.getLong("idProduto")); item.Qtd = jsoItem.getLong("quantidade"); item.Desconto = 0; item.Valor = (item.Produto.preco * item.Qtd); listaItens.add(item); } } return ok(views.html.carrinho.carrinhoCompras.render(listaItens)); } catch (JSONException e) { return ok("404"); } } public Result addItemAoCarrinho(Long idProduto) { String carrinho = session("carrinho"); try { if(carrinho == null) { carrinho = "[]"; //Recebe string JSON de array vazio } boolean aux = false; JSONArray jsa = new JSONArray(carrinho); loop : for(int i = 0; i < jsa.length(); i++) { if (jsa.getJSONObject(i).getLong("idProduto") == idProduto){ JSONObject obj = jsa.getJSONObject(i); Long qty = obj.getLong("quantidade") + 1; obj.put("quantidade",qty); session("carrinho",jsa.toString()); return listaCarrinho(); } } if (aux != true){ JSONObject jsoNovoProduto = new JSONObject(); jsoNovoProduto.put("idProduto", idProduto); jsoNovoProduto.put("quantidade", 1); jsa.put(jsoNovoProduto); } session("carrinho", jsa.toString()); return listaCarrinho(); } catch (JSONException e) { return ok("404"); } } public Result remItemDoCarrinho(Long idProduto) { String carrinho = session("carrinho"); try { JSONArray jsa = new JSONArray(carrinho); for(int i = 0; i < jsa.length(); i++) { JSONObject jsoItem = jsa.getJSONObject(i); if(jsoItem.getLong("idProduto") == idProduto){ jsa.remove(i); } } session("carrinho", jsa.toString()); return listaCarrinho(); } catch (JSONException e) { return ok("404"); } } public Result alterQtdCarrinho(Long id){ String carrinho = session("carrinho"); DynamicForm dynamicForm = Form.form().bindFromRequest(); String input = dynamicForm.get("item"); try { JSONArray jsa = new JSONArray(carrinho); loop : for(int i = 0; i < jsa.length(); i++) { if (jsa.getJSONObject(i).getLong("idProduto") == id){ JSONObject obj = jsa.getJSONObject(i); obj.put("quantidade",Long.parseLong(input.replace(".0", ""))); session("carrinho",jsa.toString()); return listaCarrinho(); } } } catch (JSONException e) { return ok("404"); } return ok(input); } public Result checkin(){ String carrinho = session("carrinho"); List<ItensCarrinho> listaItens = new ArrayList<ItensCarrinho>(); try { if(carrinho != null) { JSONArray jsa = new JSONArray(carrinho); for(int i = 0; i < jsa.length(); i++) { JSONObject jsoItem = jsa.getJSONObject(i); ItensCarrinho item = new ItensCarrinho(); item.Produto = Produto.find.byId(jsoItem.getLong("idProduto")); item.Qtd = jsoItem.getLong("quantidade"); item.Desconto = 0; item.Valor = (item.Produto.preco * item.Qtd); listaItens.add(item); } } else { if (session("carrinho") == null){ return } flash("error", String.format("Carrinho Vazio!!")); } } catch (JSONException e) { return ok("404"); } List<FormaPagamento> formas = FormaPagamento.find.all(); List<Transportadora> trans = Transportadora.find.all(); return ok(views.html.carrinho.checkin.render(formCarrinho,"Check - in",formas,trans,listaItens)); } public Result salvar(){ String carrinho = session("carrinho"); Carrinho car = new Carrinho(); try { if(carrinho != null) { //car. } boolean aux = false; JSONArray jsa = new JSONArray(carrinho); loop : for(int i = 0; i < jsa.length(); i++) { JSONObject obj = jsa.getJSONObject(i); Long qty = obj.getLong("quantidade") + 1; obj.put("quantidade",qty); session("carrinho",jsa.toString()); } session("carrinho", jsa.toString()); } catch (JSONException e) { return ok(session("carrinho")); } return ok(session("carrinho")); } }
32.339286
103
0.57887
cea27c51b344120b2f274f37a9f5c8561da51ee7
865
package com.hb0730.dubbo.boot.provider.sample.service.impl; import com.hb0730.dubbo.sample.bean.UserAddress; import com.hb0730.dubbo.sample.service.IUserService; import org.apache.dubbo.config.annotation.Service; import org.springframework.stereotype.Component; import java.util.Arrays; import java.util.List; /** * <p> * 1. 服务提供者注入注册中心 * 1. 导入dubbo依赖 * 2. 配置dubbo * 2. 服务消费者去注册中心订阅 * * </P> * * @author bing_huang * @since V1.0 */ //暴露服务 @Service @Component public class UserServiceImpl implements IUserService { @Override public List<UserAddress> getUserAddressList(String userId) { UserAddress userAddress = new UserAddress(1, "湖南长沙", "1", "张三", "15074446478", "false"); UserAddress userAddress1 = new UserAddress(2, "上海", "1", "张三", "15074446478", "true"); return Arrays.asList(userAddress, userAddress1); } }
24.714286
96
0.710983
4384bc84b0b6f2f5a49d66c1e81a6597c78527ad
3,419
package pl.plh.app.employment.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import pl.plh.app.employment.domain.GroupDto; import pl.plh.app.employment.domain.GroupToCreateDto; import pl.plh.app.employment.domain.PositiveLongInQueryDto; import pl.plh.app.employment.mapper.GroupMapper; import pl.plh.app.employment.mapper.QueryVariablesMapper; import pl.plh.app.employment.service.GroupPersistService; import pl.plh.app.employment.swagger.ApiCUDResponses; import pl.plh.app.employment.swagger.ApiReadResponses; import javax.validation.Valid; import java.util.List; @Api(description = "CRUD operations", tags = {"Group"}) @RestController @RequestMapping("/v1") public class GroupController { @Autowired private GroupPersistService db; @Autowired private GroupMapper groupMapper; @Autowired private QueryVariablesMapper queryVariablesMapper; @ApiOperation(position = 0, value = "Get all groups", tags = {"Group"}) @RequestMapping(method = RequestMethod.GET, value = "/groups", produces = "application/json") public List<GroupDto> getGroups() { return groupMapper.mapToGroupDtoList(db.getAllGroups()); } @ApiOperation(value = "Get a group by identifier", tags = {"Group"}) @ApiReadResponses @RequestMapping(method = RequestMethod.GET, value = "/groups/{groupId}", produces = "application/json") public GroupDto getGroup(@ApiParam(value = "Group identifier", required = true) @PathVariable PositiveLongInQueryDto groupId) { return groupMapper.mapToGroupDto(db.getGroup(queryVariablesMapper.mapToLong(groupId))); } @ApiOperation(value = "Create a new group", tags = {"Group"}) @ApiCUDResponses @ResponseStatus(HttpStatus.CREATED) @RequestMapping(method = RequestMethod.POST, value = "/groups", consumes = "application/json", produces = "application/json") public GroupDto createGroup(@ApiParam(name = "groupToCreate", value = "Group to create", required = true) @Valid @RequestBody GroupToCreateDto groupToCreateDto) { return groupMapper.mapToGroupDto(db.saveGroup(groupMapper.mapToGroup(groupToCreateDto))); } @ApiOperation(value = "Update a group", tags = {"Group"}) @ApiCUDResponses @ResponseStatus(HttpStatus.OK) @RequestMapping(method = RequestMethod.PUT, value = "/groups", consumes = "application/json", produces = "application/json") public GroupDto updateGroup(@ApiParam(name = "group", value = "Group", required = true) @Valid @RequestBody GroupDto groupDto) { return groupMapper.mapToGroupDto(db.updateGroup(groupMapper.mapToGroup(groupDto))); } @ApiOperation(value = "Delete a group by identifier", tags = {"Group"}) @ApiCUDResponses @ResponseStatus(HttpStatus.NO_CONTENT) @RequestMapping(method = RequestMethod.DELETE, value = "/groups/{groupId}") public void deleteGroup(@ApiParam(value = "Group identifier", required = true) @PathVariable PositiveLongInQueryDto groupId) { db.deleteGroup(queryVariablesMapper.mapToLong(groupId)); } }
44.986842
109
0.717461
63f84a24889465facd37663bde6a0ad19f66e62e
5,904
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.google.android.gms.cast; import android.os.Parcel; import com.google.android.gms.common.internal.ak; import com.google.android.gms.common.internal.safeparcel.AbstractSafeParcelable; import com.google.android.gms.common.internal.safeparcel.c; import com.google.android.gms.internal.cast.aj; import java.util.Locale; // Referenced classes of package com.google.android.gms.cast: // u public class LaunchOptions extends AbstractSafeParcelable { public LaunchOptions() { this(false, aj.a(Locale.getDefault())); // 0 0:aload_0 // 1 1:iconst_0 // 2 2:invokestatic #26 <Method Locale Locale.getDefault()> // 3 5:invokestatic #31 <Method String aj.a(Locale)> // 4 8:invokespecial #34 <Method void LaunchOptions(boolean, String)> // 5 11:return } LaunchOptions(boolean flag, String s) { // 0 0:aload_0 // 1 1:invokespecial #35 <Method void AbstractSafeParcelable()> a = flag; // 2 4:aload_0 // 3 5:iload_1 // 4 6:putfield #37 <Field boolean a> b = s; // 5 9:aload_0 // 6 10:aload_2 // 7 11:putfield #39 <Field String b> // 8 14:return } public boolean a() { return a; // 0 0:aload_0 // 1 1:getfield #37 <Field boolean a> // 2 4:ireturn } public String b() { return b; // 0 0:aload_0 // 1 1:getfield #39 <Field String b> // 2 4:areturn } public boolean equals(Object obj) { if(obj == this) //* 0 0:aload_1 //* 1 1:aload_0 //* 2 2:if_acmpne 7 return true; // 3 5:iconst_1 // 4 6:ireturn if(!(obj instanceof LaunchOptions)) //* 5 7:aload_1 //* 6 8:instanceof #2 <Class LaunchOptions> //* 7 11:ifne 16 return false; // 8 14:iconst_0 // 9 15:ireturn obj = ((Object) ((LaunchOptions)obj)); // 10 16:aload_1 // 11 17:checkcast #2 <Class LaunchOptions> // 12 20:astore_1 return a == ((LaunchOptions) (obj)).a && aj.a(((Object) (b)), ((Object) (((LaunchOptions) (obj)).b))); // 13 21:aload_0 // 14 22:getfield #37 <Field boolean a> // 15 25:aload_1 // 16 26:getfield #37 <Field boolean a> // 17 29:icmpne 48 // 18 32:aload_0 // 19 33:getfield #39 <Field String b> // 20 36:aload_1 // 21 37:getfield #39 <Field String b> // 22 40:invokestatic #46 <Method boolean aj.a(Object, Object)> // 23 43:ifeq 48 // 24 46:iconst_1 // 25 47:ireturn // 26 48:iconst_0 // 27 49:ireturn } public int hashCode() { return ak.a(new Object[] { Boolean.valueOf(a), b }); // 0 0:iconst_2 // 1 1:anewarray Object[] // 2 4:dup // 3 5:iconst_0 // 4 6:aload_0 // 5 7:getfield #37 <Field boolean a> // 6 10:invokestatic #56 <Method Boolean Boolean.valueOf(boolean)> // 7 13:aastore // 8 14:dup // 9 15:iconst_1 // 10 16:aload_0 // 11 17:getfield #39 <Field String b> // 12 20:aastore // 13 21:invokestatic #61 <Method int ak.a(Object[])> // 14 24:ireturn } public String toString() { return String.format("LaunchOptions(relaunchIfRunning=%b, language=%s)", new Object[] { Boolean.valueOf(a), b }); // 0 0:ldc1 #64 <String "LaunchOptions(relaunchIfRunning=%b, language=%s)"> // 1 2:iconst_2 // 2 3:anewarray Object[] // 3 6:dup // 4 7:iconst_0 // 5 8:aload_0 // 6 9:getfield #37 <Field boolean a> // 7 12:invokestatic #56 <Method Boolean Boolean.valueOf(boolean)> // 8 15:aastore // 9 16:dup // 10 17:iconst_1 // 11 18:aload_0 // 12 19:getfield #39 <Field String b> // 13 22:aastore // 14 23:invokestatic #70 <Method String String.format(String, Object[])> // 15 26:areturn } public void writeToParcel(Parcel parcel, int i) { i = c.a(parcel); // 0 0:aload_1 // 1 1:invokestatic #77 <Method int c.a(Parcel)> // 2 4:istore_2 c.a(parcel, 2, a()); // 3 5:aload_1 // 4 6:iconst_2 // 5 7:aload_0 // 6 8:invokevirtual #79 <Method boolean a()> // 7 11:invokestatic #82 <Method void c.a(Parcel, int, boolean)> c.a(parcel, 3, b(), false); // 8 14:aload_1 // 9 15:iconst_3 // 10 16:aload_0 // 11 17:invokevirtual #84 <Method String b()> // 12 20:iconst_0 // 13 21:invokestatic #87 <Method void c.a(Parcel, int, String, boolean)> c.a(parcel, i); // 14 24:aload_1 // 15 25:iload_2 // 16 26:invokestatic #89 <Method void c.a(Parcel, int)> // 17 29:return } public static final android.os.Parcelable.Creator CREATOR = new u(); private boolean a; private String b; static { // 0 0:new #14 <Class u> // 1 3:dup // 2 4:invokespecial #17 <Method void u()> // 3 7:putstatic #19 <Field android.os.Parcelable$Creator CREATOR> //* 4 10:return } }
32.086957
104
0.505928
bb2a9cde75dbb7e8fb6d8dbdecb8ce697cbaf8ad
877
package com.joylink.userms.cache; import java.util.HashMap; import java.util.Map; import com.joylink.userms.constants.WxConstants; import com.joylink.userms.vo.wx.WxAccessToken; public class WxAccessTokenCache { public static final Map<String, Object> LocalCache = new HashMap<>(); private WxAccessTokenCache() {} public synchronized static void put(String key, Object val) { LocalCache.put(key, val); } public synchronized static Object get(String key) { return LocalCache.get(key); } public synchronized static WxAccessToken getWxAccessToken() { return (WxAccessToken) LocalCache.get(WxConstants.ACCESS_TOKEN); } public synchronized static String getWxAccessTokenString() { WxAccessToken wat = (WxAccessToken) LocalCache.get(WxConstants.ACCESS_TOKEN); if(null != wat) { return wat.getAccess_token(); } else { return null; } } }
23.702703
79
0.749145
b04bd54875d2ae9da3cc27c71f0750fe36b64012
2,367
/** * The MIT License * * Copyright (C) 2015 Asterios Raptis * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package io.github.astrapi69.swing.img; import java.io.File; import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.model.ZipParameters; import org.testng.annotations.Test; import io.github.astrapi69.file.delete.DeleteFileExtensions; import io.github.astrapi69.file.search.PathFinder; /** * The class {@link ImageExtensionsTest}. */ public class ImageExtensionsTest { /** * Test zip. * * @throws Exception * the exception */ @Test(enabled = true) public void testZip() throws Exception { final String filenameprefix = "bell"; final String ext = "png"; final File hImg = PathFinder.getRelativePath(PathFinder.getSrcTestResourcesDir(), "img", "xmas", filenameprefix + "." + ext); final File imgDir = PathFinder.getRelativePath(PathFinder.getSrcTestResourcesDir(), "img", "xmas"); final ZipFile zipFile4j = new ZipFile( imgDir.getAbsolutePath() + File.separator + "testZip.zip"); // Initiate Zip Parameters which define various properties such // as compression method, etc. final ZipParameters parameters = new ZipParameters(); // Add folder to the zip file zipFile4j.addFile(hImg, parameters); DeleteFileExtensions.delete(zipFile4j.getFile()); } }
32.424658
92
0.741867
5d5fe8984ebf139a736998693a0a6b579d0b3bae
1,969
// Copyright (c) 2016-present Revamp package io.nlopez.revamp.sample; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import io.nlopez.revamp.sample.places.PlacesModel; import io.nlopez.revamp.sample.places.PlacesPresenter; import io.nlopez.revamp.sample.places.PlacesViewComponent; import revamp.android.PresenterFragment; public class PlacesFragment extends PresenterFragment<PlacesPresenter, PlacesViewComponent> implements PlacesViewComponent { private static final String ARG_SECTION_NUMBER = "section_number"; @BindView(R.id.section_label) TextView mTextView; public PlacesFragment() { } public static PlacesFragment newInstance(int sectionNumber) { PlacesFragment fragment = new PlacesFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(false); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_pager, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ButterKnife.bind(this, view); presenter().loadData(); } @Override public void showSectionNumber(int sectionNumber) { mTextView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER))); } @Override public PlacesPresenter buildPresenter() { return new PlacesPresenter(new PlacesModel(getArguments().getInt(ARG_SECTION_NUMBER))); } }
30.292308
124
0.772473
49c9745a315a235a73a9fa8de5c51e86c80fe984
1,882
package org.michenux.drodrolib.battery; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.BatteryManager; public class BatteryUtils { public static boolean isChargingOrFull( Context context ) { IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = context.registerReceiver(null, intentFilter); return isChargingOrFull(batteryStatus); } public static boolean isChargingOrFull(Intent batteryStatus) { int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); return status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL; } /** * * @param context * @return BatteryManager.BATTERY_PLUGGED_USB, BatteryManager.BATTERY_PLUGGED_AC, BatteryManager.BATTERY_PLUGGED_WIRELESS */ public static int getChargingMode( Context context ) { IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = context.registerReceiver(null, intentFilter); return getChargingMode(batteryStatus); } public static int getChargingMode(Intent batteryStatus) { return batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); } public static float getChargePct( Context context ) { IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = context.registerReceiver(null, intentFilter); return getChargePct(batteryStatus); } public static float getChargePct(Intent batteryStatus) { int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1); return level / (float) scale ; } }
39.208333
125
0.742295
64dba60b4ea59465c33efb08f22241362bc6bacf
1,552
package org.openbaton.nfvo.api; import org.openbaton.catalogue.mano.descriptor.VirtualNetworkFunctionDescriptor; import org.openbaton.exceptions.BadFormatException; import org.openbaton.exceptions.CyclicDependenciesException; import org.openbaton.exceptions.NetworkServiceIntegrityException; import org.openbaton.exceptions.NotFoundException; import org.openbaton.nfvo.core.interfaces.VirtualNetworkFunctionManagement; import org.openbaton.tosca.parser.TOSCAParser; import org.openbaton.tosca.templates.VNFDTemplate; import org.openbaton.utils.Utils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; /** * Created by rvl on 26.08.16. */ @RestController @RequestMapping("/api/v1/vnfd-tosca") public class RestToscaVirtualNetworkFunctionDescriptor { @Autowired private VirtualNetworkFunctionManagement vnfdManagement; @Autowired private TOSCAParser toscaParser; @RequestMapping(method = RequestMethod.POST) @ResponseStatus(HttpStatus.ACCEPTED) private VirtualNetworkFunctionDescriptor postTosca( @RequestBody String vnfd_yaml, @RequestHeader(value = "project-id") String projectId) throws NetworkServiceIntegrityException, BadFormatException, NotFoundException, CyclicDependenciesException { VNFDTemplate vnfdTemplate = Utils.stringToVNFDTemplate(vnfd_yaml); VirtualNetworkFunctionDescriptor vnfd = toscaParser.parseVNFDTemplate(vnfdTemplate); return vnfdManagement.add(vnfd, projectId); } }
39.794872
91
0.829897
4770262381c2122d00b9b041ded8ee66334305e2
1,730
package com.spark.platform.wx.shop.biz.setting.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.spark.platform.common.base.constants.GlobalsConstants; import com.spark.platform.common.base.enums.DelFlagEnum; import com.spark.platform.wx.shop.api.entity.setting.ShopSettingSwiper; import com.spark.platform.wx.shop.api.vo.SwiperVo; import com.spark.platform.wx.shop.biz.setting.dao.ShopSettingSwiperDao; import com.spark.platform.wx.shop.biz.setting.service.ShopSettingSwiperService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; import java.util.List; /** * <p> * 首页轮播图 服务实现类 * </p> * * @author wangdingfeng * @since 2021-01-03 */ @Service public class ShopSettingSwiperServiceImpl extends ServiceImpl<ShopSettingSwiperDao, ShopSettingSwiper> implements ShopSettingSwiperService { @Override public IPage finPage(Page page, ShopSettingSwiper shopSettingSwiper) { QueryWrapper wrapper = new QueryWrapper(); wrapper.eq(StringUtils.isNotBlank(shopSettingSwiper.getStatus()),"s.status",shopSettingSwiper.getStatus()); wrapper.eq("s.del_flag", DelFlagEnum.NORMAL.getValue()); return super.baseMapper.listPage(page, wrapper); } @Override public List<SwiperVo> limitSwiperVo(Integer limit) { return super.baseMapper.limitSwiperVo(limit); } }
39.318182
140
0.792486
eb6eb68acafa60577265a00e2902aa4f885e0598
1,849
package com.lc.spittr.config; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.tiles3.TilesConfigurer; import org.springframework.web.servlet.view.tiles3.TilesViewResolver; /** * @author DELL * @date 2022/1/19 20:54 */ @Configuration @EnableWebMvc @ComponentScan("com.lc.spittr.web") public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureDefaultServletHandling( DefaultServletHandlerConfigurer configurer) { configurer.enable(); } @Bean public MessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("classpath:messages"); messageSource.setCacheSeconds(10); return messageSource; } //Tiles @Bean public TilesConfigurer tilesConfigurer() { TilesConfigurer tiles = new TilesConfigurer(); tiles.setDefinitions(new String[]{ "/WEB-INF/layout/tiles.xml", "/WEB-INF/views/**/tiles.xml" }); tiles.setCheckRefresh(true); return tiles; } @Bean public ViewResolver viewResolver() { return new TilesViewResolver(); } }
33.017857
89
0.742023
11d7bef2129dbac50c4462b455b225aef8e1047b
513
package com.linguahack.app.algorithm; import com.linguahack.app.core.TextStats; import java.util.HashMap; import java.util.Map; public class AlgorithmMockImpl implements Algorithm { public Map<String, Double> process(TextStats t1, TextStats t2) { Map<String, Double> test = new HashMap<String, Double>(); test.put("home", 99.7); test.put("work", 54.2); test.put("chill", 27.1); test.put("sex", 29.8); test.put("friends", 93.0); return test; } }
25.65
68
0.635478
bd3a2e78c980ffd92fee77cb5bb25c6eb5be15f7
2,483
/* * Copyright 1999-2101 Alibaba Group Holding Ltd. * * 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.alibaba.druid.sql.dialect.sqlserver.ast; import java.util.ArrayList; import java.util.List; import com.alibaba.druid.sql.ast.SQLDataType; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.statement.SQLTableElement; import com.alibaba.druid.sql.dialect.sqlserver.visitor.SQLServerASTVisitor; public class SQLServerDeclareItem extends SQLServerObjectImpl { protected Type type; protected SQLExpr name; protected SQLDataType dataType; protected SQLExpr value; protected List<SQLTableElement> tableElementList = new ArrayList<SQLTableElement>(); @Override public void accept0(SQLServerASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, this.name); acceptChild(visitor, this.dataType); acceptChild(visitor, this.value); acceptChild(visitor, this.tableElementList); } visitor.endVisit(this); } public SQLExpr getName() { return name; } public void setName(SQLExpr name) { this.name = name; } public SQLDataType getDataType() { return dataType; } public void setDataType(SQLDataType dataType) { this.dataType = dataType; } public SQLExpr getValue() { return value; } public void setValue(SQLExpr value) { this.value = value; } public List<SQLTableElement> getTableElementList() { return tableElementList; } public void setTableElementList(List<SQLTableElement> tableElementList) { this.tableElementList = tableElementList; } public enum Type { TABLE, LOCAL, CURSOR; } public Type getType() { return type; } public void setType(Type type) { this.type = type; } }
26.414894
88
0.668546
d8e573d3fa1aea84f09898267db9e9e9ba6c4b8e
2,644
package com.twinkle.framework.datasource.spring.boot.autoconfigure; import com.twinkle.framework.datasource.spring.boot.autoconfigure.druid.DruidConfig; import com.twinkle.framework.datasource.spring.boot.autoconfigure.hikari.HikariCpConfig; import com.twinkle.framework.datasource.strategy.LoadBalanceRoutingDataSourceStrategy; import com.twinkle.framework.datasource.strategy.RoutingDataSourceStrategy; import com.twinkle.framework.datasource.utils.CryptoUtil; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; import org.springframework.core.Ordered; import java.util.LinkedHashMap; import java.util.Map; /** * Function: TODO ADD FUNCTION. <br/> * Reason: TODO ADD REASON. <br/> * Date: 10/12/19 6:31 PM<br/> * * @author chenxj * @see DataSourceProperties * @since JDK 1.8 */ @Slf4j @Getter @Setter @ConfigurationProperties(prefix = DynamicDataSourceProperties.PREFIX) public class DynamicDataSourceProperties { public static final String PREFIX = "spring.datasource.dynamic"; public static final String HEALTH = PREFIX + ".health"; /** * Required DataSource. Default: master. */ private String primary = "master"; /** * If Ture, * Did not find the datasource, will throw exception. * Otherwise * will use the primary datasource. */ private Boolean strict = false; /** * Enable p6spy or not? */ private Boolean p6spy = false; /** * Enable spring actuator to do the check health? */ private boolean health = false; /** * All of the data sources. */ private Map<String, DataSourceProperty> datasource = new LinkedHashMap<>(); /** * The routing algorithm for multi read(slave) data sources, * Use LB strategy by default. */ private Class<? extends RoutingDataSourceStrategy> strategy = LoadBalanceRoutingDataSourceStrategy.class; /** * aop's order * Highest by default. */ private Integer order = Ordered.HIGHEST_PRECEDENCE; /** * Druid global parameters. */ @NestedConfigurationProperty private DruidConfig druid = new DruidConfig(); /** * HikariCp global parameters. */ @NestedConfigurationProperty private HikariCpConfig hikari = new HikariCpConfig(); /** * Global publicKey */ private String publicKey = CryptoUtil.DEFAULT_PUBLIC_KEY_STRING; }
31.105882
109
0.720121
f66e76568712e7d316edaa2554c5651d603b5b75
2,166
package com.example.android.bakingbuddy; import android.support.test.espresso.contrib.RecyclerViewActions; import android.support.test.filters.LargeTest; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isClickable; import static android.support.test.espresso.matcher.ViewMatchers.isCompletelyDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withId; @RunWith(AndroidJUnit4.class) @LargeTest public class BakingBuddyInstrumentedTest { @Rule public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(MainActivity.class,true, true); @Test public void testNavigationUntilDetail(){ // Click Main Activity item and check next screen onView(withId(R.id.rv_recipes)) .perform(RecyclerViewActions.actionOnItemAtPosition(0,click())); onView(withId(R.id.rv_ingredients)) .check(matches(isDisplayed())); onView(withId(R.id.rv_steps)) .check(matches(isDisplayed())); // Click step detail item and check next screen onView(withId(R.id.rv_steps)) .perform(RecyclerViewActions.actionOnItemAtPosition(0, click())); onView(withId(R.id.player_step_video)) .check(matches(isCompletelyDisplayed())); onView(withId(R.id.tv_step_description)) .check(matches(isCompletelyDisplayed())); // Click on Next to go to next step and check if previous button is shown onView(withId(R.id.bt_next_step)) .perform(click()); onView(withId(R.id.bt_previous_step)) .check(matches(isClickable())); } }
40.111111
87
0.718837
d8241c644d9bba782d21ff0d09d6f469d31869f6
1,612
package org.esfinge.guardian.interceptor.cglib; import java.lang.reflect.Method; import org.esfinge.guardian.context.WrappedObj; import org.esfinge.guardian.exception.ProxyCreationException; import org.esfinge.guardian.interceptor.GuardianInterceptor; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; public class CGLIBProxy extends GuardianInterceptor implements MethodInterceptor { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Exception { return guardianIntercept(obj, method, args); } @Override @SuppressWarnings("unchecked") public <E> E createGuardedObject(E obj, Object[] constructorArgs, WrappedObj<?>... dynamicContext) { CGLIBProxy proxy = new CGLIBProxy(); proxy.setDynamicContext(dynamicContext); proxy.setGuardedObject(obj); Enhancer e = new Enhancer(); e.setSuperclass(obj.getClass()); e.setCallback(proxy); E returnObj = null; try { if (constructorArgs == null) { returnObj = (E) e.create(); } else { Class<?>[] argTypes = new Class<?>[constructorArgs.length]; for (int i=0; i < constructorArgs.length; i++) { argTypes[i] = constructorArgs[i].getClass(); } returnObj = (E) e.create(argTypes, constructorArgs); } } catch (Exception ex) { String msg = "Could not create proxy. Try checking the number of atributes in the constructor of: " + obj.getClass().getSimpleName(); throw new ProxyCreationException(msg, ex); } return returnObj; } }
33.583333
137
0.712779
7a1ab9da1b103d685a6b130468ef5df15a98f0f8
1,668
package com.skeqi.mes.util.yp.oa; import java.util.List; import com.alibaba.fastjson.JSONObject; /** * 检查是否需要审批 * * @author yinp * */ public class Check { public void runCheck(String step, Integer userId) throws Exception { List<JSONObject> stepList = JSONObject.parseArray(step, JSONObject.class); // 只保留审批 for (int i = 0; i < stepList.size(); i++) { if (!stepList.get(i).getString("type").equals("approver")) { stepList.remove(i); i--; } } for (int i = 0; i < stepList.size(); i++) { JSONObject properties = stepList.get(i).getJSONObject("properties"); // 审批方式 String counterSign = properties.getString("counterSign"); // 审批人 String approvers = properties.getString("approvers"); List<JSONObject> approversList = JSONObject.parseArray(approvers, JSONObject.class); if (counterSign.equals("1")) { // 依次审批 if (stepList.get(i).getString("stepState").equals("未完成")) { for (int j = 0; j < approversList.size(); j++) { if (approversList.get(j).getString("approvalOrNot").equals("未批")) { if (approversList.get(j).getString("id").equals(userId.toString())) { return; } throw new Exception("您无需操作"); } if (j == approversList.size() - 1) { throw new Exception("您无需操作"); } } } } else { // 会签、或签 if (stepList.get(i).getString("stepState").equals("未完成")) { for (int j = 0; j < approversList.size(); j++) { if (approversList.get(j).getString("id").equals(userId.toString())) { return; } if (j == approversList.size() - 1) { throw new Exception("您无需操作"); } } } } } } }
24.529412
87
0.596523
51c124232608d91bb7631e1dd996388a6648081f
608
package com.jimsp.accountsettlement.converter; import org.springframework.stereotype.Component; import com.jimsp.accountsettlement.canonico.AccountSettlementCanonico; import com.jimsp.accountsettlement.model.AccountSettlementData; @Component public class AccountSettlementDataToAccountSettlementCanonico { public AccountSettlementCanonico accountSettlementCanonicoToAccountSettlementData( final AccountSettlementData accountSettlementData) { return new AccountSettlementCanonico(accountSettlementData.getContaContabil(), accountSettlementData.getData(), accountSettlementData.getValor()); } }
35.764706
113
0.866776
c7bb8f843dcc8bbbe3ffac0213df634e4963a8a4
544
package skyblock.mixin; import net.minecraft.structure.StructurePiece; import net.minecraft.util.BlockMirror; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; import org.spongepowered.asm.mixin.gen.Invoker; @Mixin(StructurePiece.class) public interface StructurePieceAccessor { @Accessor("mirror") BlockMirror getMirror(); @Invoker int invokeApplyXTransform(int x, int z); @Invoker int invokeApplyYTransform(int y); @Invoker int invokeApplyZTransform(int x, int z); }
27.2
48
0.768382
a5b66f974389b8d62ecf378b086a8723ce1b6676
1,811
/*- * ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ * The Apache Software License, Version 2.0 * —————————————————————————————————————————————————————————————————————————————— * Copyright (C) 2013 - 2020 Autonomic, LLC - All rights reserved * —————————————————————————————————————————————————————————————————————————————— * Proprietary and confidential. * * NOTICE: All information contained herein is, and remains the property of * Autonomic, LLC and its suppliers, if any. The intellectual and technical * concepts contained herein are proprietary to Autonomic, LLC and its suppliers * and may be covered by U.S. and Foreign Patents, patents in process, and are * protected by trade secret or copyright law. Dissemination of this information * or reproduction of this material is strictly forbidden unless prior written * permission is obtained from Autonomic, LLC. * * Unauthorized copy of this file, via any medium is strictly prohibited. * ______________________________________________________________________________ */ package com.github.davidmoten.fsm.example.account; import java.math.BigDecimal; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public final class Account { public final String id; public final BigDecimal balance; @JsonCreator public Account(@JsonProperty("id") String id, @JsonProperty("balance") BigDecimal balance) { this.id = id; this.balance = balance; } @Override public String toString() { StringBuilder b = new StringBuilder(); b.append("Account [id="); b.append(id); b.append(", balance="); b.append(balance); b.append("]"); return b.toString(); } }
36.22
96
0.620099
1f7372c543c6ccce4b5935100edee895f2c57428
62,591
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Copyright (C) 2007 The Guava 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. */ end_comment begin_package DECL|package|com.google.common.io package|package name|com operator|. name|google operator|. name|common operator|. name|io package|; end_package begin_import import|import static name|com operator|. name|google operator|. name|common operator|. name|truth operator|. name|Truth operator|. name|assertThat import|; end_import begin_import import|import name|com operator|. name|google operator|. name|common operator|. name|base operator|. name|Charsets import|; end_import begin_import import|import name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|ImmutableList import|; end_import begin_import import|import name|com operator|. name|google operator|. name|common operator|. name|hash operator|. name|Hashing import|; end_import begin_import import|import name|com operator|. name|google operator|. name|common operator|. name|primitives operator|. name|Bytes import|; end_import begin_import import|import name|java operator|. name|io operator|. name|BufferedReader import|; end_import begin_import import|import name|java operator|. name|io operator|. name|BufferedWriter import|; end_import begin_import import|import name|java operator|. name|io operator|. name|ByteArrayOutputStream import|; end_import begin_import import|import name|java operator|. name|io operator|. name|File import|; end_import begin_import import|import name|java operator|. name|io operator|. name|FileNotFoundException import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|io operator|. name|PrintWriter import|; end_import begin_import import|import name|java operator|. name|io operator|. name|RandomAccessFile import|; end_import begin_import import|import name|java operator|. name|nio operator|. name|ByteBuffer import|; end_import begin_import import|import name|java operator|. name|nio operator|. name|MappedByteBuffer import|; end_import begin_import import|import name|java operator|. name|nio operator|. name|channels operator|. name|FileChannel operator|. name|MapMode import|; end_import begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Arrays import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Random import|; end_import begin_import import|import name|junit operator|. name|framework operator|. name|TestSuite import|; end_import begin_comment comment|/** * Unit test for {@link Files}. * *<p>Note: {@link Files#fileTraverser()} is tested in {@link FilesFileTraverserTest}. * * @author Chris Nokleberg */ end_comment begin_class DECL|class|FilesTest specifier|public class|class name|FilesTest extends|extends name|IoTestCase block|{ DECL|method|suite () specifier|public specifier|static name|TestSuite name|suite parameter_list|() block|{ name|TestSuite name|suite init|= operator|new name|TestSuite argument_list|() decl_stmt|; name|suite operator|. name|addTest argument_list|( name|ByteSourceTester operator|. name|tests argument_list|( literal|"Files.asByteSource[File]" argument_list|, name|SourceSinkFactories operator|. name|fileByteSourceFactory argument_list|() argument_list|, literal|true argument_list|) argument_list|) expr_stmt|; name|suite operator|. name|addTest argument_list|( name|ByteSinkTester operator|. name|tests argument_list|( literal|"Files.asByteSink[File]" argument_list|, name|SourceSinkFactories operator|. name|fileByteSinkFactory argument_list|() argument_list|) argument_list|) expr_stmt|; name|suite operator|. name|addTest argument_list|( name|ByteSinkTester operator|. name|tests argument_list|( literal|"Files.asByteSink[File, APPEND]" argument_list|, name|SourceSinkFactories operator|. name|appendingFileByteSinkFactory argument_list|() argument_list|) argument_list|) expr_stmt|; name|suite operator|. name|addTest argument_list|( name|CharSourceTester operator|. name|tests argument_list|( literal|"Files.asCharSource[File, Charset]" argument_list|, name|SourceSinkFactories operator|. name|fileCharSourceFactory argument_list|() argument_list|, literal|false argument_list|) argument_list|) expr_stmt|; name|suite operator|. name|addTest argument_list|( name|CharSinkTester operator|. name|tests argument_list|( literal|"Files.asCharSink[File, Charset]" argument_list|, name|SourceSinkFactories operator|. name|fileCharSinkFactory argument_list|() argument_list|) argument_list|) expr_stmt|; name|suite operator|. name|addTest argument_list|( name|CharSinkTester operator|. name|tests argument_list|( literal|"Files.asCharSink[File, Charset, APPEND]" argument_list|, name|SourceSinkFactories operator|. name|appendingFileCharSinkFactory argument_list|() argument_list|) argument_list|) expr_stmt|; name|suite operator|. name|addTestSuite argument_list|( name|FilesTest operator|. name|class argument_list|) expr_stmt|; return|return name|suite return|; block|} DECL|method|testRoundTripSources () specifier|public name|void name|testRoundTripSources parameter_list|() throws|throws name|Exception block|{ name|File name|asciiFile init|= name|getTestFile argument_list|( literal|"ascii.txt" argument_list|) decl_stmt|; name|ByteSource name|byteSource init|= name|Files operator|. name|asByteSource argument_list|( name|asciiFile argument_list|) decl_stmt|; name|assertSame argument_list|( name|byteSource argument_list|, name|byteSource operator|. name|asCharSource argument_list|( name|Charsets operator|. name|UTF_8 argument_list|) operator|. name|asByteSource argument_list|( name|Charsets operator|. name|UTF_8 argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testToByteArray () specifier|public name|void name|testToByteArray parameter_list|() throws|throws name|IOException block|{ name|File name|asciiFile init|= name|getTestFile argument_list|( literal|"ascii.txt" argument_list|) decl_stmt|; name|File name|i18nFile init|= name|getTestFile argument_list|( literal|"i18n.txt" argument_list|) decl_stmt|; name|assertTrue argument_list|( name|Arrays operator|. name|equals argument_list|( name|ASCII operator|. name|getBytes argument_list|( name|Charsets operator|. name|US_ASCII argument_list|) argument_list|, name|Files operator|. name|toByteArray argument_list|( name|asciiFile argument_list|) argument_list|) argument_list|) expr_stmt|; name|assertTrue argument_list|( name|Arrays operator|. name|equals argument_list|( name|I18N operator|. name|getBytes argument_list|( name|Charsets operator|. name|UTF_8 argument_list|) argument_list|, name|Files operator|. name|toByteArray argument_list|( name|i18nFile argument_list|) argument_list|) argument_list|) expr_stmt|; name|assertTrue argument_list|( name|Arrays operator|. name|equals argument_list|( name|I18N operator|. name|getBytes argument_list|( name|Charsets operator|. name|UTF_8 argument_list|) argument_list|, name|Files operator|. name|asByteSource argument_list|( name|i18nFile argument_list|) operator|. name|read argument_list|() argument_list|) argument_list|) expr_stmt|; block|} comment|/** A {@link File} that provides a specialized value for {@link File#length()}. */ DECL|class|BadLengthFile specifier|private specifier|static class|class name|BadLengthFile extends|extends name|File block|{ DECL|field|badLength specifier|private specifier|final name|long name|badLength decl_stmt|; DECL|method|BadLengthFile (File delegate, long badLength) specifier|public name|BadLengthFile parameter_list|( name|File name|delegate parameter_list|, name|long name|badLength parameter_list|) block|{ name|super argument_list|( name|delegate operator|. name|getPath argument_list|() argument_list|) expr_stmt|; name|this operator|. name|badLength operator|= name|badLength expr_stmt|; block|} annotation|@ name|Override DECL|method|length () specifier|public name|long name|length parameter_list|() block|{ return|return name|badLength return|; block|} DECL|field|serialVersionUID specifier|private specifier|static specifier|final name|long name|serialVersionUID init|= literal|0 decl_stmt|; block|} DECL|method|testToString () specifier|public name|void name|testToString parameter_list|() throws|throws name|IOException block|{ name|File name|asciiFile init|= name|getTestFile argument_list|( literal|"ascii.txt" argument_list|) decl_stmt|; name|File name|i18nFile init|= name|getTestFile argument_list|( literal|"i18n.txt" argument_list|) decl_stmt|; name|assertEquals argument_list|( name|ASCII argument_list|, name|Files operator|. name|toString argument_list|( name|asciiFile argument_list|, name|Charsets operator|. name|US_ASCII argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( name|I18N argument_list|, name|Files operator|. name|toString argument_list|( name|i18nFile argument_list|, name|Charsets operator|. name|UTF_8 argument_list|) argument_list|) expr_stmt|; name|assertThat argument_list|( name|Files operator|. name|toString argument_list|( name|i18nFile argument_list|, name|Charsets operator|. name|US_ASCII argument_list|) argument_list|) operator|. name|isNotEqualTo argument_list|( name|I18N argument_list|) expr_stmt|; block|} DECL|method|testWriteString () specifier|public name|void name|testWriteString parameter_list|() throws|throws name|IOException block|{ name|File name|temp init|= name|createTempFile argument_list|() decl_stmt|; name|Files operator|. name|write argument_list|( name|I18N argument_list|, name|temp argument_list|, name|Charsets operator|. name|UTF_16LE argument_list|) expr_stmt|; name|assertEquals argument_list|( name|I18N argument_list|, name|Files operator|. name|toString argument_list|( name|temp argument_list|, name|Charsets operator|. name|UTF_16LE argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testWriteBytes () specifier|public name|void name|testWriteBytes parameter_list|() throws|throws name|IOException block|{ name|File name|temp init|= name|createTempFile argument_list|() decl_stmt|; name|byte index|[] name|data init|= name|newPreFilledByteArray argument_list|( literal|2000 argument_list|) decl_stmt|; name|Files operator|. name|write argument_list|( name|data argument_list|, name|temp argument_list|) expr_stmt|; name|assertTrue argument_list|( name|Arrays operator|. name|equals argument_list|( name|data argument_list|, name|Files operator|. name|toByteArray argument_list|( name|temp argument_list|) argument_list|) argument_list|) expr_stmt|; try|try block|{ name|Files operator|. name|write argument_list|( literal|null argument_list|, name|temp argument_list|) expr_stmt|; name|fail argument_list|( literal|"expected exception" argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|NullPointerException name|expected parameter_list|) block|{ } block|} DECL|method|testAppendString () specifier|public name|void name|testAppendString parameter_list|() throws|throws name|IOException block|{ name|File name|temp init|= name|createTempFile argument_list|() decl_stmt|; name|Files operator|. name|append argument_list|( name|I18N argument_list|, name|temp argument_list|, name|Charsets operator|. name|UTF_16LE argument_list|) expr_stmt|; name|assertEquals argument_list|( name|I18N argument_list|, name|Files operator|. name|toString argument_list|( name|temp argument_list|, name|Charsets operator|. name|UTF_16LE argument_list|) argument_list|) expr_stmt|; name|Files operator|. name|append argument_list|( name|I18N argument_list|, name|temp argument_list|, name|Charsets operator|. name|UTF_16LE argument_list|) expr_stmt|; name|assertEquals argument_list|( name|I18N operator|+ name|I18N argument_list|, name|Files operator|. name|toString argument_list|( name|temp argument_list|, name|Charsets operator|. name|UTF_16LE argument_list|) argument_list|) expr_stmt|; name|Files operator|. name|append argument_list|( name|I18N argument_list|, name|temp argument_list|, name|Charsets operator|. name|UTF_16LE argument_list|) expr_stmt|; name|assertEquals argument_list|( name|I18N operator|+ name|I18N operator|+ name|I18N argument_list|, name|Files operator|. name|toString argument_list|( name|temp argument_list|, name|Charsets operator|. name|UTF_16LE argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testCopyToOutputStream () specifier|public name|void name|testCopyToOutputStream parameter_list|() throws|throws name|IOException block|{ name|File name|i18nFile init|= name|getTestFile argument_list|( literal|"i18n.txt" argument_list|) decl_stmt|; name|ByteArrayOutputStream name|out init|= operator|new name|ByteArrayOutputStream argument_list|() decl_stmt|; name|Files operator|. name|copy argument_list|( name|i18nFile argument_list|, name|out argument_list|) expr_stmt|; name|assertEquals argument_list|( name|I18N argument_list|, name|out operator|. name|toString argument_list|( literal|"UTF-8" argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testCopyToAppendable () specifier|public name|void name|testCopyToAppendable parameter_list|() throws|throws name|IOException block|{ name|File name|i18nFile init|= name|getTestFile argument_list|( literal|"i18n.txt" argument_list|) decl_stmt|; name|StringBuilder name|sb init|= operator|new name|StringBuilder argument_list|() decl_stmt|; name|Files operator|. name|copy argument_list|( name|i18nFile argument_list|, name|Charsets operator|. name|UTF_8 argument_list|, name|sb argument_list|) expr_stmt|; name|assertEquals argument_list|( name|I18N argument_list|, name|sb operator|. name|toString argument_list|() argument_list|) expr_stmt|; block|} DECL|method|testCopyFile () specifier|public name|void name|testCopyFile parameter_list|() throws|throws name|IOException block|{ name|File name|i18nFile init|= name|getTestFile argument_list|( literal|"i18n.txt" argument_list|) decl_stmt|; name|File name|temp init|= name|createTempFile argument_list|() decl_stmt|; name|Files operator|. name|copy argument_list|( name|i18nFile argument_list|, name|temp argument_list|) expr_stmt|; name|assertEquals argument_list|( name|I18N argument_list|, name|Files operator|. name|toString argument_list|( name|temp argument_list|, name|Charsets operator|. name|UTF_8 argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testCopyEqualFiles () specifier|public name|void name|testCopyEqualFiles parameter_list|() throws|throws name|IOException block|{ name|File name|temp1 init|= name|createTempFile argument_list|() decl_stmt|; name|File name|temp2 init|= name|file argument_list|( name|temp1 operator|. name|getPath argument_list|() argument_list|) decl_stmt|; name|assertEquals argument_list|( name|temp1 argument_list|, name|temp2 argument_list|) expr_stmt|; name|Files operator|. name|write argument_list|( name|ASCII argument_list|, name|temp1 argument_list|, name|Charsets operator|. name|UTF_8 argument_list|) expr_stmt|; try|try block|{ name|Files operator|. name|copy argument_list|( name|temp1 argument_list|, name|temp2 argument_list|) expr_stmt|; name|fail argument_list|( literal|"Expected an IAE to be thrown but wasn't" argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|IllegalArgumentException name|expected parameter_list|) block|{ } name|assertEquals argument_list|( name|ASCII argument_list|, name|Files operator|. name|toString argument_list|( name|temp1 argument_list|, name|Charsets operator|. name|UTF_8 argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testCopySameFile () specifier|public name|void name|testCopySameFile parameter_list|() throws|throws name|IOException block|{ name|File name|temp init|= name|createTempFile argument_list|() decl_stmt|; name|Files operator|. name|write argument_list|( name|ASCII argument_list|, name|temp argument_list|, name|Charsets operator|. name|UTF_8 argument_list|) expr_stmt|; try|try block|{ name|Files operator|. name|copy argument_list|( name|temp argument_list|, name|temp argument_list|) expr_stmt|; name|fail argument_list|( literal|"Expected an IAE to be thrown but wasn't" argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|IllegalArgumentException name|expected parameter_list|) block|{ } name|assertEquals argument_list|( name|ASCII argument_list|, name|Files operator|. name|toString argument_list|( name|temp argument_list|, name|Charsets operator|. name|UTF_8 argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testCopyIdenticalFiles () specifier|public name|void name|testCopyIdenticalFiles parameter_list|() throws|throws name|IOException block|{ name|File name|temp1 init|= name|createTempFile argument_list|() decl_stmt|; name|Files operator|. name|write argument_list|( name|ASCII argument_list|, name|temp1 argument_list|, name|Charsets operator|. name|UTF_8 argument_list|) expr_stmt|; name|File name|temp2 init|= name|createTempFile argument_list|() decl_stmt|; name|Files operator|. name|write argument_list|( name|ASCII argument_list|, name|temp2 argument_list|, name|Charsets operator|. name|UTF_8 argument_list|) expr_stmt|; name|Files operator|. name|copy argument_list|( name|temp1 argument_list|, name|temp2 argument_list|) expr_stmt|; name|assertEquals argument_list|( name|ASCII argument_list|, name|Files operator|. name|toString argument_list|( name|temp2 argument_list|, name|Charsets operator|. name|UTF_8 argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testEqual () specifier|public name|void name|testEqual parameter_list|() throws|throws name|IOException block|{ name|File name|asciiFile init|= name|getTestFile argument_list|( literal|"ascii.txt" argument_list|) decl_stmt|; name|File name|i18nFile init|= name|getTestFile argument_list|( literal|"i18n.txt" argument_list|) decl_stmt|; name|assertFalse argument_list|( name|Files operator|. name|equal argument_list|( name|asciiFile argument_list|, name|i18nFile argument_list|) argument_list|) expr_stmt|; name|assertTrue argument_list|( name|Files operator|. name|equal argument_list|( name|asciiFile argument_list|, name|asciiFile argument_list|) argument_list|) expr_stmt|; name|File name|temp init|= name|createTempFile argument_list|() decl_stmt|; name|Files operator|. name|copy argument_list|( name|asciiFile argument_list|, name|temp argument_list|) expr_stmt|; name|assertTrue argument_list|( name|Files operator|. name|equal argument_list|( name|asciiFile argument_list|, name|temp argument_list|) argument_list|) expr_stmt|; name|Files operator|. name|copy argument_list|( name|i18nFile argument_list|, name|temp argument_list|) expr_stmt|; name|assertTrue argument_list|( name|Files operator|. name|equal argument_list|( name|i18nFile argument_list|, name|temp argument_list|) argument_list|) expr_stmt|; name|Files operator|. name|copy argument_list|( name|asciiFile argument_list|, name|temp argument_list|) expr_stmt|; name|RandomAccessFile name|rf init|= operator|new name|RandomAccessFile argument_list|( name|temp argument_list|, literal|"rw" argument_list|) decl_stmt|; name|rf operator|. name|writeByte argument_list|( literal|0 argument_list|) expr_stmt|; name|rf operator|. name|close argument_list|() expr_stmt|; name|assertEquals argument_list|( name|asciiFile operator|. name|length argument_list|() argument_list|, name|temp operator|. name|length argument_list|() argument_list|) expr_stmt|; name|assertFalse argument_list|( name|Files operator|. name|equal argument_list|( name|asciiFile argument_list|, name|temp argument_list|) argument_list|) expr_stmt|; name|assertTrue argument_list|( name|Files operator|. name|asByteSource argument_list|( name|asciiFile argument_list|) operator|. name|contentEquals argument_list|( name|Files operator|. name|asByteSource argument_list|( name|asciiFile argument_list|) argument_list|) argument_list|) expr_stmt|; comment|// 0-length files have special treatment (/proc, etc.) name|assertTrue argument_list|( name|Files operator|. name|equal argument_list|( name|asciiFile argument_list|, operator|new name|BadLengthFile argument_list|( name|asciiFile argument_list|, literal|0 argument_list|) argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testNewReader () specifier|public name|void name|testNewReader parameter_list|() throws|throws name|IOException block|{ name|File name|asciiFile init|= name|getTestFile argument_list|( literal|"ascii.txt" argument_list|) decl_stmt|; try|try block|{ name|Files operator|. name|newReader argument_list|( name|asciiFile argument_list|, literal|null argument_list|) expr_stmt|; name|fail argument_list|( literal|"expected exception" argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|NullPointerException name|expected parameter_list|) block|{ } try|try block|{ name|Files operator|. name|newReader argument_list|( literal|null argument_list|, name|Charsets operator|. name|UTF_8 argument_list|) expr_stmt|; name|fail argument_list|( literal|"expected exception" argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|NullPointerException name|expected parameter_list|) block|{ } name|BufferedReader name|r init|= name|Files operator|. name|newReader argument_list|( name|asciiFile argument_list|, name|Charsets operator|. name|US_ASCII argument_list|) decl_stmt|; try|try block|{ name|assertEquals argument_list|( name|ASCII argument_list|, name|r operator|. name|readLine argument_list|() argument_list|) expr_stmt|; block|} finally|finally block|{ name|r operator|. name|close argument_list|() expr_stmt|; block|} block|} DECL|method|testNewWriter () specifier|public name|void name|testNewWriter parameter_list|() throws|throws name|IOException block|{ name|File name|temp init|= name|createTempFile argument_list|() decl_stmt|; try|try block|{ name|Files operator|. name|newWriter argument_list|( name|temp argument_list|, literal|null argument_list|) expr_stmt|; name|fail argument_list|( literal|"expected exception" argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|NullPointerException name|expected parameter_list|) block|{ } try|try block|{ name|Files operator|. name|newWriter argument_list|( literal|null argument_list|, name|Charsets operator|. name|UTF_8 argument_list|) expr_stmt|; name|fail argument_list|( literal|"expected exception" argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|NullPointerException name|expected parameter_list|) block|{ } name|BufferedWriter name|w init|= name|Files operator|. name|newWriter argument_list|( name|temp argument_list|, name|Charsets operator|. name|UTF_8 argument_list|) decl_stmt|; try|try block|{ name|w operator|. name|write argument_list|( name|I18N argument_list|) expr_stmt|; block|} finally|finally block|{ name|w operator|. name|close argument_list|() expr_stmt|; block|} name|File name|i18nFile init|= name|getTestFile argument_list|( literal|"i18n.txt" argument_list|) decl_stmt|; name|assertTrue argument_list|( name|Files operator|. name|equal argument_list|( name|i18nFile argument_list|, name|temp argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testTouch () specifier|public name|void name|testTouch parameter_list|() throws|throws name|IOException block|{ name|File name|temp init|= name|createTempFile argument_list|() decl_stmt|; name|assertTrue argument_list|( name|temp operator|. name|exists argument_list|() argument_list|) expr_stmt|; name|assertTrue argument_list|( name|temp operator|. name|delete argument_list|() argument_list|) expr_stmt|; name|assertFalse argument_list|( name|temp operator|. name|exists argument_list|() argument_list|) expr_stmt|; name|Files operator|. name|touch argument_list|( name|temp argument_list|) expr_stmt|; name|assertTrue argument_list|( name|temp operator|. name|exists argument_list|() argument_list|) expr_stmt|; name|Files operator|. name|touch argument_list|( name|temp argument_list|) expr_stmt|; name|assertTrue argument_list|( name|temp operator|. name|exists argument_list|() argument_list|) expr_stmt|; try|try block|{ name|Files operator|. name|touch argument_list|( operator|new name|File argument_list|( name|temp operator|. name|getPath argument_list|() argument_list|) block|{ annotation|@ name|Override specifier|public name|boolean name|setLastModified parameter_list|( name|long name|t parameter_list|) block|{ return|return literal|false return|; block|} specifier|private specifier|static specifier|final name|long name|serialVersionUID init|= literal|0 decl_stmt|; block|} argument_list|) expr_stmt|; name|fail argument_list|( literal|"expected exception" argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|IOException name|expected parameter_list|) block|{ } block|} DECL|method|testTouchTime () specifier|public name|void name|testTouchTime parameter_list|() throws|throws name|IOException block|{ name|File name|temp init|= name|createTempFile argument_list|() decl_stmt|; name|assertTrue argument_list|( name|temp operator|. name|exists argument_list|() argument_list|) expr_stmt|; name|temp operator|. name|setLastModified argument_list|( literal|0 argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|0 argument_list|, name|temp operator|. name|lastModified argument_list|() argument_list|) expr_stmt|; name|Files operator|. name|touch argument_list|( name|temp argument_list|) expr_stmt|; name|assertThat argument_list|( name|temp operator|. name|lastModified argument_list|() argument_list|) operator|. name|isNotEqualTo argument_list|( literal|0 argument_list|) expr_stmt|; block|} DECL|method|testCreateParentDirs_root () specifier|public name|void name|testCreateParentDirs_root parameter_list|() throws|throws name|IOException block|{ name|File name|file init|= name|root argument_list|() decl_stmt|; name|assertNull argument_list|( name|file operator|. name|getParentFile argument_list|() argument_list|) expr_stmt|; name|assertNull argument_list|( name|file operator|. name|getCanonicalFile argument_list|() operator|. name|getParentFile argument_list|() argument_list|) expr_stmt|; name|Files operator|. name|createParentDirs argument_list|( name|file argument_list|) expr_stmt|; block|} DECL|method|testCreateParentDirs_relativePath () specifier|public name|void name|testCreateParentDirs_relativePath parameter_list|() throws|throws name|IOException block|{ name|File name|file init|= name|file argument_list|( literal|"nonexistent.file" argument_list|) decl_stmt|; name|assertNull argument_list|( name|file operator|. name|getParentFile argument_list|() argument_list|) expr_stmt|; name|assertNotNull argument_list|( name|file operator|. name|getCanonicalFile argument_list|() operator|. name|getParentFile argument_list|() argument_list|) expr_stmt|; name|Files operator|. name|createParentDirs argument_list|( name|file argument_list|) expr_stmt|; block|} DECL|method|testCreateParentDirs_noParentsNeeded () specifier|public name|void name|testCreateParentDirs_noParentsNeeded parameter_list|() throws|throws name|IOException block|{ name|File name|file init|= name|file argument_list|( name|getTempDir argument_list|() argument_list|, literal|"nonexistent.file" argument_list|) decl_stmt|; name|assertTrue argument_list|( name|file operator|. name|getParentFile argument_list|() operator|. name|exists argument_list|() argument_list|) expr_stmt|; name|Files operator|. name|createParentDirs argument_list|( name|file argument_list|) expr_stmt|; block|} DECL|method|testCreateParentDirs_oneParentNeeded () specifier|public name|void name|testCreateParentDirs_oneParentNeeded parameter_list|() throws|throws name|IOException block|{ name|File name|file init|= name|file argument_list|( name|getTempDir argument_list|() argument_list|, literal|"parent" argument_list|, literal|"nonexistent.file" argument_list|) decl_stmt|; name|File name|parent init|= name|file operator|. name|getParentFile argument_list|() decl_stmt|; name|assertFalse argument_list|( name|parent operator|. name|exists argument_list|() argument_list|) expr_stmt|; try|try block|{ name|Files operator|. name|createParentDirs argument_list|( name|file argument_list|) expr_stmt|; name|assertTrue argument_list|( name|parent operator|. name|exists argument_list|() argument_list|) expr_stmt|; block|} finally|finally block|{ name|assertTrue argument_list|( name|parent operator|. name|delete argument_list|() argument_list|) expr_stmt|; block|} block|} DECL|method|testCreateParentDirs_multipleParentsNeeded () specifier|public name|void name|testCreateParentDirs_multipleParentsNeeded parameter_list|() throws|throws name|IOException block|{ name|File name|file init|= name|file argument_list|( name|getTempDir argument_list|() argument_list|, literal|"grandparent" argument_list|, literal|"parent" argument_list|, literal|"nonexistent.file" argument_list|) decl_stmt|; name|File name|parent init|= name|file operator|. name|getParentFile argument_list|() decl_stmt|; name|File name|grandparent init|= name|parent operator|. name|getParentFile argument_list|() decl_stmt|; name|assertFalse argument_list|( name|grandparent operator|. name|exists argument_list|() argument_list|) expr_stmt|; name|Files operator|. name|createParentDirs argument_list|( name|file argument_list|) expr_stmt|; name|assertTrue argument_list|( name|parent operator|. name|exists argument_list|() argument_list|) expr_stmt|; block|} DECL|method|testCreateParentDirs_nonDirectoryParentExists () specifier|public name|void name|testCreateParentDirs_nonDirectoryParentExists parameter_list|() throws|throws name|IOException block|{ name|File name|parent init|= name|getTestFile argument_list|( literal|"ascii.txt" argument_list|) decl_stmt|; name|assertTrue argument_list|( name|parent operator|. name|isFile argument_list|() argument_list|) expr_stmt|; name|File name|file init|= name|file argument_list|( name|parent argument_list|, literal|"foo" argument_list|) decl_stmt|; try|try block|{ name|Files operator|. name|createParentDirs argument_list|( name|file argument_list|) expr_stmt|; name|fail argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|IOException name|expected parameter_list|) block|{ } block|} DECL|method|testCreateTempDir () specifier|public name|void name|testCreateTempDir parameter_list|() block|{ name|File name|temp init|= name|Files operator|. name|createTempDir argument_list|() decl_stmt|; name|assertTrue argument_list|( name|temp operator|. name|exists argument_list|() argument_list|) expr_stmt|; name|assertTrue argument_list|( name|temp operator|. name|isDirectory argument_list|() argument_list|) expr_stmt|; name|assertThat argument_list|( name|temp operator|. name|listFiles argument_list|() argument_list|) operator|. name|isEmpty argument_list|() expr_stmt|; name|assertTrue argument_list|( name|temp operator|. name|delete argument_list|() argument_list|) expr_stmt|; block|} DECL|method|testMove () specifier|public name|void name|testMove parameter_list|() throws|throws name|IOException block|{ name|File name|i18nFile init|= name|getTestFile argument_list|( literal|"i18n.txt" argument_list|) decl_stmt|; name|File name|temp1 init|= name|createTempFile argument_list|() decl_stmt|; name|File name|temp2 init|= name|createTempFile argument_list|() decl_stmt|; name|Files operator|. name|copy argument_list|( name|i18nFile argument_list|, name|temp1 argument_list|) expr_stmt|; name|moveHelper argument_list|( literal|true argument_list|, name|temp1 argument_list|, name|temp2 argument_list|) expr_stmt|; name|assertTrue argument_list|( name|Files operator|. name|equal argument_list|( name|temp2 argument_list|, name|i18nFile argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testMoveViaCopy () specifier|public name|void name|testMoveViaCopy parameter_list|() throws|throws name|IOException block|{ name|File name|i18nFile init|= name|getTestFile argument_list|( literal|"i18n.txt" argument_list|) decl_stmt|; name|File name|temp1 init|= name|createTempFile argument_list|() decl_stmt|; name|File name|temp2 init|= name|createTempFile argument_list|() decl_stmt|; name|Files operator|. name|copy argument_list|( name|i18nFile argument_list|, name|temp1 argument_list|) expr_stmt|; name|moveHelper argument_list|( literal|true argument_list|, operator|new name|UnmovableFile argument_list|( name|temp1 argument_list|, literal|false argument_list|, literal|true argument_list|) argument_list|, name|temp2 argument_list|) expr_stmt|; name|assertTrue argument_list|( name|Files operator|. name|equal argument_list|( name|temp2 argument_list|, name|i18nFile argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testMoveFailures () specifier|public name|void name|testMoveFailures parameter_list|() throws|throws name|IOException block|{ name|File name|temp1 init|= name|createTempFile argument_list|() decl_stmt|; name|File name|temp2 init|= name|createTempFile argument_list|() decl_stmt|; name|moveHelper argument_list|( literal|false argument_list|, operator|new name|UnmovableFile argument_list|( name|temp1 argument_list|, literal|false argument_list|, literal|false argument_list|) argument_list|, name|temp2 argument_list|) expr_stmt|; name|moveHelper argument_list|( literal|false argument_list|, operator|new name|UnmovableFile argument_list|( name|temp1 argument_list|, literal|false argument_list|, literal|false argument_list|) argument_list|, operator|new name|UnmovableFile argument_list|( name|temp2 argument_list|, literal|true argument_list|, literal|false argument_list|) argument_list|) expr_stmt|; try|try block|{ name|File name|asciiFile init|= name|getTestFile argument_list|( literal|"ascii.txt" argument_list|) decl_stmt|; name|moveHelper argument_list|( literal|false argument_list|, name|asciiFile argument_list|, name|asciiFile argument_list|) expr_stmt|; name|fail argument_list|( literal|"expected exception" argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|IllegalArgumentException name|expected parameter_list|) block|{ } block|} DECL|method|moveHelper (boolean success, File from, File to) specifier|private name|void name|moveHelper parameter_list|( name|boolean name|success parameter_list|, name|File name|from parameter_list|, name|File name|to parameter_list|) throws|throws name|IOException block|{ try|try block|{ name|Files operator|. name|move argument_list|( name|from argument_list|, name|to argument_list|) expr_stmt|; if|if condition|( name|success condition|) block|{ name|assertFalse argument_list|( name|from operator|. name|exists argument_list|() argument_list|) expr_stmt|; name|assertTrue argument_list|( name|to operator|. name|exists argument_list|() argument_list|) expr_stmt|; block|} else|else block|{ name|fail argument_list|( literal|"expected exception" argument_list|) expr_stmt|; block|} block|} catch|catch parameter_list|( name|IOException name|possiblyExpected parameter_list|) block|{ if|if condition|( name|success condition|) block|{ throw|throw name|possiblyExpected throw|; block|} block|} block|} DECL|class|UnmovableFile specifier|private specifier|static class|class name|UnmovableFile extends|extends name|File block|{ DECL|field|canRename specifier|private specifier|final name|boolean name|canRename decl_stmt|; DECL|field|canDelete specifier|private specifier|final name|boolean name|canDelete decl_stmt|; DECL|method|UnmovableFile (File file, boolean canRename, boolean canDelete) specifier|public name|UnmovableFile parameter_list|( name|File name|file parameter_list|, name|boolean name|canRename parameter_list|, name|boolean name|canDelete parameter_list|) block|{ name|super argument_list|( name|file operator|. name|getPath argument_list|() argument_list|) expr_stmt|; name|this operator|. name|canRename operator|= name|canRename expr_stmt|; name|this operator|. name|canDelete operator|= name|canDelete expr_stmt|; block|} annotation|@ name|Override DECL|method|renameTo (File to) specifier|public name|boolean name|renameTo parameter_list|( name|File name|to parameter_list|) block|{ return|return name|canRename operator|&& name|super operator|. name|renameTo argument_list|( name|to argument_list|) return|; block|} annotation|@ name|Override DECL|method|delete () specifier|public name|boolean name|delete parameter_list|() block|{ return|return name|canDelete operator|&& name|super operator|. name|delete argument_list|() return|; block|} DECL|field|serialVersionUID specifier|private specifier|static specifier|final name|long name|serialVersionUID init|= literal|0 decl_stmt|; block|} DECL|method|testLineReading () specifier|public name|void name|testLineReading parameter_list|() throws|throws name|IOException block|{ name|File name|temp init|= name|createTempFile argument_list|() decl_stmt|; name|assertNull argument_list|( name|Files operator|. name|readFirstLine argument_list|( name|temp argument_list|, name|Charsets operator|. name|UTF_8 argument_list|) argument_list|) expr_stmt|; name|assertTrue argument_list|( name|Files operator|. name|readLines argument_list|( name|temp argument_list|, name|Charsets operator|. name|UTF_8 argument_list|) operator|. name|isEmpty argument_list|() argument_list|) expr_stmt|; name|PrintWriter name|w init|= operator|new name|PrintWriter argument_list|( name|Files operator|. name|newWriter argument_list|( name|temp argument_list|, name|Charsets operator|. name|UTF_8 argument_list|) argument_list|) decl_stmt|; name|w operator|. name|println argument_list|( literal|"hello" argument_list|) expr_stmt|; name|w operator|. name|println argument_list|( literal|"" argument_list|) expr_stmt|; name|w operator|. name|println argument_list|( literal|" world " argument_list|) expr_stmt|; name|w operator|. name|println argument_list|( literal|"" argument_list|) expr_stmt|; name|w operator|. name|close argument_list|() expr_stmt|; name|assertEquals argument_list|( literal|"hello" argument_list|, name|Files operator|. name|readFirstLine argument_list|( name|temp argument_list|, name|Charsets operator|. name|UTF_8 argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( name|ImmutableList operator|. name|of argument_list|( literal|"hello" argument_list|, literal|"" argument_list|, literal|" world " argument_list|, literal|"" argument_list|) argument_list|, name|Files operator|. name|readLines argument_list|( name|temp argument_list|, name|Charsets operator|. name|UTF_8 argument_list|) argument_list|) expr_stmt|; name|assertTrue argument_list|( name|temp operator|. name|delete argument_list|() argument_list|) expr_stmt|; block|} DECL|method|testReadLines_withLineProcessor () specifier|public name|void name|testReadLines_withLineProcessor parameter_list|() throws|throws name|IOException block|{ name|File name|temp init|= name|createTempFile argument_list|() decl_stmt|; name|LineProcessor argument_list|< name|List argument_list|< name|String argument_list|> argument_list|> name|collect init|= operator|new name|LineProcessor argument_list|< name|List argument_list|< name|String argument_list|> argument_list|> argument_list|() block|{ name|List argument_list|< name|String argument_list|> name|collector init|= operator|new name|ArrayList argument_list|<> argument_list|() decl_stmt|; annotation|@ name|Override specifier|public name|boolean name|processLine parameter_list|( name|String name|line parameter_list|) block|{ name|collector operator|. name|add argument_list|( name|line argument_list|) expr_stmt|; return|return literal|true return|; block|} annotation|@ name|Override specifier|public name|List argument_list|< name|String argument_list|> name|getResult parameter_list|() block|{ return|return name|collector return|; block|} block|} decl_stmt|; name|assertThat argument_list|( name|Files operator|. name|readLines argument_list|( name|temp argument_list|, name|Charsets operator|. name|UTF_8 argument_list|, name|collect argument_list|) argument_list|) operator|. name|isEmpty argument_list|() expr_stmt|; name|PrintWriter name|w init|= operator|new name|PrintWriter argument_list|( name|Files operator|. name|newWriter argument_list|( name|temp argument_list|, name|Charsets operator|. name|UTF_8 argument_list|) argument_list|) decl_stmt|; name|w operator|. name|println argument_list|( literal|"hello" argument_list|) expr_stmt|; name|w operator|. name|println argument_list|( literal|"" argument_list|) expr_stmt|; name|w operator|. name|println argument_list|( literal|" world " argument_list|) expr_stmt|; name|w operator|. name|println argument_list|( literal|"" argument_list|) expr_stmt|; name|w operator|. name|close argument_list|() expr_stmt|; name|Files operator|. name|readLines argument_list|( name|temp argument_list|, name|Charsets operator|. name|UTF_8 argument_list|, name|collect argument_list|) expr_stmt|; name|assertThat argument_list|( name|collect operator|. name|getResult argument_list|() argument_list|) operator|. name|containsExactly argument_list|( literal|"hello" argument_list|, literal|"" argument_list|, literal|" world " argument_list|, literal|"" argument_list|) operator|. name|inOrder argument_list|() expr_stmt|; name|LineProcessor argument_list|< name|List argument_list|< name|String argument_list|> argument_list|> name|collectNonEmptyLines init|= operator|new name|LineProcessor argument_list|< name|List argument_list|< name|String argument_list|> argument_list|> argument_list|() block|{ name|List argument_list|< name|String argument_list|> name|collector init|= operator|new name|ArrayList argument_list|<> argument_list|() decl_stmt|; annotation|@ name|Override specifier|public name|boolean name|processLine parameter_list|( name|String name|line parameter_list|) block|{ if|if condition|( name|line operator|. name|length argument_list|() operator|> literal|0 condition|) block|{ name|collector operator|. name|add argument_list|( name|line argument_list|) expr_stmt|; block|} return|return literal|true return|; block|} annotation|@ name|Override specifier|public name|List argument_list|< name|String argument_list|> name|getResult parameter_list|() block|{ return|return name|collector return|; block|} block|} decl_stmt|; name|Files operator|. name|readLines argument_list|( name|temp argument_list|, name|Charsets operator|. name|UTF_8 argument_list|, name|collectNonEmptyLines argument_list|) expr_stmt|; name|assertThat argument_list|( name|collectNonEmptyLines operator|. name|getResult argument_list|() argument_list|) operator|. name|containsExactly argument_list|( literal|"hello" argument_list|, literal|" world " argument_list|) operator|. name|inOrder argument_list|() expr_stmt|; name|assertTrue argument_list|( name|temp operator|. name|delete argument_list|() argument_list|) expr_stmt|; block|} DECL|method|testHash () specifier|public name|void name|testHash parameter_list|() throws|throws name|IOException block|{ name|File name|asciiFile init|= name|getTestFile argument_list|( literal|"ascii.txt" argument_list|) decl_stmt|; name|File name|i18nFile init|= name|getTestFile argument_list|( literal|"i18n.txt" argument_list|) decl_stmt|; name|String name|init init|= literal|"d41d8cd98f00b204e9800998ecf8427e" decl_stmt|; name|assertEquals argument_list|( name|init argument_list|, name|Hashing operator|. name|md5 argument_list|() operator|. name|newHasher argument_list|() operator|. name|hash argument_list|() operator|. name|toString argument_list|() argument_list|) expr_stmt|; name|String name|asciiHash init|= literal|"e5df5a39f2b8cb71b24e1d8038f93131" decl_stmt|; name|assertEquals argument_list|( name|asciiHash argument_list|, name|Files operator|. name|hash argument_list|( name|asciiFile argument_list|, name|Hashing operator|. name|md5 argument_list|() argument_list|) operator|. name|toString argument_list|() argument_list|) expr_stmt|; name|String name|i18nHash init|= literal|"7fa826962ce2079c8334cd4ebf33aea4" decl_stmt|; name|assertEquals argument_list|( name|i18nHash argument_list|, name|Files operator|. name|hash argument_list|( name|i18nFile argument_list|, name|Hashing operator|. name|md5 argument_list|() argument_list|) operator|. name|toString argument_list|() argument_list|) expr_stmt|; block|} DECL|method|testMap () specifier|public name|void name|testMap parameter_list|() throws|throws name|IOException block|{ comment|// Test data name|int name|size init|= literal|1024 decl_stmt|; name|byte index|[] name|bytes init|= name|newPreFilledByteArray argument_list|( name|size argument_list|) decl_stmt|; comment|// Setup name|File name|file init|= name|createTempFile argument_list|() decl_stmt|; name|Files operator|. name|write argument_list|( name|bytes argument_list|, name|file argument_list|) expr_stmt|; comment|// Test name|MappedByteBuffer name|actual init|= name|Files operator|. name|map argument_list|( name|file argument_list|) decl_stmt|; comment|// Verify name|ByteBuffer name|expected init|= name|ByteBuffer operator|. name|wrap argument_list|( name|bytes argument_list|) decl_stmt|; name|assertTrue argument_list|( literal|"ByteBuffers should be equal." argument_list|, name|expected operator|. name|equals argument_list|( name|actual argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testMap_noSuchFile () specifier|public name|void name|testMap_noSuchFile parameter_list|() throws|throws name|IOException block|{ comment|// Setup name|File name|file init|= name|createTempFile argument_list|() decl_stmt|; name|boolean name|deleted init|= name|file operator|. name|delete argument_list|() decl_stmt|; name|assertTrue argument_list|( name|deleted argument_list|) expr_stmt|; comment|// Test try|try block|{ name|Files operator|. name|map argument_list|( name|file argument_list|) expr_stmt|; name|fail argument_list|( literal|"Should have thrown FileNotFoundException." argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|FileNotFoundException name|expected parameter_list|) block|{ } block|} DECL|method|testMap_readWrite () specifier|public name|void name|testMap_readWrite parameter_list|() throws|throws name|IOException block|{ comment|// Test data name|int name|size init|= literal|1024 decl_stmt|; name|byte index|[] name|expectedBytes init|= operator|new name|byte index|[ name|size index|] decl_stmt|; name|byte index|[] name|bytes init|= name|newPreFilledByteArray argument_list|( literal|1024 argument_list|) decl_stmt|; comment|// Setup name|File name|file init|= name|createTempFile argument_list|() decl_stmt|; name|Files operator|. name|write argument_list|( name|bytes argument_list|, name|file argument_list|) expr_stmt|; name|Random name|random init|= operator|new name|Random argument_list|() decl_stmt|; name|random operator|. name|nextBytes argument_list|( name|expectedBytes argument_list|) expr_stmt|; comment|// Test name|MappedByteBuffer name|map init|= name|Files operator|. name|map argument_list|( name|file argument_list|, name|MapMode operator|. name|READ_WRITE argument_list|) decl_stmt|; name|map operator|. name|put argument_list|( name|expectedBytes argument_list|) expr_stmt|; comment|// Verify name|byte index|[] name|actualBytes init|= name|Files operator|. name|toByteArray argument_list|( name|file argument_list|) decl_stmt|; name|assertTrue argument_list|( name|Arrays operator|. name|equals argument_list|( name|expectedBytes argument_list|, name|actualBytes argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testMap_readWrite_creates () specifier|public name|void name|testMap_readWrite_creates parameter_list|() throws|throws name|IOException block|{ comment|// Test data name|int name|size init|= literal|1024 decl_stmt|; name|byte index|[] name|expectedBytes init|= name|newPreFilledByteArray argument_list|( literal|1024 argument_list|) decl_stmt|; comment|// Setup name|File name|file init|= name|createTempFile argument_list|() decl_stmt|; name|boolean name|deleted init|= name|file operator|. name|delete argument_list|() decl_stmt|; name|assertTrue argument_list|( name|deleted argument_list|) expr_stmt|; name|assertFalse argument_list|( name|file operator|. name|exists argument_list|() argument_list|) expr_stmt|; comment|// Test name|MappedByteBuffer name|map init|= name|Files operator|. name|map argument_list|( name|file argument_list|, name|MapMode operator|. name|READ_WRITE argument_list|, name|size argument_list|) decl_stmt|; name|map operator|. name|put argument_list|( name|expectedBytes argument_list|) expr_stmt|; comment|// Verify name|assertTrue argument_list|( name|file operator|. name|exists argument_list|() argument_list|) expr_stmt|; name|assertTrue argument_list|( name|file operator|. name|isFile argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( name|size argument_list|, name|file operator|. name|length argument_list|() argument_list|) expr_stmt|; name|byte index|[] name|actualBytes init|= name|Files operator|. name|toByteArray argument_list|( name|file argument_list|) decl_stmt|; name|assertTrue argument_list|( name|Arrays operator|. name|equals argument_list|( name|expectedBytes argument_list|, name|actualBytes argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testMap_readWrite_max_value_plus_1 () specifier|public name|void name|testMap_readWrite_max_value_plus_1 parameter_list|() throws|throws name|IOException block|{ comment|// Setup name|File name|file init|= name|createTempFile argument_list|() decl_stmt|; comment|// Test try|try block|{ name|Files operator|. name|map argument_list|( name|file argument_list|, name|MapMode operator|. name|READ_WRITE argument_list|, operator|( name|long operator|) name|Integer operator|. name|MAX_VALUE operator|+ literal|1 argument_list|) expr_stmt|; name|fail argument_list|( literal|"Should throw when size exceeds Integer.MAX_VALUE" argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|IllegalArgumentException name|expected parameter_list|) block|{ } block|} DECL|method|testGetFileExtension () specifier|public name|void name|testGetFileExtension parameter_list|() block|{ name|assertEquals argument_list|( literal|"txt" argument_list|, name|Files operator|. name|getFileExtension argument_list|( literal|".txt" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"txt" argument_list|, name|Files operator|. name|getFileExtension argument_list|( literal|"blah.txt" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"txt" argument_list|, name|Files operator|. name|getFileExtension argument_list|( literal|"blah..txt" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"txt" argument_list|, name|Files operator|. name|getFileExtension argument_list|( literal|".blah.txt" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"txt" argument_list|, name|Files operator|. name|getFileExtension argument_list|( literal|"/tmp/blah.txt" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"gz" argument_list|, name|Files operator|. name|getFileExtension argument_list|( literal|"blah.tar.gz" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"" argument_list|, name|Files operator|. name|getFileExtension argument_list|( literal|"/" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"" argument_list|, name|Files operator|. name|getFileExtension argument_list|( literal|"." argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"" argument_list|, name|Files operator|. name|getFileExtension argument_list|( literal|".." argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"" argument_list|, name|Files operator|. name|getFileExtension argument_list|( literal|"..." argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"" argument_list|, name|Files operator|. name|getFileExtension argument_list|( literal|"blah" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"" argument_list|, name|Files operator|. name|getFileExtension argument_list|( literal|"blah." argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"" argument_list|, name|Files operator|. name|getFileExtension argument_list|( literal|".blah." argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"" argument_list|, name|Files operator|. name|getFileExtension argument_list|( literal|"/foo.bar/blah" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"" argument_list|, name|Files operator|. name|getFileExtension argument_list|( literal|"/foo/.bar/blah" argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testGetNameWithoutExtension () specifier|public name|void name|testGetNameWithoutExtension parameter_list|() block|{ name|assertEquals argument_list|( literal|"" argument_list|, name|Files operator|. name|getNameWithoutExtension argument_list|( literal|".txt" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"blah" argument_list|, name|Files operator|. name|getNameWithoutExtension argument_list|( literal|"blah.txt" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"blah." argument_list|, name|Files operator|. name|getNameWithoutExtension argument_list|( literal|"blah..txt" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|".blah" argument_list|, name|Files operator|. name|getNameWithoutExtension argument_list|( literal|".blah.txt" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"blah" argument_list|, name|Files operator|. name|getNameWithoutExtension argument_list|( literal|"/tmp/blah.txt" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"blah.tar" argument_list|, name|Files operator|. name|getNameWithoutExtension argument_list|( literal|"blah.tar.gz" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"" argument_list|, name|Files operator|. name|getNameWithoutExtension argument_list|( literal|"/" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"" argument_list|, name|Files operator|. name|getNameWithoutExtension argument_list|( literal|"." argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"." argument_list|, name|Files operator|. name|getNameWithoutExtension argument_list|( literal|".." argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|".." argument_list|, name|Files operator|. name|getNameWithoutExtension argument_list|( literal|"..." argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"blah" argument_list|, name|Files operator|. name|getNameWithoutExtension argument_list|( literal|"blah" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"blah" argument_list|, name|Files operator|. name|getNameWithoutExtension argument_list|( literal|"blah." argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|".blah" argument_list|, name|Files operator|. name|getNameWithoutExtension argument_list|( literal|".blah." argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"blah" argument_list|, name|Files operator|. name|getNameWithoutExtension argument_list|( literal|"/foo.bar/blah" argument_list|) argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"blah" argument_list|, name|Files operator|. name|getNameWithoutExtension argument_list|( literal|"/foo/.bar/blah" argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testReadBytes () specifier|public name|void name|testReadBytes parameter_list|() throws|throws name|IOException block|{ name|ByteProcessor argument_list|< name|byte index|[] argument_list|> name|processor init|= operator|new name|ByteProcessor argument_list|< name|byte index|[] argument_list|> argument_list|() block|{ specifier|private specifier|final name|ByteArrayOutputStream name|out init|= operator|new name|ByteArrayOutputStream argument_list|() decl_stmt|; annotation|@ name|Override specifier|public name|boolean name|processBytes parameter_list|( name|byte index|[] name|buffer parameter_list|, name|int name|offset parameter_list|, name|int name|length parameter_list|) throws|throws name|IOException block|{ if|if condition|( name|length operator|>= literal|0 condition|) block|{ name|out operator|. name|write argument_list|( name|buffer argument_list|, name|offset argument_list|, name|length argument_list|) expr_stmt|; block|} return|return literal|true return|; block|} annotation|@ name|Override specifier|public name|byte index|[] name|getResult parameter_list|() block|{ return|return name|out operator|. name|toByteArray argument_list|() return|; block|} block|} decl_stmt|; name|File name|asciiFile init|= name|getTestFile argument_list|( literal|"ascii.txt" argument_list|) decl_stmt|; name|byte index|[] name|result init|= name|Files operator|. name|readBytes argument_list|( name|asciiFile argument_list|, name|processor argument_list|) decl_stmt|; name|assertEquals argument_list|( name|Bytes operator|. name|asList argument_list|( name|Files operator|. name|toByteArray argument_list|( name|asciiFile argument_list|) argument_list|) argument_list|, name|Bytes operator|. name|asList argument_list|( name|result argument_list|) argument_list|) expr_stmt|; block|} DECL|method|testReadBytes_returnFalse () specifier|public name|void name|testReadBytes_returnFalse parameter_list|() throws|throws name|IOException block|{ name|ByteProcessor argument_list|< name|byte index|[] argument_list|> name|processor init|= operator|new name|ByteProcessor argument_list|< name|byte index|[] argument_list|> argument_list|() block|{ specifier|private specifier|final name|ByteArrayOutputStream name|out init|= operator|new name|ByteArrayOutputStream argument_list|() decl_stmt|; annotation|@ name|Override specifier|public name|boolean name|processBytes parameter_list|( name|byte index|[] name|buffer parameter_list|, name|int name|offset parameter_list|, name|int name|length parameter_list|) throws|throws name|IOException block|{ if|if condition|( name|length operator|> literal|0 condition|) block|{ name|out operator|. name|write argument_list|( name|buffer argument_list|, name|offset argument_list|, literal|1 argument_list|) expr_stmt|; return|return literal|false return|; block|} else|else block|{ return|return literal|true return|; block|} block|} annotation|@ name|Override specifier|public name|byte index|[] name|getResult parameter_list|() block|{ return|return name|out operator|. name|toByteArray argument_list|() return|; block|} block|} decl_stmt|; name|File name|asciiFile init|= name|getTestFile argument_list|( literal|"ascii.txt" argument_list|) decl_stmt|; name|byte index|[] name|result init|= name|Files operator|. name|readBytes argument_list|( name|asciiFile argument_list|, name|processor argument_list|) decl_stmt|; name|assertEquals argument_list|( literal|1 argument_list|, name|result operator|. name|length argument_list|) expr_stmt|; block|} DECL|method|testPredicates () specifier|public name|void name|testPredicates parameter_list|() throws|throws name|IOException block|{ name|File name|asciiFile init|= name|getTestFile argument_list|( literal|"ascii.txt" argument_list|) decl_stmt|; name|File name|dir init|= name|asciiFile operator|. name|getParentFile argument_list|() decl_stmt|; name|assertTrue argument_list|( name|Files operator|. name|isDirectory argument_list|() operator|. name|apply argument_list|( name|dir argument_list|) argument_list|) expr_stmt|; name|assertFalse argument_list|( name|Files operator|. name|isFile argument_list|() operator|. name|apply argument_list|( name|dir argument_list|) argument_list|) expr_stmt|; name|assertFalse argument_list|( name|Files operator|. name|isDirectory argument_list|() operator|. name|apply argument_list|( name|asciiFile argument_list|) argument_list|) expr_stmt|; name|assertTrue argument_list|( name|Files operator|. name|isFile argument_list|() operator|. name|apply argument_list|( name|asciiFile argument_list|) argument_list|) expr_stmt|; block|} comment|/** Returns a root path for the file system. */ DECL|method|root () specifier|private specifier|static name|File name|root parameter_list|() block|{ return|return name|File operator|. name|listRoots argument_list|() index|[ literal|0 index|] return|; block|} comment|/** Returns a {@code File} object for the given path parts. */ DECL|method|file (String first, String... more) specifier|private specifier|static name|File name|file parameter_list|( name|String name|first parameter_list|, name|String modifier|... name|more parameter_list|) block|{ return|return name|file argument_list|( operator|new name|File argument_list|( name|first argument_list|) argument_list|, name|more argument_list|) return|; block|} comment|/** Returns a {@code File} object for the given path parts. */ DECL|method|file (File first, String... more) specifier|private specifier|static name|File name|file parameter_list|( name|File name|first parameter_list|, name|String modifier|... name|more parameter_list|) block|{ comment|// not very efficient, but should definitely be correct name|File name|file init|= name|first decl_stmt|; for|for control|( name|String name|name range|: name|more control|) block|{ name|file operator|= operator|new name|File argument_list|( name|file argument_list|, name|name argument_list|) expr_stmt|; block|} return|return name|file return|; block|} block|} end_class end_unit
14.247894
608
0.803742
078341096217444bf49070c0aaee1d79383bf82b
538
package com.gaadi.sfa.ui; /** * Created by kanishroshan on 10/2/16. */ public class TitleData { private String title; private int iconid; public TitleData(String title, int iconid) { this.title = title; this.iconid = iconid; } public int getIconid() { return iconid; } public void setIconid(int iconid) { this.iconid = iconid; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
16.8125
48
0.585502
3da2dda9a7a3bff815ee0632f6d66c5e5aec913b
3,414
/* * Copyright (C) 2016 Selerity, Inc. (support@seleritycorp.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 com.seleritycorp.common.base.logging; import com.seleritycorp.common.base.inject.InjectorFactory; import org.apache.commons.logging.LogConfigurationException; /** * Factory for creating Log instances. */ public class LogFactory { private static Formatter encoder = InjectorFactory.getInjector().getInstance(Formatter.class); /** * Gets the non-permanent Log for a given Class * * <p>Non-permanent logs will get deleted after some time, and not retained * forever. * * @param clazz The clazz to get the {@code Log} instance for. * @return The non-permanent log for {@code clazz} * @exception LogConfigurationException if no suitable {@code Log} instance * can be returned. */ public static Log getLog(@SuppressWarnings("rawtypes") Class clazz) throws LogConfigurationException { return getLog(clazz.getName()); } /** * Gets the non-permanent Log for a given name * * <p>Non-permanent logs will get deleted after some time, and not retained * forever. * * @param name The name to get the permanent {@code Log} instance for. * @return The non-permanent log for {@code name} * @exception LogConfigurationException if no suitable {@code Log} instance * can be returned. */ public static Log getLog(String name) throws LogConfigurationException { return new CommonsLog(org.apache.commons.logging.LogFactory.getLog(name), encoder); } /** * Gets the permanent Log for a given Class * * <p>Permanent logs are meant to be kept around forever. Use them only for * messages that are worth to keep around forever. * * <p>Messages sent to the returned Log are converted to a single line. * * @param clazz The clazz to get the {@code Log} instance for. * @return The permanent log for {@code clazz} * @exception LogConfigurationException if no suitable {@code Log} instance * can be returned. */ public static Log getPermanentLog(@SuppressWarnings("rawtypes") Class clazz) throws LogConfigurationException { return getPermanentLog(clazz.getName()); } /** * Gets the permanent Logger for a given name * * <p>Permanent logs are meant to be kept around forever. Use them only for * messages that are worth to keep around forever. * * <p>Messages sent to the returned Log are converted to a single line. * * @param name The name to get the permanent {@code Log} instance for. * @return The non-permanent log for {@code clazz} * @exception LogConfigurationException if no suitable {@code Log} instance * can be returned. */ public static Log getPermanentLog(String name) throws LogConfigurationException { return new FlatLog(getLog("permanent." + name)); } }
35.5625
96
0.705624
e67d740c54450fd21df380bfc42674549361c10b
612
package com.easy.cloud.core.operator.sysroleresource.dao; import com.easy.cloud.core.operator.sysroleresource.pojo.entity.SysRoleResourceEntity; import com.easy.cloud.core.jdbc.base.dao.EcBaseDAO; import com.easy.cloud.core.operator.sysroleresource.pojo.query.SysRoleResourceQuery; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 描述:数据处理接口 * * @author THINK * @date 2018-05-30 16:24:33 */ public interface SysRoleResourceDAO extends EcBaseDAO<SysRoleResourceEntity> { List<SysRoleResourceEntity> listByQuery(@Param(value = "query") SysRoleResourceQuery roleResourceQuery); }
32.210526
108
0.802288
c8f580260817d4bbf9e54aa23e43e983ebaa5456
6,589
/* 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.flowable.cmmn.engine.impl.runtime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.flowable.cmmn.api.runtime.ChangePlanItemStateBuilder; import org.flowable.common.engine.api.FlowableException; /** * @author Tijs Rademakers */ public class ChangePlanItemStateBuilderImpl implements ChangePlanItemStateBuilder { protected CmmnRuntimeServiceImpl runtimeService; protected String caseInstanceId; protected List<MovePlanItemInstanceIdContainer> movePlanItemInstanceIdList = new ArrayList<>(); protected List<MovePlanItemDefinitionIdContainer> movePlanItemDefinitionIdList = new ArrayList<>(); protected Map<String, Object> caseVariables = new HashMap<>(); public ChangePlanItemStateBuilderImpl() { } public ChangePlanItemStateBuilderImpl(CmmnRuntimeServiceImpl runtimeService) { this.runtimeService = runtimeService; } @Override public ChangePlanItemStateBuilder caseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; return this; } @Override public ChangePlanItemStateBuilder movePlanItemInstanceToPlanItemDefinitionId(String planItemInstanceId, String planItemDefinitionId) { return moveExecutionToActivityId(planItemInstanceId, planItemDefinitionId, null); } public ChangePlanItemStateBuilder moveExecutionToActivityId(String planItemInstanceId, String planItemDefinitionId, String newAssigneeId) { movePlanItemInstanceIdList.add(new MovePlanItemInstanceIdContainer(planItemInstanceId, planItemDefinitionId, newAssigneeId)); return this; } @Override public ChangePlanItemStateBuilder movePlanItemInstancesToSinglePlanItemDefinitionId(List<String> planItemInstanceIds, String planItemDefinitionId) { return movePlanItemInstancesToSinglePlanItemDefinitionId(planItemInstanceIds, planItemDefinitionId, null); } public ChangePlanItemStateBuilder movePlanItemInstancesToSinglePlanItemDefinitionId(List<String> planItemInstanceIds, String planItemDefinitionId, String newAssigneeId) { movePlanItemInstanceIdList.add(new MovePlanItemInstanceIdContainer(planItemInstanceIds, planItemDefinitionId, newAssigneeId)); return this; } @Override public ChangePlanItemStateBuilder moveSinglePlanItemInstanceToPlanItemDefinitionIds(String executionId, List<String> activityIds) { return moveSinglePlanItemInstanceToPlanItemDefinitionIds(executionId, activityIds, null); } public ChangePlanItemStateBuilder moveSinglePlanItemInstanceToPlanItemDefinitionIds(String executionId, List<String> activityIds, String newAssigneeId) { movePlanItemInstanceIdList.add(new MovePlanItemInstanceIdContainer(executionId, activityIds, newAssigneeId)); return this; } @Override public ChangePlanItemStateBuilder movePlanItemDefinitionIdTo(String currentPlanItemDefinitionId, String newPlanItemDefinitionId) { return movePlanItemDefinitionIdTo(currentPlanItemDefinitionId, newPlanItemDefinitionId, null); } public ChangePlanItemStateBuilder movePlanItemDefinitionIdTo(String currentPlanItemDefinitionId, String newPlanItemDefinitionId, String newAssigneeId) { movePlanItemDefinitionIdList.add(new MovePlanItemDefinitionIdContainer(currentPlanItemDefinitionId, newPlanItemDefinitionId, newAssigneeId)); return this; } @Override public ChangePlanItemStateBuilder movePlanItemDefinitionIdsToSinglePlanItemDefinitionId(List<String> planItemDefinitionIds, String planItemDefinitionId) { return movePlanItemDefinitionIdsToSinglePlanItemDefinitionId(planItemDefinitionIds, planItemDefinitionId, null); } public ChangePlanItemStateBuilder movePlanItemDefinitionIdsToSinglePlanItemDefinitionId(List<String> planItemDefinitionIds, String planItemDefinitionId, String newAssigneeId) { movePlanItemDefinitionIdList.add(new MovePlanItemDefinitionIdContainer(planItemDefinitionIds, planItemDefinitionId, newAssigneeId)); return this; } @Override public ChangePlanItemStateBuilder moveSinglePlanItemDefinitionIdToPlanItemDefinitionIds(String currentPlanItemDefinitionId, List<String> newPlanItemDefinitionIds) { return moveSinglePlanItemDefinitionIdToPlanItemDefinitionIds(currentPlanItemDefinitionId, newPlanItemDefinitionIds, null); } public ChangePlanItemStateBuilder moveSinglePlanItemDefinitionIdToPlanItemDefinitionIds(String currentPlanItemDefinitionId, List<String> newPlanItemDefinitionIds, String newAssigneeId) { movePlanItemDefinitionIdList.add(new MovePlanItemDefinitionIdContainer(currentPlanItemDefinitionId, newPlanItemDefinitionIds, newAssigneeId)); return this; } @Override public ChangePlanItemStateBuilder caseVariable(String caseVariableName, Object caseVariableValue) { if (this.caseVariables == null) { this.caseVariables = new HashMap<>(); } this.caseVariables.put(caseVariableName, caseVariableValue); return this; } @Override public ChangePlanItemStateBuilder caseVariables(Map<String, Object> caseVariables) { this.caseVariables = caseVariables; return this; } @Override public void changeState() { if (runtimeService == null) { throw new FlowableException("CmmnRuntimeService cannot be null, Obtain your builder instance from the CmmnRuntimService to access this feature"); } runtimeService.changePlanItemState(this); } public String getCaseInstanceId() { return caseInstanceId; } public List<MovePlanItemInstanceIdContainer> getMovePlanItemInstanceIdList() { return movePlanItemInstanceIdList; } public List<MovePlanItemDefinitionIdContainer> getMovePlanItemDefinitionIdList() { return movePlanItemDefinitionIdList; } public Map<String, Object> getCaseVariables() { return caseVariables; } }
44.52027
190
0.788132
8373857408305ff71c05e5d090c47320bd57b861
182
package steed.hibernatemaster.util; import java.util.Map; public class OrHqlGenerator extends SimpleHqlGenerator{ // public class OrGroup{ // Map<String, Object> // } }
18.2
56
0.71978
a2a66b88ae53c7cd086b4f5185d7ef3e51bcec05
2,732
/** * <p> * 文件名称: LogMessage * </p> */ package com.zhou.yadmin.system.monitor.dto; import java.io.Serializable; /** * <p> * 类注释 * </p> * * @author yuZhou * @since 2020/3/10 19:47 */ public class LogMessage implements Serializable { private static final long serialVersionUID = -8158905318770373036L; private String body; private String timestamp; private String threadName; private String className; private String level; public LogMessage(String body, String timestamp, String threadName, String className, String level) { this.body = body; this.timestamp = timestamp; this.threadName = threadName; this.className = className; this.level = level; } /** * Gets the value of body * * @return the value of body */ public String getBody() { return body; } /** * Sets the body * <p>You can use getBody() to get the value of body</p> * * @param body body */ public void setBody(String body) { this.body = body; } /** * Gets the value of timestamp * * @return the value of timestamp */ public String getTimestamp() { return timestamp; } /** * Sets the timestamp * <p>You can use getTimestamp() to get the value of timestamp</p> * * @param timestamp timestamp */ public void setTimestamp(String timestamp) { this.timestamp = timestamp; } /** * Gets the value of threadName * * @return the value of threadName */ public String getThreadName() { return threadName; } /** * Sets the threadName * <p>You can use getThreadName() to get the value of threadName</p> * * @param threadName threadName */ public void setThreadName(String threadName) { this.threadName = threadName; } /** * Gets the value of className * * @return the value of className */ public String getClassName() { return className; } /** * Sets the className * <p>You can use getClassName() to get the value of className</p> * * @param className className */ public void setClassName(String className) { this.className = className; } /** * Gets the value of level * * @return the value of level */ public String getLevel() { return level; } /** * Sets the level * <p>You can use getLevel() to get the value of level</p> * * @param level level */ public void setLevel(String level) { this.level = level; } }
19.239437
103
0.56552
2e863775046af0343e39600317eb0c730ac067c5
1,316
package yao.algs.stack; import org.junit.Test; import org.junit.Before; import org.junit.After; import java.util.Arrays; import static org.junit.Assert.assertEquals; /** * ArrayStack Tester. * * @author <Authors name> * @version 1.0 * @since <pre>Jan 11, 2018</pre> */ public class ArrayStackTest { private ArrayStack<String> algs = new ArrayStack<>(); @Before public void before() throws Exception { algs.push("aaa"); algs.push("bbb"); algs.push("ccc"); algs.push("ddd"); } @After public void after() throws Exception { algs.clear(); } /** * Method: push(E e) */ @Test public void testPush() throws Exception { algs.push("push-here"); System.out.println(Arrays.toString(algs.toArray(new String[algs.size()]))); } /** * Method: pop() */ @Test public void testPop() throws Exception { String old = algs.pop(); assertEquals("ddd", old); } /** * Method: peek() */ @Test public void testPeek() throws Exception { String old = algs.peek(); assertEquals("ddd", old); } /** * Method: search(Object o) */ @Test public void testSearch() throws Exception { //TODO: Test goes here... } }
18.277778
83
0.56535
009b830c013f289878550d9ccdd2cfb1025af4b9
9,809
package es.deusto.deustock.dao; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import javax.jdo.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import java.util.*; /** * @author Erik B. Terres */ @Tag("dbtest") class DBManagerTest { private PersistenceManagerFactory mockPMF = null; private PersistenceManager mockPM; private DBManager dbManager; private Transaction mockTransaction; private Query mockQuery = null; @BeforeEach void setUp(){ mockPMF = mock(PersistenceManagerFactory.class); mockPM = mock(PersistenceManager.class); mockTransaction = mock(Transaction.class); mockQuery = mock(Query.class); when(mockPMF.getPersistenceManager()).thenReturn(mockPM); when(mockPM.currentTransaction()).thenReturn(mockTransaction); doNothing().when(mockTransaction).begin(); doNothing().when(mockTransaction).rollback(); doNothing().when(mockTransaction).commit(); FetchPlan mockFetchPlan = mock(FetchPlan.class); when(mockPM.getFetchPlan()).thenReturn(mockFetchPlan); when(mockFetchPlan.setMaxFetchDepth(anyInt())).thenReturn(mockFetchPlan); when(mockPM.newQuery(anyString(), anyString())).thenReturn(mockQuery); dbManager = (DBManager) DBManager.getInstance(); dbManager.setPFM(mockPMF); } @Test @DisplayName("Test storeObject catch works") void testStoreCatchWorks(){ //Given Object object = new Object(); when(mockPM.makePersistent(any(Object.class))).thenThrow(new IllegalArgumentException("Exception")); FetchPlan mockFetchPlan = mock(FetchPlan.class); when(mockPM.getFetchPlan()).thenReturn(mockFetchPlan); when(mockFetchPlan.setMaxFetchDepth(anyInt())).thenReturn(mockFetchPlan); when(mockTransaction.isActive()).thenReturn(true); //When assertDoesNotThrow( () -> dbManager.store(object) ); } @Test @DisplayName("Test storeObject catch works with non active transaction") void testStoreCatchWorksIsNotActive(){ //Given Object object = new Object(); when(mockPM.makePersistent(any(Object.class))).thenThrow(new IllegalArgumentException("Exception")); FetchPlan mockFetchPlan = mock(FetchPlan.class); when(mockPM.getFetchPlan()).thenReturn(mockFetchPlan); when(mockFetchPlan.setMaxFetchDepth(anyInt())).thenReturn(mockFetchPlan); when(mockTransaction.isActive()).thenReturn(false); //When assertDoesNotThrow( () -> dbManager.store(object) ); } @Test @DisplayName("Test storeObject function works") void testStoreWorks(){ //Given Object object = new Object(); when(mockPM.makePersistent(any())).thenReturn(object); //When assertDoesNotThrow( () -> dbManager.store(object)); } // GET ALL @Test @DisplayName("Test getAll catch works") void testGetAllCatchWorks(){ //Given Class<Object> objectClass = Object.class; when(mockPM.getExtent(objectClass)).thenThrow(new IllegalArgumentException("Exception")); when(mockTransaction.isActive()).thenReturn(true); //When // Then assertDoesNotThrow( () -> dbManager.getAll(objectClass) ); } @Test @DisplayName("Test getAll catch works with non active transaction") void testGetAllCatchWorksIsNotActive(){ //Given Class<Object> objectClass = Object.class; when(mockPM.getExtent(objectClass)).thenThrow(new IllegalArgumentException("Exception")); when(mockTransaction.isActive()).thenReturn(false); //When // Then assertDoesNotThrow( () -> dbManager.getAll(objectClass) ); } // GET LIST @Test @DisplayName("Test getList works") void testGetListWithConditionWorks(){ //Given Class<Object> objectClass = Object.class; when(mockQuery.executeWithMap(anyMap())).thenReturn(new LinkedList<>()); //When assertDoesNotThrow( () ->dbManager.getList(objectClass, "testConditions", new HashMap<>()) ); } @Test @DisplayName("Test getList catch works") void testGetListWithConditionCatchWorks(){ //Given Class<Object> objectClass = Object.class; doThrow(new IllegalArgumentException("Exception")).when(mockQuery).executeWithMap(anyMap()); when(mockTransaction.isActive()).thenReturn(true); //When assertDoesNotThrow( () ->dbManager.getList(objectClass, "testConditions", new HashMap<>()) ); } @Test @DisplayName("Test getList catch works with non active transaction") void testGetListWithConditionCatchWorksIsNotActive(){ //Given Class<Object> objectClass = Object.class; doThrow(new IllegalArgumentException("Exception")).when(mockQuery).executeWithMap(anyMap()); when(mockTransaction.isActive()).thenReturn(false); //When assertDoesNotThrow( () ->dbManager.getList(objectClass, "testConditions", new HashMap<>()) ); } // GET CONDITION @Test @DisplayName("Test get with condition works") void testGetObjectWithConditionWorks(){ //Given //When when(mockPM.detachCopy(any())).thenReturn(new Object()); assertDoesNotThrow( () -> dbManager.get(Object.class, "", new HashMap<>())); } @Test @DisplayName("Test get with condition catch works") void testGetObjectWithConditionCatchWorks(){ //Given //When doThrow(new IllegalArgumentException("Exception")).when(mockPM).detachCopy(any()); when(mockTransaction.isActive()).thenReturn(true); assertDoesNotThrow( () -> dbManager.get(Object.class, "", new HashMap<>())); } @Test @DisplayName("Test get with condition catch works with non active transaction") void testGetObjectWithConditionCatchWorksIsNotActive(){ //Given //When doThrow(new IllegalArgumentException("Exception")).when(mockPM).detachCopy(any()); when(mockTransaction.isActive()).thenReturn(false); assertDoesNotThrow( () -> dbManager.get(Object.class, "", new HashMap<>())); } // UPDATE @Test @DisplayName("Test update works") void testUpdateWorks(){ //Given Object object = new Object(); when(mockPM.makePersistent(any())).thenReturn(object); //When // Then assertDoesNotThrow( () -> dbManager.update(object) ); } @Test @DisplayName("Test update catch works") void testUpdateCatchWorks(){ //Given Object object = new Object(); when(mockPM.makePersistent(any())).thenThrow(new IllegalArgumentException("Exception")); when(mockTransaction.isActive()).thenReturn(true); //When assertDoesNotThrow( () -> dbManager.update(object) ); } @Test @DisplayName("Test update catch works with non active transaction") void testUpdateCatchWorksIsNotActive(){ //Given Object object = new Object(); when(mockPM.makePersistent(any())).thenThrow(new IllegalArgumentException("Exception")); when(mockTransaction.isActive()).thenReturn(false); //When assertDoesNotThrow( () -> dbManager.update(object) ); } // DELETE CONDITION @Test @DisplayName("Test delete with conditions catch works") void testDeleteObjectWithConditionThrowsError(){ //Given Class<Object> objectClass = Object.class; //When doThrow(new IllegalArgumentException("Exception")).when(mockQuery).deletePersistentAll(anyMap()); when(mockTransaction.isActive()).thenReturn(true); assertDoesNotThrow( () -> dbManager.delete(objectClass, "", new HashMap<>()) ); } @Test @DisplayName("Test delete with conditions catch works with non active transaction") void testDeleteObjectWithConditionThrowsErrorIsNotActive(){ //Given Class<Object> objectClass = Object.class; //When doThrow(new IllegalArgumentException("Exception")).when(mockQuery).deletePersistentAll(anyMap()); when(mockTransaction.isActive()).thenReturn(false); assertDoesNotThrow( () -> dbManager.delete(objectClass, "", new HashMap<>()) ); } @Test @DisplayName("Test delete with conditions works") void testDeleteObjectWithConditionDoesNotThrowError(){ //Given Class<Object> objectClass = Object.class; //When when(mockPM.newQuery(anyString())).thenReturn(mockQuery); doNothing().when(mockPM).deletePersistent(objectClass); doNothing().when(mockPM).setDetachAllOnCommit(anyBoolean()); doNothing().when(mockQuery).setUnique(anyBoolean()); when(mockQuery.deletePersistentAll(anyMap())).thenReturn((long) 2); //Then assertDoesNotThrow(() -> dbManager.delete(objectClass, "", new HashMap<>())); } // DELETE @Test @DisplayName("Test delete object works") void testDeleteObjectDoesNotThrowError(){ //Given Class<Object> objectClass = Object.class; //When when(mockPMF.getPersistenceManager()).thenReturn(mockPM); doNothing().when(mockTransaction).begin(); doNothing().when(mockPM).deletePersistent(objectClass); doNothing().when(mockTransaction).commit(); assertDoesNotThrow( () -> dbManager.delete(objectClass)); } @Test @DisplayName("Test delete object function catch works") void testDeleteObjectThrowsError(){ //Given Class<Object> objectClass = Object.class; //When doThrow(new IllegalArgumentException()).when(mockPM).deletePersistent(any(Object.class)); when(mockTransaction.isActive()).thenReturn(true); // Then assertDoesNotThrow( () -> dbManager.delete(objectClass) ); } @Test @DisplayName("Test delete object function catch works with non active transaction") void testDeleteObjectThrowsErrorIsNotActive(){ //Given Class<Object> objectClass = Object.class; //When doThrow(new IllegalArgumentException()).when(mockPM).deletePersistent(any(Object.class)); when(mockTransaction.isActive()).thenReturn(false); // Then assertDoesNotThrow( () -> dbManager.delete(objectClass) ); } }
26.654891
102
0.720461
22db1e1298c286b36c9057d100302a79403b61f2
964
package com.cmcc.shiro.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="t_resource") public class Resource { private int id; private String name; private String permission; private String url; @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPermission() { return permission; } public void setPermission(String permission) { this.permission = permission; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Override public String toString() { return "Resource [id=" + id + ", name=" + name + ", permission=" + permission + ", url=" + url + "]"; } }
20.083333
67
0.654564
3b6486ee7ba837a254036cf178bdf9f92cf22a07
16,560
package com.hbird.base.mvc.bean.ReturnBean; import com.hbird.base.mvc.bean.BaseReturn; import java.util.List; /** * Created by Liul on 2018/9/5. */ public class SystemParamsReturn extends BaseReturn { private String code; private String msg; private ResultBean result; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public ResultBean getResult() { return result; } public void setResult(ResultBean result) { this.result = result; } public static class ResultBean { private AllUserCommUseSpendTypeBean allUserCommUseSpendType; private AllSysIncomeTypeBean allSysIncomeType; private AllUserCommUseIncomeTypeBean allUserCommUseIncomeType; private String synInterval; private AllSysSpendTypeBean allSysSpendType; private String accountBookId; private String userInfoId; public AllUserCommUseSpendTypeBean getAllUserCommUseSpendType() { return allUserCommUseSpendType; } public void setAllUserCommUseSpendType(AllUserCommUseSpendTypeBean allUserCommUseSpendType) { this.allUserCommUseSpendType = allUserCommUseSpendType; } public AllSysIncomeTypeBean getAllSysIncomeType() { return allSysIncomeType; } public void setAllSysIncomeType(AllSysIncomeTypeBean allSysIncomeType) { this.allSysIncomeType = allSysIncomeType; } public AllUserCommUseIncomeTypeBean getAllUserCommUseIncomeType() { return allUserCommUseIncomeType; } public void setAllUserCommUseIncomeType(AllUserCommUseIncomeTypeBean allUserCommUseIncomeType) { this.allUserCommUseIncomeType = allUserCommUseIncomeType; } public String getSynInterval() { return synInterval; } public void setSynInterval(String synInterval) { this.synInterval = synInterval; } public AllSysSpendTypeBean getAllSysSpendType() { return allSysSpendType; } public void setAllSysSpendType(AllSysSpendTypeBean allSysSpendType) { this.allSysSpendType = allSysSpendType; } public String getAccountBookId() { return accountBookId; } public void setAccountBookId(String accountBookId) { this.accountBookId = accountBookId; } public String getUserInfoId() { return userInfoId; } public void setUserInfoId(String userInfoId) { this.userInfoId = userInfoId; } public static class AllUserCommUseSpendTypeBean { private String version; private List<AllUserCommUseSpendTypeArraysBean> allUserCommUseSpendTypeArrays; public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public List<AllUserCommUseSpendTypeArraysBean> getAllUserCommUseSpendTypeArrays() { return allUserCommUseSpendTypeArrays; } public void setAllUserCommUseSpendTypeArrays(List<AllUserCommUseSpendTypeArraysBean> allUserCommUseSpendTypeArrays) { this.allUserCommUseSpendTypeArrays = allUserCommUseSpendTypeArrays; } public static class AllUserCommUseSpendTypeArraysBean { private String id; private String spendName; private String parentId; private String parentName; private String icon; private int priority; private int mark; private Object spendTypeSons; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSpendName() { return spendName; } public void setSpendName(String spendName) { this.spendName = spendName; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getParentName() { return parentName; } public void setParentName(String parentName) { this.parentName = parentName; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public int getMark() { return mark; } public void setMark(int mark) { this.mark = mark; } public Object getSpendTypeSons() { return spendTypeSons; } public void setSpendTypeSons(Object spendTypeSons) { this.spendTypeSons = spendTypeSons; } } } public static class AllSysIncomeTypeBean { private String version; private List<AllSysIncomeTypeArraysBean> allSysIncomeTypeArrays; public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public List<AllSysIncomeTypeArraysBean> getAllSysIncomeTypeArrays() { return allSysIncomeTypeArrays; } public void setAllSysIncomeTypeArrays(List<AllSysIncomeTypeArraysBean> allSysIncomeTypeArrays) { this.allSysIncomeTypeArrays = allSysIncomeTypeArrays; } public static class AllSysIncomeTypeArraysBean { private long updateDate; private long createDate; private String parentId; private String incomeName; private Object incomeTypeSons; private Integer delflag; private long delDate; private Integer mark; private String icon; private String status; private int priority; private String id; public long getUpdateDate() { return updateDate; } public void setUpdateDate(long updateDate) { this.updateDate = updateDate; } public long getCreateDate() { return createDate; } public void setCreateDate(long createDate) { this.createDate = createDate; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getIncomeName() { return incomeName; } public void setIncomeName(String incomeName) { this.incomeName = incomeName; } public Object getIncomeTypeSons() { return incomeTypeSons; } public void setIncomeTypeSons(Object incomeTypeSons) { this.incomeTypeSons = incomeTypeSons; } public Integer getDelflag() { return delflag; } public void setDelflag(Integer delflag) { this.delflag = delflag; } public long getDelDate() { return delDate; } public void setDelDate(long delDate) { this.delDate = delDate; } public Integer getMark() { return mark; } public void setMark(Integer mark) { this.mark = mark; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public String getId() { return id; } public void setId(String id) { this.id = id; } } } public static class AllUserCommUseIncomeTypeBean { private String version; private List<AllUserCommUseIncomeTypeArraysBean> allUserCommUseIncomeTypeArrays; public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public List<AllUserCommUseIncomeTypeArraysBean> getAllUserCommUseIncomeTypeArrays() { return allUserCommUseIncomeTypeArrays; } public void setAllUserCommUseIncomeTypeArrays(List<AllUserCommUseIncomeTypeArraysBean> allUserCommUseIncomeTypeArrays) { this.allUserCommUseIncomeTypeArrays = allUserCommUseIncomeTypeArrays; } public static class AllUserCommUseIncomeTypeArraysBean { private String id; private String incomeName; private String parentId; private String parentName; private String icon; private int priority; private int mark; private Object incomeTypeSons; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getIncomeName() { return incomeName; } public void setIncomeName(String incomeName) { this.incomeName = incomeName; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getParentName() { return parentName; } public void setParentName(String parentName) { this.parentName = parentName; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public int getMark() { return mark; } public void setMark(int mark) { this.mark = mark; } public Object getIncomeTypeSons() { return incomeTypeSons; } public void setIncomeTypeSons(Object incomeTypeSons) { this.incomeTypeSons = incomeTypeSons; } } } public static class AllSysSpendTypeBean { private String version; private List<AllSysSpendTypeArraysBean> allSysSpendTypeArrays; public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public List<AllSysSpendTypeArraysBean> getAllSysSpendTypeArrays() { return allSysSpendTypeArrays; } public void setAllSysSpendTypeArrays(List<AllSysSpendTypeArraysBean> allSysSpendTypeArrays) { this.allSysSpendTypeArrays = allSysSpendTypeArrays; } public static class AllSysSpendTypeArraysBean { private long updateDate; private long createDate; private String parentId; private String spendName; private Object spendTypeSons; private Integer delflag; private long delDate; private Integer mark; private String icon; private String status; private int priority; private String id; public long getUpdateDate() { return updateDate; } public void setUpdateDate(long updateDate) { this.updateDate = updateDate; } public long getCreateDate() { return createDate; } public void setCreateDate(long createDate) { this.createDate = createDate; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getSpendName() { return spendName; } public void setSpendName(String spendName) { this.spendName = spendName; } public Object getSpendTypeSons() { return spendTypeSons; } public void setSpendTypeSons(Object spendTypeSons) { this.spendTypeSons = spendTypeSons; } public Integer getDelflag() { return delflag; } public void setDelflag(Integer delflag) { this.delflag = delflag; } public long getDelDate() { return delDate; } public void setDelDate(long delDate) { this.delDate = delDate; } public Integer getMark() { return mark; } public void setMark(Integer mark) { this.mark = mark; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public String getId() { return id; } public void setId(String id) { this.id = id; } } } } }
29.413854
132
0.493237
146fbca4cf5bdf2cc264ffd392e0306c32d60e3d
12,599
package zhuoyuan.li.fluttershareme; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import androidx.annotation.NonNull; import androidx.core.content.FileProvider; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.share.Sharer; import com.facebook.share.model.ShareLinkContent; import com.facebook.share.widget.ShareDialog; import com.twitter.sdk.android.tweetcomposer.TweetComposer; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.MethodChannel.MethodCallHandler; import io.flutter.plugin.common.MethodChannel.Result; import io.flutter.plugin.common.PluginRegistry.Registrar; /** * FlutterShareMePlugin */ public class FlutterShareMePlugin implements MethodCallHandler, FlutterPlugin, ActivityAware { final private static String _methodWhatsApp = "whatsapp_share"; final private static String _methodWhatsAppPersonal = "whatsapp_personal"; final private static String _methodWhatsAppBusiness = "whatsapp_business_share"; final private static String _methodFaceBook = "facebook_share"; final private static String _methodTwitter = "twitter_share"; final private static String _methodSystemShare = "system_share"; final private static String _methodInstagramShare = "instagram_share"; final private static String _methodTelegramShare = "telegram_share"; private Activity activity; private static CallbackManager callbackManager; private MethodChannel methodChannel; /** * Plugin registration. */ public static void registerWith(Registrar registrar) { final FlutterShareMePlugin instance = new FlutterShareMePlugin(); instance.onAttachedToEngine(registrar.messenger()); instance.activity = registrar.activity(); } @Override public void onAttachedToEngine(FlutterPluginBinding binding) { onAttachedToEngine(binding.getBinaryMessenger()); } @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { methodChannel.setMethodCallHandler(null); methodChannel = null; activity = null; } private void onAttachedToEngine(BinaryMessenger messenger) { methodChannel = new MethodChannel(messenger, "flutter_share_me"); methodChannel.setMethodCallHandler(this); callbackManager = CallbackManager.Factory.create(); } /** * method * * @param call methodCall * @param result Result */ @Override public void onMethodCall(MethodCall call, @NonNull Result result) { String url, msg, fileType; switch (call.method) { case _methodFaceBook: url = call.argument("url"); msg = call.argument("msg"); shareToFacebook(url, msg, result); break; case _methodTwitter: url = call.argument("url"); msg = call.argument("msg"); shareToTwitter(url, msg, result); break; case _methodWhatsApp: msg = call.argument("msg"); url = call.argument("url"); shareWhatsApp(url, msg, result, false); break; case _methodWhatsAppBusiness: msg = call.argument("msg"); url = call.argument("url"); shareWhatsApp(url, msg, result, true); break; case _methodWhatsAppPersonal: msg = call.argument("msg"); String phoneNumber = call.argument("phoneNumber"); shareWhatsAppPersonal(msg, phoneNumber, result); break; case _methodSystemShare: msg = call.argument("msg"); shareSystem(result, msg); break; case _methodInstagramShare: msg = call.argument("url"); fileType = call.argument("fileType"); shareInstagramStory(msg, fileType, result); break; case _methodTelegramShare: msg = call.argument("msg"); shareToTelegram(msg, result); break; default: result.notImplemented(); break; } } /** * system share * * @param msg String * @param result Result */ private void shareSystem(Result result, String msg) { try { Intent textIntent = new Intent("android.intent.action.VIEW"); textIntent.setType("text/plain"); textIntent.putExtra("android.intent.extra.TEXT", msg); activity.startActivity(Intent.createChooser(textIntent, "Share to")); result.success("success"); } catch (Exception var7) { result.error("error", var7.toString(), ""); } } /** * share to twitter * * @param url String * @param msg String * @param result Result */ private void shareToTwitter(String url, String msg, Result result) { try { TweetComposer.Builder builder = new TweetComposer.Builder(activity) .text(msg); if (url != null && url.length() > 0) { builder.url(new URL(url)); } builder.show(); result.success("success"); } catch (MalformedURLException e) { e.printStackTrace(); } } /** * share to Facebook * * @param url String * @param msg String * @param result Result */ private void shareToFacebook(String url, String msg, Result result) { ShareDialog shareDialog = new ShareDialog(activity); // this part is optional shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() { @Override public void onSuccess(Sharer.Result result) { System.out.println("--------------------success"); } @Override public void onCancel() { System.out.println("-----------------onCancel"); } @Override public void onError(FacebookException error) { System.out.println("---------------onError"); } }); ShareLinkContent content = new ShareLinkContent.Builder() .setContentUrl(Uri.parse(url)) .setQuote(msg) .build(); if (ShareDialog.canShow(ShareLinkContent.class)) { shareDialog.show(content); result.success("success"); } } /** * share to whatsapp * * @param msg String * @param result Result * @param shareToWhatsAppBiz boolean */ private void shareWhatsApp(String imagePath, String msg, Result result, boolean shareToWhatsAppBiz) { try { Intent whatsappIntent = new Intent(Intent.ACTION_SEND); whatsappIntent.setPackage(shareToWhatsAppBiz ? "com.whatsapp.w4b" : "com.whatsapp"); whatsappIntent.putExtra(Intent.EXTRA_TEXT, msg); // if the url is the not empty then get url of the file and share if (!TextUtils.isEmpty(imagePath)) { whatsappIntent.setType("*/*"); System.out.print(imagePath+"url is not empty"); File file = new File(imagePath); Uri fileUri = FileProvider.getUriForFile(activity, activity.getApplicationContext().getPackageName() + ".provider", file); whatsappIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); whatsappIntent.putExtra(Intent.EXTRA_STREAM, fileUri); whatsappIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } else { whatsappIntent.setType("text/plain"); } activity.startActivity(whatsappIntent); result.success("success"); } catch (Exception var9) { result.error("error", var9.toString(), ""); } } /** * share to telegram * * @param msg String * @param result Result */ private void shareToTelegram(String msg, Result result) { try { Intent telegramIntent = new Intent(Intent.ACTION_SEND); telegramIntent.setType("text/plain"); telegramIntent.setPackage("org.telegram.messenger"); telegramIntent.putExtra(Intent.EXTRA_TEXT, msg); try { activity.startActivity(telegramIntent); result.success("true"); } catch (Exception ex) { result.success("false:Telegram app is not installed on your device"); } } catch (Exception var9) { result.error("error", var9.toString(), ""); } } /** * share whatsapp message to personal number * * @param msg String * @param phoneNumber String with country code * @param result */ private void shareWhatsAppPersonal(String msg, String phoneNumber, Result result) { String url = null; try { url = "https://api.whatsapp.com/send?phone=" + phoneNumber + "&text=" + URLEncoder.encode(msg, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } Intent i = new Intent(Intent.ACTION_VIEW); i.setPackage("com.whatsapp"); i.setData(Uri.parse(url)); activity.startActivity(i); result.success("success"); } /** * share to instagram * * @param url local file path * @param fileType type of file to share (image or video) * @param result flutterResult */ private void shareInstagramStory(String url, String fileType, Result result) { if (instagramInstalled()) { File file = new File(url); Uri fileUri = FileProvider.getUriForFile(activity, activity.getApplicationContext().getPackageName() + ".provider", file); Intent instagramIntent = new Intent(Intent.ACTION_SEND); if(fileType.equals("image")) instagramIntent.setType("image/*"); else if(fileType.equals("video")) instagramIntent.setType("video/*"); instagramIntent.putExtra(Intent.EXTRA_STREAM, fileUri); instagramIntent.setPackage("com.instagram.android"); try { activity.startActivity(instagramIntent); result.success("Success"); } catch (ActivityNotFoundException e) { e.printStackTrace(); result.success("Failure"); } } else { result.error("Instagram not found", "Instagram is not installed on device.", ""); } } @Override public void onAttachedToActivity(ActivityPluginBinding binding) { activity = binding.getActivity(); } @Override public void onDetachedFromActivityForConfigChanges() { } @Override public void onReattachedToActivityForConfigChanges(ActivityPluginBinding binding) { activity = binding.getActivity(); } @Override public void onDetachedFromActivity() { } ///Utils methods private boolean instagramInstalled() { try { if (activity != null) { activity.getPackageManager() .getApplicationInfo("com.instagram.android", 0); return true; } else { Log.d("App", "Instagram app is not installed on your device"); return false; } } catch (PackageManager.NameNotFoundException e) { return false; } // return false; } }
34.707989
138
0.601159
f7a7818648571b1193a7b09b44ffa549866c6703
905
package org.openstack4j.model.network.ext.status; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.openstack4j.model.ModelEntity; import org.openstack4j.model.network.ext.HealthMonitorType; import org.openstack4j.openstack.networking.domain.ext.LoadBalancerV2StatusTree.NeutronHealthMonitorV2Status; /** * The status of an lbaas v2 heathmonitor * * @author emjburns */ @JsonDeserialize(as = NeutronHealthMonitorV2Status.class) public interface HealthMonitorV2Status extends ModelEntity { /** * The id of the healthmonitor * * @return id */ public String getId(); /** * The health monitor type * * @return HealthMonitorType */ public HealthMonitorType getType(); /** * Provisioning status of the health monitor * * @return provisioningStatus */ public String getProvisioningStatus(); }
25.138889
109
0.720442
8ceef90ebfc101d983e08fa5ff94657b73ad6b39
3,478
/** * @Name: JavaClosingHomework * @Author: SaarChaffee * @Code: UTF-8 * @Date: Created in 2021 2021/6/6 */ package main.DAO; import java.sql.ResultSet; import java.sql.SQLException; public class DaoPro { public static boolean isFriend( int UserUid, int FriendUid ) { try{ if( UserUid > FriendUid ){ UserUid = UserUid ^ FriendUid; FriendUid = UserUid ^ FriendUid; UserUid = UserUid ^ FriendUid; } ResultSet re = DaoPlus.getFriend( UserUid ); while( re.next() ){ if( re.getInt( "friend" ) == FriendUid ) return true; } }catch( SQLException throwables ){ throwables.printStackTrace(); } return false; } public static boolean isRedemptionUsed( String RedemptionCode ) { try{ ResultSet re = DaoPlus.getRedemptionInfo( RedemptionCode ); re.next(); if( re.getInt( "RedemptionUsed" ) != 0 ) return true; }catch( SQLException throwables ){ throwables.printStackTrace(); } return false; } public static int recharge( int UserUid, String Code ) { int result = 0; if( !isRedemptionUsed( Code ) ){ ResultSet re; int balance = 0; try{ re = DaoPlus.getRedemptionInfo( Code ); re.next(); balance = DaoPlus.getUserBalance( UserUid ) + re.getInt( "RedemptionCodeValue" ); }catch( SQLException throwables ){ throwables.printStackTrace(); } String str1 = "update UserData set UserBalance = " + balance + " where UserUid = " + UserUid; result += DaoBase.Update( str1 ); String str2 = "update Redemption set RedemptionUsed = " + UserUid + " where RedemptionCode = '" + Code + "'"; result += DaoBase.Update( str2 ); } return result; } public static boolean[] colles( int UserUid ) { ResultSet re = DaoPlus.getColleSet( UserUid ); boolean[] bl = new boolean[61]; try{ re.next(); for( int i = 1; i <= 60; i++ ){ bl[i] = re.getBoolean( i + 1 ); } re.close(); }catch( SQLException throwables ){ throwables.printStackTrace(); } return bl; } public static int getWin( int UserUid ) { ResultSet re; int win = 0; try{ re = DaoPlus.getAllUserData( UserUid ); re.next(); win = re.getInt( "UserWin" ); }catch( SQLException throwables ){ throwables.printStackTrace(); } return win; } public static int getLost( int UserUid ) { ResultSet re; int lost = 0; try{ re = DaoPlus.getAllUserData( UserUid ); re.next(); lost = re.getInt( "UserLost" ); }catch( SQLException throwables ){ throwables.printStackTrace(); } return lost; } public static int getReport( int UserUid ) { ResultSet re; int report = 0; try{ re = DaoPlus.getAllUserData( UserUid ); re.next(); report = re.getInt( "Reported" ); }catch( SQLException throwables ){ throwables.printStackTrace(); } return report; } }
29.474576
121
0.518976
d10c4d99e086452674458d0d7813ae2d47891e80
1,585
package com.jwcrain.sandcastle; import java.util.HashMap; import java.util.Map; public class DocumentFrequency { HashMap<String, Integer> frequency = new HashMap<>(); public DocumentFrequency(String document) { String[] words = document.split(" "); for (int i = 0; i < words.length; i++) { String currentWord = words[i]; currentWord = sanitizeWord(currentWord); if (frequency.containsKey(currentWord)) { int currentFrequency = frequency.get(currentWord); frequency.put(currentWord, currentFrequency + 1); } else { frequency.put(currentWord, 1); } } } private String sanitizeWord(String input) { StringBuilder output = new StringBuilder(); input = input.toLowerCase().trim(); for (int i = 0; i < input.length(); i++) { char currentChar = input.charAt(i); if (currentChar >= 'a' && currentChar <= 'z') { output.append(currentChar); } } return output.toString(); } public Integer search(String search) { if (frequency.containsKey(search)) { return frequency.get(search); } return null; } public void print() { StringBuilder stringBuilder = new StringBuilder(); for (String key : frequency.keySet()) { stringBuilder.append(key).append("=").append(frequency.get(key)).append("; "); } System.out.println(stringBuilder.toString()); } }
26.416667
90
0.5653
0fc49b80961679209509a8934c1765510b78d317
3,063
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.commands.auton; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.WaitCommand; import frc.robot.util; import frc.robot.commands.BeakAutonCommand; import frc.robot.commands.chassis.RotateDrivetrainToAngle; import frc.robot.commands.chassis.RotateDrivetrainToOdometryTargetAngle; import frc.robot.commands.conveyor.RunConveyor; import frc.robot.commands.shooter.ResetDefaultIndex; import frc.robot.subsystems.Infeed; import frc.robot.subsystems.Shooter; import frc.robot.utilities.Trajectories; // NOTE: Consider using this command inline, rather than writing a subclass. For more // information, see: // https://docs.wpilib.org/en/stable/docs/software/commandbased/convenience-features.html public class FourBallAuton extends BeakAutonCommand { /** Creates a new TestAutonCommand. */ public FourBallAuton() { // Add your commands in the addCommands() call, e.g. // addCommands(new FooCommand(), new BarCommand()); super.addCommands( new ResetDefaultIndex(), new InstantCommand(() -> Infeed.getInstance().setInfeedDown()), new WaitCommand(0.25), util.getPathPlannerSwerveControllerCommand(Trajectories.FourBall_AcquireFirstCargo()) .alongWith(new InstantCommand(() -> Infeed.getInstance().runInfeedSingulatorMotors(1.0))), new WaitCommand(0.5), new RotateDrivetrainToAngle(Rotation2d.fromDegrees(37.0)) .alongWith(new InstantCommand(() -> Shooter.getInstance().runShooterMotors())), new WaitCommand(1.1).deadlineWith(new RunConveyor()), util.getPathPlannerSwerveControllerCommand(Trajectories.FourBall_AcquireLoadingZoneCargo()).alongWith( new WaitCommand(0.5).andThen(new InstantCommand(() -> Shooter.getInstance().stop()))), new WaitCommand(1.5), util.getPathPlannerSwerveControllerCommand(Trajectories.FourBall_ReturnToShoot()) .alongWith(new WaitCommand(0.5) .andThen(new InstantCommand(() -> Shooter.getInstance().runShooterMotors()))), new WaitCommand(1.1).deadlineWith(new RunConveyor()), new WaitCommand(0.25).andThen(new InstantCommand(() -> Shooter.getInstance().stop())), new InstantCommand(() -> Infeed.getInstance().stopInfeedSingulatorMotors()), new RotateDrivetrainToOdometryTargetAngle().withTimeout(2.5)); super.setInitialPose(Trajectories.FourBall_AcquireFirstCargo()); } public static Pose2d initialPose() { return Trajectories.FourBall_AcquireFirstCargo().getInitialPose(); } }
54.696429
118
0.695397
94cac9275be523002e724848f3a69ffbda65629d
156
/* * Copyright (c) 2017-01-02 23:31, Kenta Yamamoto <ymkjp@jaist.ac.jp>, s1510756. */ public interface Nat extends Comparable<Nat> { Nat plus(Nat y); }
22.285714
80
0.679487
b8b2d3424138b1d2406c70bb93b3aba1a6c9d0e1
7,131
/** */ package thing_ui.interaction.util; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.util.Switch; import thing_ui.interaction.*; /** * <!-- begin-user-doc --> * The <b>Switch</b> for the model's inheritance hierarchy. * It supports the call {@link #doSwitch(EObject) doSwitch(object)} * to invoke the <code>caseXXX</code> method for each class of the model, * starting with the actual class of the object * and proceeding up the inheritance hierarchy * until a non-null result is returned, * which is the result of the switch. * <!-- end-user-doc --> * @see thing_ui.interaction.InteractionPackage * @generated */ public class InteractionSwitch<T> extends Switch<T> { /** * The cached model package * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static InteractionPackage modelPackage; /** * Creates an instance of the switch. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public InteractionSwitch() { if (modelPackage == null) { modelPackage = InteractionPackage.eINSTANCE; } } /** * Checks whether this is a switch for the given package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param ePackage the package in question. * @return whether this is a switch for the given package. * @generated */ @Override protected boolean isSwitchFor(EPackage ePackage) { return ePackage == modelPackage; } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ @Override protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case InteractionPackage.FORM: { Form form = (Form)theEObject; T result = caseForm(form); if (result == null) result = defaultCase(theEObject); return result; } case InteractionPackage.INPUT: { Input input = (Input)theEObject; T result = caseInput(input); if (result == null) result = defaultCase(theEObject); return result; } case InteractionPackage.TEXT_INPUT: { TextInput textInput = (TextInput)theEObject; T result = caseTextInput(textInput); if (result == null) result = caseInput(textInput); if (result == null) result = defaultCase(theEObject); return result; } case InteractionPackage.NUMBER_INPUT: { NumberInput numberInput = (NumberInput)theEObject; T result = caseNumberInput(numberInput); if (result == null) result = caseInput(numberInput); if (result == null) result = defaultCase(theEObject); return result; } case InteractionPackage.OBJECT_INPUT: { ObjectInput objectInput = (ObjectInput)theEObject; T result = caseObjectInput(objectInput); if (result == null) result = caseInput(objectInput); if (result == null) result = defaultCase(theEObject); return result; } case InteractionPackage.BOOL_INPUT: { boolInput boolInput = (boolInput)theEObject; T result = caseboolInput(boolInput); if (result == null) result = caseInput(boolInput); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpreting the object as an instance of '<em>Form</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Form</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseForm(Form object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Input</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Input</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseInput(Input object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Text Input</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Text Input</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseTextInput(TextInput object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Number Input</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Number Input</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseNumberInput(NumberInput object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Object Input</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Object Input</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseObjectInput(ObjectInput object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>bool Input</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>bool Input</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseboolInput(boolInput object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>EObject</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>EObject</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ @Override public T defaultCase(EObject object) { return null; } } //InteractionSwitch
32.413636
118
0.68083
31c3986f20fdf5bd5a76d153a576d53dbb806e3a
705
package net.rizon.moo.plugin.tickets.conf; import net.rizon.moo.conf.Configuration; import net.rizon.moo.conf.ConfigurationException; import net.rizon.moo.conf.Validator; public class TicketsConfiguration extends Configuration { public String url, username, password; public static TicketsConfiguration load() throws Exception { return load("tickets.yml", TicketsConfiguration.class); } @Override public void validate() throws ConfigurationException { Validator.validateURL("Tickets URL", url); Validator.validateNotEmpty("Tickets Username", username); // In case you're connecting to a site without a password. :D Validator.validateNullOrNotEmpty("Tickets Password", password); } }
28.2
65
0.785816
965a8b4ec298151d3e5b8fbce2b7547dfb1d3fcf
535
package com.proposta.propostaservice.cartao.bloqueio; import com.proposta.propostaservice.cartao.Cartao; import javax.validation.constraints.NotBlank; public class BloqueioRequest { @NotBlank private String ip; @NotBlank private String userAgent; public BloqueioRequest( @NotBlank String ip, @NotBlank String userAgent) { this.ip = ip; this.userAgent = userAgent; } public BloqueioCartao toBloqueioCartao(Cartao cartao){ return new BloqueioCartao(cartao,ip,userAgent); } }
23.26087
78
0.725234
8ee574f81a475acf749e2a891583effc122543eb
2,208
/* * (c) Copyright 2015 Micro Focus or one of its affiliates. * * Licensed under the MIT License (the "License"); you may not use this file * except in compliance with the License. * * The only warranties for products and services of Micro Focus and its affiliates * and licensors ("Micro Focus") are as may be set forth in the express warranty * statements accompanying such products and services. Nothing herein should be * construed as constituting an additional warranty. Micro Focus shall not be * liable for technical or editorial errors or omissions contained herein. The * information contained herein is subject to change without notice. */ package com.hp.autonomy.searchcomponents.idol.configuration; import com.autonomy.aci.client.services.AciService; import com.hp.autonomy.frontend.configuration.ConfigService; import com.hp.autonomy.searchcomponents.core.search.QueryRequest; import org.apache.commons.lang.BooleanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * Default implementation of {@link AciServiceRetriever} */ @Component(AciServiceRetriever.ACI_SERVICE_RETRIEVER_BEAN_NAME) class AciServiceRetrieverImpl implements AciServiceRetriever { private final ConfigService<? extends IdolSearchCapable> configService; private final AciService contentAciService; private final AciService qmsAciService; @Autowired AciServiceRetrieverImpl(final ConfigService<? extends IdolSearchCapable> configService, final AciService contentAciService, final AciService qmsAciService) { this.configService = configService; this.contentAciService = contentAciService; this.qmsAciService = qmsAciService; } @Override public boolean qmsEnabled() { return configService.getConfig().getQueryManipulation() != null && BooleanUtils.isTrue(configService.getConfig().getQueryManipulation().getEnabled()); } @Override public AciService getAciService(final QueryRequest.QueryType queryType) { final boolean useQms = qmsEnabled() && queryType != QueryRequest.QueryType.RAW; return useQms ? qmsAciService : contentAciService; } }
43.294118
161
0.779891
61044ce8bea43617b2aec3be60cd84712d178cef
363
package de.siebn.javaBug.util; public class JsUtil { public static String getSelector(XML xml) { String id = xml.getId(); return id == null ? null : "#" + id; } public static String getJQuerySelector(XML xml) { String selector = getSelector(xml); return selector == null ? null : "$(\"" + selector + "\")"; } }
22.6875
67
0.578512
4669ad24783650252e0df5624bdc5b1bf6a153a0
603
package org.activiti.bpmn.model; public class Assignment extends BaseElement { protected String from; protected String to; public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public Assignment clone() { Assignment clone = new Assignment(); clone.setValues(this); return clone; } public void setValues(Assignment otherAssignment) { setFrom(otherAssignment.getFrom()); setTo(otherAssignment.getTo()); } }
17.228571
53
0.666667
60ecf4ea99c1d3cea8c91b6ac3472e7cf765ddf3
1,936
package io.github.jitwxs.easydata.core.mybatis.action; import io.github.jitwxs.easydata.common.cache.PropertyCache; import io.github.jitwxs.easydata.common.enums.ClassDiffVerifyStrategyEnum; import io.github.jitwxs.easydata.common.exception.EasyDataException; import io.github.jitwxs.easydata.core.verify.EasyVerify; import io.github.jitwxs.easydata.core.verify.VerifyInstance; import lombok.AllArgsConstructor; import org.apache.ibatis.builder.xml.XMLMapperBuilder; import org.apache.ibatis.mapping.ResultMap; import org.apache.ibatis.session.Configuration; import java.util.Set; /** * inspect mybatis mapper file resultMap with entity attribute is match * * @author jitwxs@foxmail.com * @since 2022-06-05 9:39 */ @AllArgsConstructor public class ResultMapAttributeMapperInspectAction implements IMapperInspectStaticAction { /** * mybatis mapper xml inspect resultMap's id */ private final String resultMapId; /** * ignore inspect field in resultMap */ private final String[] ignoreFields; @Override public void doAction(XMLMapperBuilder xmlMapperBuilder) { final Configuration configuration = xmlMapperBuilder.getConfiguration(); final ResultMap resultMap = configuration.getResultMap(resultMapId); if (resultMap == null) { throw new EasyDataException("Not found resultMap: " + resultMapId); } final Class<?> target = resultMap.getType(); final Set<String> except = PropertyCache.tryGet(target).getAll().keySet(); final Set<String> actual = resultMap.getMappedProperties(); final VerifyInstance instance = EasyVerify.with(except, actual); if (ignoreFields != null && ignoreFields.length > 0) { // using ignore elements instance.ignoreElements(ignoreFields); } instance.ignoreClassDiff(ClassDiffVerifyStrategyEnum.CONVERT_SAME_CLASS).verify(); } }
34.571429
90
0.733471
08bebc9b3f153ba4d461427dd26c275aafb25b98
3,299
/* * Copyright 2022 Whilein * * 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 w.asm; import lombok.SneakyThrows; import lombok.val; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import w.util.ClassLoaderUtils; import w.util.TypeUtils; import java.util.function.BiConsumer; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.objectweb.asm.Opcodes.IRETURN; /** * @author whilein */ final class MakerTests { ClassMaker cm; @BeforeEach void tearUp() { cm = new ClassMaker(0); cm.visit( Opcodes.V1_1, Opcodes.ACC_PUBLIC, "Test", null, "java/lang/Object", null ); } private Class<?> make() { val bytes = cm.toByteArray(); return ClassLoaderUtils.defineClass(this.getClass().getClassLoader(), cm.name, bytes); } @Test @SneakyThrows void testEmptyConstructor() { cm.visitEmptyConstructor(Opcodes.ACC_PUBLIC).visitEnd(); Object object = make().getConstructor().newInstance(); assertNotNull(object); } private String getNumber(final Number number) { return ("getNumber" + number).replace('-', 'M').replace('.', '_'); } @SneakyThrows <T extends Number> void testNumbers(final T[] numbers, final BiConsumer<MethodMaker, T> maker) { for (val number : numbers) { val primitive = TypeUtils.getPrimitive(number.getClass()).orElseThrow(); val primitiveType = Type.getType(primitive); val mm = cm.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, getNumber(number), "()" + primitiveType.getDescriptor(), null, null); maker.accept(mm, number); mm.visitInsn(primitiveType.getOpcode(IRETURN)); mm.visitMaxs(2, 0); } val cls = make(); for (val test : numbers) { assertEquals(test, cls.getDeclaredMethod(getNumber(test)).invoke(null)); } } @Test @SneakyThrows void testVisitFloat() { testNumbers(new Float[]{0f, 1f, 1.1f, 100f}, MethodMaker::visitFloat); } @Test @SneakyThrows void testVisitDouble() { testNumbers(new Double[]{0d, 1d, 1.1d, 100d}, MethodMaker::visitDouble); } @Test @SneakyThrows void testVisitLong() { testNumbers(new Long[]{0L, 1L, 100L}, MethodMaker::visitLong); } @Test @SneakyThrows void testVisitInt() { testNumbers(new Integer[]{-1, 0, 1, 2, 3, 4, 5, 100, 1000, 10000}, MethodMaker::visitInt); } }
27.957627
100
0.636557
57c7f7f38c35b3fcc268e9a6cd71d00633d682da
1,361
package pratica_facul; import java.util.Scanner; public class Questao08 { public static void main(String[]args){ Scanner teclado = new Scanner(System.in); int v2[] = new int[3]; int dia; int mes; int ano; int i; int r2 = 0; System.out.print("Digite quantos anos você tem: "); ano = teclado.nextInt(); System.out.print("Quantos meses desde que completou "+ano+" anos: "); mes = teclado.nextInt(); System.out.print("Quantos dias: "); dia = teclado.nextInt(); teclado.close(); for(i=0; i < v2.length;i++){ if (i == 0 ) { v2[i] = ano ; r2 += (v2[i] * 365); } if (i == 1) { v2[i] = mes; r2 += (v2[i] * 30); } if (i == 2) { v2[i] = dia; r2 += v2[i]; } } System.out.println(""); System.out.println("Hoje você está com "+r2+" dias de idade"); } } /* Ler a idade da pessoa expressa em anos, meses e dias e imprimir expressa apenas em dias. */
24.303571
83
0.392359
c3f3805fdcf515d12cbc41253af40f8cdb061f36
3,440
package com.infoclinika.mssharing.model.internal.entity; import com.infoclinika.mssharing.platform.entity.AbstractPersistable; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import javax.persistence.*; import java.util.Date; @Entity @Table(name = "storage_usage_statistics") public class StorageUsageStatistics extends AbstractPersistable { @ManyToOne(optional = false) @JoinColumn(name = "lab_id") @Fetch(FetchMode.JOIN) private Lab lab; @Column(name = "from_date") private Date from; @Column(name = "to_date") private Date to; @Column(name = "raw_files_count") private int rawFilesCount; @Column(name = "raw_files_size") private long rawFilesSize; @Column(name = "other_files_count") private int otherFilesCount; @Column(name = "other_files_size") private long otherFilesSize; @Column(name = "total_files_size") private long totalFilesSize; public StorageUsageStatistics() { } public StorageUsageStatistics(Lab lab, Date from, Date to, int rawFilesCount, long rawFilesSize, int otherFilesCount, long otherFilesSize, long totalFilesSize) { this.lab = lab; this.from = from; this.to = to; this.rawFilesCount = rawFilesCount; this.rawFilesSize = rawFilesSize; this.otherFilesCount = otherFilesCount; this.otherFilesSize = otherFilesSize; this.totalFilesSize = totalFilesSize; } public Lab getLab() { return lab; } public void setLab(Lab lab) { this.lab = lab; } public Date getFrom() { return from; } public void setFrom(Date from) { this.from = from; } public Date getTo() { return to; } public void setTo(Date to) { this.to = to; } public int getRawFilesCount() { return rawFilesCount; } public void setRawFilesCount(int rawFilesCount) { this.rawFilesCount = rawFilesCount; } public long getRawFilesSize() { return rawFilesSize; } public void setRawFilesSize(long rawFilesSize) { this.rawFilesSize = rawFilesSize; } public int getOtherFilesCount() { return otherFilesCount; } public void setOtherFilesCount(int otherFilesCount) { this.otherFilesCount = otherFilesCount; } public long getOtherFilesSize() { return otherFilesSize; } public void setOtherFilesSize(long otherFilesSize) { this.otherFilesSize = otherFilesSize; } public long getTotalFilesSize() { return totalFilesSize; } public void setTotalFilesSize(long totalFilesSize) { this.totalFilesSize = totalFilesSize; } @Override public String toString() { return "StorageUsageStatistics{" + "lab=" + lab + ", from=" + from + ", to=" + to + ", rawFilesCount=" + rawFilesCount + ", rawFilesSize=" + rawFilesSize + ", otherFilesCount=" + otherFilesCount + ", otherFilesSize=" + otherFilesSize + ", totalFilesSize=" + totalFilesSize + '}'; } }
24.571429
69
0.593314
6aea01c557b31d5f0ed92a66f54a5250db65327d
456
package bi.know.kettle.neo4j.steps.split; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.trans.step.BaseStepData; import org.pentaho.di.trans.step.StepDataInterface; import java.util.List; public class SplitGraphData extends BaseStepData implements StepDataInterface { public RowMetaInterface outputRowMeta; public int graphFieldIndex; public String typeField; public String idField; public String propertySetField; }
26.823529
79
0.820175
d359a9f9bb15389dc04efa29bcdc08f6a06eb62e
2,290
/********************************************************************* * Copyright 2010, UCAR/Unidata * See netcdf/COPYRIGHT file for copying and redistribution conditions. * $Id$ * $Header$ *********************************************************************/ package unidata.ast.runtime; // Wrapper class to provide expandable byte valuebuffer class ByteBuffer { static final int INITSIZE = 256; byte[] buffer = new byte[INITSIZE]; int pos = 0; byte[] converter = new byte[8] ; public ByteBuffer() {} public void clear() {pos = 0;} public void setSize(int size) { if(buffer == null || ((buffer.length - pos) <= size)) { byte[] newbuf = new byte[size]; if(pos > 0) System.arraycopy(buffer,0,newbuf,0,pos); buffer = newbuf; } } public int getPosition() {return pos;} public byte[] getBuffer() {return buffer;} public byte[] getContent() { byte[] newbuf = new byte[pos]; if(pos > 0) System.arraycopy(buffer,0,newbuf,0,pos); return newbuf; } public void add(byte[] bytes, int offset, int length) { if((buffer.length - pos) <= length) { byte[] newbuf = new byte[pos*2+length]; System.arraycopy(buffer,0,newbuf,0,pos); } System.arraycopy(bytes,offset,buffer,pos,length); pos += length; } // Type converters public void add(int value) { converter[0] = (byte)((value)|0xff); converter[1] = (byte)((value>>>8)|0xff); converter[2] = (byte)((value>>>16)|0xff); converter[3] = (byte)((value>>>24)|0xff); add(converter,0,4); } public void add(long value) { converter[0] = (byte)((value)|0xff); converter[1] = (byte)((value>>>8)|0xff); converter[2] = (byte)((value>>>16)|0xff); converter[3] = (byte)((value>>>24)|0xff); converter[4] = (byte)((value>>>32)|0xff); converter[5] = (byte)((value>>>40)|0xff); converter[6] = (byte)((value>>>48)|0xff); converter[7] = (byte)((value>>>56)|0xff); add(converter,0,8); } public void add(double value) { long n = Double.doubleToLongBits(value); add(n); } public void add(float value) { int n = Float.floatToIntBits(value); add(n); } }
23.131313
73
0.537555
cbcab29cecfa102cc9241d46d5e8e804f3cca22e
206
package de.schleger.boiler.heat; import de.schleger.boiler.config.HeatPower; public interface HeatTimeInterpolator { public Float interpolateTimeToHeat(float deltaTemperature, HeatPower heatPower); }
25.75
84
0.825243
eadbf4fceba51f78a2e83547693fe510833fdbfb
515
package everything.AI.AICards; import everything.Player; import everything.Card; import java.util.Random; /** * Created by Steve on 4/17/2017. */ public class GoblinStrike extends Card { public GoblinStrike(){ super("Goblin swings wildly, dealing 1-8 damage", "Goblin Strike", "Attack", 0,0, false); } public void cardFunction(Player p1, Player p2) { Random number = new Random(0); int randomnum1 = number.nextInt((8-1) + 1) + 1; p2.takeDamage(randomnum1); } }
23.409091
97
0.656311
c77bd5e317f78ef1b5646eb934b750501cd2621f
1,733
/* * Copyright 2011 SpringSource * * 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.grails.datastore.mapping.validation; import org.springframework.validation.BeanPropertyBindingResult; /** * Models validation errors * * @author Graeme Rocher * @since 2.0 */ public class ValidationErrors extends BeanPropertyBindingResult { private static final long serialVersionUID = 1; /** * Creates a new instance of the {@link org.springframework.validation.BeanPropertyBindingResult} class. * * @param target the target bean to bind onto * @param objectName the name of the target object */ public ValidationErrors(Object target, String objectName) { super(target, objectName); } /** * Creates a new instance of the {@link org.springframework.validation.BeanPropertyBindingResult} class. * * @param target the target bean to bind onto */ public ValidationErrors(Object target) { super(target, target.getClass().getName()); } public Object getAt(String field) { return getFieldError(field); } public void putAt(String field, String errorCode) { rejectValue(field, errorCode); } }
31.509091
108
0.704559
3121b8e94848494d19516c4963cfa43f94dd730e
915
package com.avalith.hotelo.utils; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Validator { public static boolean isValidPassword(final String password) { Pattern pattern; Matcher matcher; final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=\\S+$).{8,}$"; pattern = Pattern.compile(PASSWORD_PATTERN); matcher = pattern.matcher(password); return matcher.matches(); } public static boolean isEmailValid(String email) { boolean isValid = false; String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$"; CharSequence inputStr = email; Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(inputStr); if (matcher.matches()) { isValid = true; } return isValid; } }
26.142857
92
0.597814
2642ab6557fc8e2af2a23ccbc64e6411cd90cd1a
3,968
package com.zoomulus.speakeasy.sdp.messages; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import java.net.Inet4Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.Map; import java.util.Optional; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.net.MediaType; import com.zoomulus.speakeasy.core.types.AddrType; import com.zoomulus.speakeasy.core.types.LocalInetAddress; import com.zoomulus.speakeasy.sdp.messages.exceptions.SDPMessageException; import com.zoomulus.speakeasy.sdp.types.SDPOrigin; public class SDPMessageTest { SDPMessage defaultMessage; SDPOrigin defaultOrigin; private void fail() { assertFalse(true); } @Before public void setup() throws UnknownHostException, SDPMessageException { defaultMessage = SDPMessage.builder() .origin(new SDPOrigin(Inet4Address.getLoopbackAddress())) .build(); Optional<InetAddress> inetAddress = LocalInetAddress.guess(AddrType.IP4); defaultOrigin = new SDPOrigin(inetAddress.isPresent() ? inetAddress.get() : InetAddress.getByName("127.0.0.1")); } @After public void teardown() { defaultMessage = null; } private ByteBuffer buildSimpleSdp(final Map<String, String> sdpValues) { final StringBuilder builder = new StringBuilder(); builder.append(String.format("%s=%s\n", "v", sdpValues.getOrDefault("v", SDPMessage.VERSION))); builder.append(String.format("%s=%s\n", "o", sdpValues.getOrDefault("o", defaultOrigin.toString()))); return ByteBuffer.wrap(builder.toString().getBytes()); } @Test public void testBuildSDPMessage() { assertNotNull(defaultMessage); } @Test public void testContentTypeIsApplicationSDP() { assertEquals(MediaType.create("application", "sdp"), defaultMessage.contentType()); assertEquals("application/sdp", defaultMessage.contentType().toString()); } @Test public void testVersionIs0() { assertEquals("0", defaultMessage.version()); } @Test public void testParseInvalidVersionFails() { for (final String s : Lists.newArrayList("", null, "1", "invalid")) { try { final Map<String, String> sdpValues = Maps.newHashMap(); sdpValues.put(SDPMessage.Tokens.VERSION_TOKEN, s); SDPMessage.parse(buildSimpleSdp(sdpValues)); fail(); } catch (SDPMessageException e) { } } } @Test public void testParseValidVersion() throws SDPMessageException { final Map<String, String> sdpValues = Maps.newHashMap(); sdpValues.put(SDPMessage.Tokens.VERSION_TOKEN, "0"); SDPMessage.parse(buildSimpleSdp(sdpValues)); } @Test public void testParseInvalidOriginFails() { for (final String s : Lists.newArrayList("", null, "invalid", "- 12345 54321 OUT IP4 127.0.0.1", "- 12345 54321 IN IP7 127.0.0.1")) { try { final Map<String, String> sdpValues = Maps.newHashMap(); sdpValues.put(SDPMessage.Tokens.ORIGIN_TOKEN, s); SDPMessage.parse(buildSimpleSdp(sdpValues)); fail(); } catch (SDPMessageException e) { } } } @Test public void testParseValidOrigin() throws SDPMessageException { final Map<String, String> sdpValues = Maps.newHashMap(); sdpValues.put(SDPMessage.Tokens.ORIGIN_TOKEN, "- 12345 54321 IN IP4 127.0.0.1"); SDPMessage.parse(buildSimpleSdp(sdpValues)); } }
32
139
0.648942
feb5555ee27cd4acfc5e1f2dc490787c92cdac69
691
package cn.lee.leetcode.probolems.g1; import lombok.extern.slf4j.Slf4j; /** * @Title: Q167 * @Description: https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/ * @author: libo * @date: 2020/9/15 22:48 * @Version: 1.0 */ @Slf4j public class Q167 { public int[] twoSum(int[] numbers, int target) { int[] pos = new int[2]; for (int i = 0; i < numbers.length - 1; i++) { for (int j = i + 1; j < numbers.length; j++) { if (numbers[i] + numbers[j] == target) { pos[0] = i+1; pos[1] = j+1; break; } } } return pos; } }
23.827586
83
0.477569
e1f561482d660c4b68a8600b8769e4a289ff0540
4,871
package org.protege.osgi.jdbc.prefs; import org.osgi.framework.BundleContext; import org.osgi.util.tracker.ServiceTracker; import org.protege.editor.core.prefs.Preferences; import org.protege.editor.core.prefs.PreferencesManager; import org.protege.editor.owl.ui.preferences.OWLPreferencesPanel; import org.protege.osgi.jdbc.JdbcRegistry; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class PreferencesPanel extends OWLPreferencesPanel { private static final long serialVersionUID = 2892884854196959326L; public static final String PREFERENCES_SET="org.protege.osgi.jdbc.prefs"; public static final String DRIVER_PREFERENCES_KEY="driver.list"; public static final String DEFAULT_DRIVER_DIR="driver.dir"; private JTable table; private DriverTableModel driverTableModel; private ServiceTracker jdbcRegistryTracker; @Override public void initialise() throws Exception { BundleContext context = Activator.getInstance().getContext(); jdbcRegistryTracker = new ServiceTracker(context, JdbcRegistry.class.getName(), null); setPreferredSize(new java.awt.Dimension(620, 300)); setLayout(new GridBagLayout()); GridBagConstraints listConstraints = new GridBagConstraints(); listConstraints.fill = GridBagConstraints.BOTH; listConstraints.gridx = 0; listConstraints.gridy = 0; listConstraints.gridwidth = 3; listConstraints.gridheight = 3; listConstraints.weightx=1; listConstraints.weighty=1; GridBagConstraints buttonsConstraints = new GridBagConstraints(); buttonsConstraints.gridx = 0; buttonsConstraints.gridy = 4; add(createList(), listConstraints); add(createButtons(), buttonsConstraints); } @Override public void applyChanges() { setDrivers(driverTableModel.getDrivers()); } @Override public void dispose() { } public static List<DriverInfo> getDrivers() { List<DriverInfo> drivers = new ArrayList<>(); Preferences prefs = PreferencesManager.getInstance().getPreferencesForSet(PREFERENCES_SET, DRIVER_PREFERENCES_KEY); Iterator<String> driverStrings = prefs.getStringList(DRIVER_PREFERENCES_KEY, new ArrayList<>()).iterator(); while (driverStrings.hasNext()) { drivers.add(new DriverInfo(driverStrings.next(), driverStrings.next(), new File(driverStrings.next()))); } return drivers; } private void setDrivers(List<DriverInfo> drivers) { Preferences prefs = PreferencesManager.getInstance().getPreferencesForSet(PREFERENCES_SET, DRIVER_PREFERENCES_KEY); List<String> prefsStringList = new ArrayList<>(); for (DriverInfo driver : drivers) { prefsStringList.add(driver.getDescription()); prefsStringList.add(driver.getClassName()); prefsStringList.add(driver.getDriverLocation().getPath()); } prefs.clear(); prefs.putStringList(DRIVER_PREFERENCES_KEY, prefsStringList); } private JComponent createList() { driverTableModel = new DriverTableModel(getDrivers(), jdbcRegistryTracker); table = new JTable(driverTableModel); return new JScrollPane(table); } private JComponent createButtons() { JPanel panel = new JPanel(); panel.setLayout(new FlowLayout()); JButton add = new JButton("Add"); add.addActionListener(this::handleAdd); panel.add(add); JButton remove = new JButton("Remove"); panel.add(remove); remove.addActionListener(this::handleRemove); JButton edit = new JButton("Edit"); panel.add(edit); edit.addActionListener(this::handleEdit); return panel; } public void handleAdd(ActionEvent e) { final EditorPanel editor = new EditorPanel(jdbcRegistryTracker); DriverInfo info = editor.askUserForDriverInfo(); if (info != null) { driverTableModel.addDriver(info); } } public void handleRemove(ActionEvent e) { int[] rows = table.getSelectedRows(); List<Integer> rowList = new ArrayList<>(); for (int row : rows) { rowList.add(row); } driverTableModel.removeDrivers(rowList); } public void handleEdit(ActionEvent e) { int row = table.getSelectedRow(); DriverInfo existing = driverTableModel.getDrivers().get(row); EditorPanel editor = new EditorPanel(jdbcRegistryTracker, existing.getDescription(), existing.getClassName(), existing.getDriverLocation()); DriverInfo info = editor.askUserForDriverInfo(); driverTableModel.replaceDriver(row, info); } }
36.901515
120
0.690618
08c16200b35e513c3e4eb63932c4e061c566dd4e
8,767
package org.python.types; public class DictKeys extends org.python.types.FrozenSet { static { org.python.types.Type.declarePythonType(DictKeys.class, "dict_keys", null, null); } @Override public org.python.Object __hash__() { throw new org.python.exceptions.AttributeError(this, "__hash__"); } @Override public boolean isHashable() { return false; } public DictKeys(org.python.types.Dict dict) { this.value = dict.value.keySet(); } /** * A utility method to create a set from an iterable object * <p> * Used by the __and__,__or__,__sub__ and __xor__ operations * obj must have a valid iterator */ private java.util.Set<org.python.Object> fromIter(org.python.Object obj) { java.util.Set<org.python.Object> generated = new java.util.HashSet<org.python.Object>(); org.python.Object iterator = org.Python.iter(obj); try { while (true) { org.python.Object next = iterator.__next__(); generated.add(next); } } catch (org.python.exceptions.StopIteration si) { } return generated; } @org.python.Method( __doc__ = "Return repr(self)." ) public org.python.types.Str __repr__() { java.lang.StringBuilder buffer = new java.lang.StringBuilder(this.typeName() + "(["); boolean first = true; for (org.python.Object item : this.value) { if (first) { first = false; } else { buffer.append(", "); } buffer.append(String.format("%s", item.__repr__())); } buffer.append("])"); return new org.python.types.Str(buffer.toString()); } @org.python.Method( __doc__ = "default object formatter" ) public org.python.types.Str __format__(org.python.Object other) { throw new org.python.exceptions.NotImplementedError(this.typeName() + ".__format__() has not been implemented."); } @org.python.Method( __doc__ = "__dir__() -> list\ndefault dir() implementation" ) public org.python.types.List __dir__() { throw new org.python.exceptions.NotImplementedError(this.typeName() + ".__dir__() has not been implemented."); } public boolean __setattr_null(java.lang.String name, org.python.Object value) { // Builtin types can't have attributes set on them. return false; } public boolean __delattr_null(java.lang.String name) { // Can't delete attributes of Builtin types return false; } @org.python.Method( __doc__ = "", args = {"index"} ) public org.python.Object __getitem__(org.python.Object index) { if (index instanceof org.python.types.Int || index instanceof org.python.types.Bool) { throw new org.python.exceptions.TypeError("'" + this.typeName() + "' object does not support indexing"); } else { throw new org.python.exceptions.TypeError("'" + this.typeName() + "' object is not subscriptable"); } } @org.python.Method( __doc__ = "", args = {"index", "value"} ) public void __setitem__(org.python.Object item, org.python.Object value) { throw new org.python.exceptions.TypeError("'" + this.typeName() + "' object does not support item assignment"); } @org.python.Method( __doc__ = "", args = {"index"} ) public void __delitem__(org.python.Object item) { throw new org.python.exceptions.TypeError("'" + this.typeName() + "' object doesn't support item deletion"); } @org.python.Method( __doc__ = "" ) public org.python.Object __invert__() { throw new org.python.exceptions.TypeError("bad operand type for unary ~: '" + this.typeName() + "'"); } @org.python.Method( __doc__ = "" ) public org.python.Object __pos__() { throw new org.python.exceptions.TypeError("bad operand type for unary +: '" + this.typeName() + "'"); } @org.python.Method( __doc__ = "" ) public org.python.Object __neg__() { throw new org.python.exceptions.TypeError("bad operand type for unary -: '" + this.typeName() + "'"); } @org.python.Method( __doc__ = "Return self&value." ) public org.python.types.Set __and__(org.python.Object other) { java.util.Set<org.python.Object> generated = this.fromIter(other); generated.retainAll(this.value); return new org.python.types.Set(generated); } @org.python.Method( __doc__ = "Return self|value." ) public org.python.types.Set __or__(org.python.Object other) { java.util.Set<org.python.Object> generated = this.fromIter(other); generated.addAll(this.value); return new org.python.types.Set(generated); } @org.python.Method( __doc__ = "Return self-value." ) public org.python.types.Set __sub__(org.python.Object other) { java.util.Set<org.python.Object> set1 = new java.util.HashSet<org.python.Object>(this.value); java.util.Set<org.python.Object> set2 = this.fromIter(other); set1.removeAll(set2); return new org.python.types.Set(set1); } @org.python.Method( __doc__ = "Return self^value." ) public org.python.types.Set __xor__(org.python.Object other) { java.util.Set<org.python.Object> s1 = this.fromIter(other); java.util.Set<org.python.Object> sym_dif = new java.util.HashSet<org.python.Object>(s1); sym_dif.addAll(this.value); java.util.Set<org.python.Object> tmp = new java.util.HashSet<org.python.Object>(s1); tmp.retainAll(this.value); sym_dif.removeAll(tmp); return new org.python.types.Set(sym_dif); } @org.python.Method( __doc__ = "Return value&self." ) public org.python.types.Set __rand__(org.python.Object other) { return this.__and__(other); } @org.python.Method( __doc__ = "Return value|self." ) public org.python.types.Set __ror__(org.python.Object other) { return this.__or__(other); } @org.python.Method( __doc__ = "Return value^self." ) public org.python.types.Set __rxor__(org.python.Object other) { return this.__xor__(other); } @org.python.Method( __doc__ = "Return value-self." ) public org.python.types.Set __rsub__(org.python.Object other) { java.util.Set<org.python.Object> generated = this.fromIter(other); generated.removeAll(this.value); return new org.python.types.Set(generated); } @org.python.Method( __doc__ = "Return True if the set has no elements in common with other. Sets are\n" + "disjoint if and only if their intersection is the empty set.", args = {"other"} ) public org.python.Object isdisjoint(org.python.Object other) { java.util.Set<org.python.Object> generated = new java.util.HashSet<org.python.Object>(); org.python.Object iterator = org.Python.iter(other); try { while (true) { org.python.Object next = iterator.__next__(); generated.add(next); } } catch (org.python.exceptions.StopIteration si) { } generated.retainAll(this.value); return org.python.types.Bool.getBool(generated.size() > 0); } /** * The following methods are not present in Python's dict_keys but are present in DictKeys (inherited from FrozenSet) * <p> * Hence, throw an AttributeError every time any of these methods is called */ public org.python.Object issubset(org.python.Object other) { throw new org.python.exceptions.AttributeError(this, "issubset"); } public org.python.Object issuperset(org.python.Object other) { throw new org.python.exceptions.AttributeError(this, "issuperset"); } public org.python.Object union(org.python.types.Tuple others) { throw new org.python.exceptions.AttributeError(this, "union"); } public org.python.Object intersection(org.python.types.Tuple others) { throw new org.python.exceptions.AttributeError(this, "intersection"); } public org.python.Object difference(org.python.types.Tuple others) { throw new org.python.exceptions.AttributeError(this, "difference"); } public org.python.Object symmetric_difference(org.python.Object other) { throw new org.python.exceptions.AttributeError(this, "issuperset"); } }
35.068
121
0.617315
bc573c61ce146ce2c1b3561e767eebc02c62091e
654
package com.websocket.user; /** * Date: 2020/9/8 Ahming */ public class OnlineWsUserConstants { private OnlineWsUserConstants(){} /** * 用户信息 hash 键模板. * %s: 频道id * %d: 用户uid */ public static final String USER_HASH_KEY_PATTERN = "wstc:u:h:%s:uid:%d"; /** * 在线用户 uid set 键前缀. */ public static final String USERS_UID_SET_KEY_PREFIX = "wstc:u:s:"; /** * 在线用户 uid set 键全部匹配. */ public static final String USERS_UID_SET_KEY_ALL_PATTERN = "wstc:u:s:*"; /** * 在线用户 uid set 键模板. * %s: 频道id */ public static final String USERS_UID_SET_KEY_PATTERN = "wstc:u:s:%s"; }
20.4375
76
0.593272
8ca93482cbc42b1c8f798214e5a1717f6e1f3e89
15,159
/* * Copyright 2018 Pivotal, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.clouddriver.cloudfoundry.client; import com.google.api.client.repackaged.com.google.common.annotations.VisibleForTesting; import com.netflix.spinnaker.clouddriver.cloudfoundry.client.api.ServiceInstanceService; import com.netflix.spinnaker.clouddriver.cloudfoundry.client.model.ServiceInstanceResponse; import com.netflix.spinnaker.clouddriver.cloudfoundry.client.model.v2.*; import com.netflix.spinnaker.clouddriver.cloudfoundry.model.*; import lombok.RequiredArgsConstructor; import javax.annotation.Nullable; import java.util.*; import java.util.function.*; import static com.netflix.spinnaker.clouddriver.cloudfoundry.client.CloudFoundryClientUtils.collectPageResources; import static com.netflix.spinnaker.clouddriver.cloudfoundry.client.CloudFoundryClientUtils.safelyCall; import static com.netflix.spinnaker.clouddriver.cloudfoundry.client.model.ErrorDescription.Code.SERVICE_ALREADY_EXISTS; import static com.netflix.spinnaker.clouddriver.cloudfoundry.client.model.v2.LastOperation.State.*; import static com.netflix.spinnaker.clouddriver.cloudfoundry.client.model.v2.LastOperation.Type.CREATE; import static com.netflix.spinnaker.clouddriver.cloudfoundry.client.model.v2.LastOperation.Type.DELETE; import static com.netflix.spinnaker.clouddriver.cloudfoundry.client.model.v2.LastOperation.Type.UPDATE; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; import static org.apache.commons.lang3.StringUtils.isBlank; @RequiredArgsConstructor public class ServiceInstances { private final ServiceInstanceService api; private final Organizations orgs; private final Spaces spaces; public void createServiceBindingsByName(CloudFoundryServerGroup cloudFoundryServerGroup, @Nullable List<String> serviceNames) throws CloudFoundryApiException { if (serviceNames != null && !serviceNames.isEmpty()) { String spaceGuid = cloudFoundryServerGroup.getSpace().getId(); List<String> serviceInstanceQuery = new ArrayList<>(); serviceInstanceQuery.add("name IN " + String.join(",", serviceNames)); List<String> userProvidedServiceInstanceQuery = new ArrayList<>(); userProvidedServiceInstanceQuery.add("name IN " + String.join(",", serviceNames)); userProvidedServiceInstanceQuery.add("organization_guid:" + cloudFoundryServerGroup.getSpace().getOrganization().getId()); userProvidedServiceInstanceQuery.add("space_guid:" + spaceGuid); List<Resource<? extends AbstractServiceInstance>> serviceInstances = new ArrayList<>(); serviceInstances.addAll(collectPageResources("service instances", pg -> api.all(pg, spaceGuid, serviceInstanceQuery))); serviceInstances.addAll(collectPageResources("service instances", pg -> api.allUserProvided(pg, userProvidedServiceInstanceQuery))); if (serviceInstances.size() != serviceNames.size()) { throw new CloudFoundryApiException("Number of service instances does not match the number of service names"); } for (Resource<? extends AbstractServiceInstance> serviceInstance : serviceInstances) { api.createServiceBinding(new CreateServiceBinding( serviceInstance.getMetadata().getGuid(), cloudFoundryServerGroup.getId() )); } } } private Resource<Service> findServiceByServiceName(String serviceName) { List<Resource<Service>> services = collectPageResources("services by name", pg -> api.findService(pg, singletonList("label:" + serviceName))); return Optional.ofNullable(services.get(0)).orElse(null); } private List<CloudFoundryServicePlan> findAllServicePlansByServiceName(String serviceName) { Resource<Service> service = findServiceByServiceName(serviceName); List<Resource<ServicePlan>> services = collectPageResources("service plans by id", pg -> api.findServicePlans(pg, singletonList("service_guid:" + service.getMetadata().getGuid()))); return services.stream() .map(resource -> CloudFoundryServicePlan.builder() .name(resource.getEntity().getName()) .id(resource.getMetadata().getGuid()) .build()) .collect(toList()); } public List<CloudFoundryService> findAllServicesByRegion(String region) { CloudFoundrySpace space = getSpaceByRegionName(region); if (space == null) { return Collections.emptyList(); } List<Resource<Service>> services = collectPageResources("all service", pg -> api.findServiceBySpaceId(space.getId(), pg, null)); return services.stream() .map(serviceResource -> CloudFoundryService.builder() .name(serviceResource.getEntity().getLabel()) .servicePlans(findAllServicePlansByServiceName(serviceResource.getEntity().getLabel())) .build()) .collect(toList()); } private CloudFoundrySpace getSpaceByRegionName(String region) { CloudFoundrySpace space = CloudFoundrySpace.fromRegion(region); Optional<CloudFoundryOrganization> org = orgs.findByName(space.getOrganization().getName()); return org.map(cfOrg -> spaces.findByName(cfOrg.getId(), space.getName())).orElse(null); } @Nullable public CloudFoundryServiceInstance getServiceInstance(String region, @Nullable String serviceInstanceName) throws CloudFoundryApiException { CloudFoundrySpace space = getSpaceByRegionName(region); Supplier<CloudFoundryServiceInstance> si = () -> Optional.ofNullable(getServiceInstance(space, serviceInstanceName)) .map(Resource::getEntity) .map(e -> CloudFoundryServiceInstance.builder() .serviceInstanceName(serviceInstanceName) .status(e.getLastOperation().getState().toString()) .build() ) .orElse(null); Supplier<CloudFoundryServiceInstance> up = () -> Optional.ofNullable(getUserProvidedServiceInstance(space, serviceInstanceName)) .map(Resource::getEntity) .map(e -> CloudFoundryServiceInstance.builder() .serviceInstanceName(serviceInstanceName) .status(SUCCEEDED.toString()) .build() ) .orElse(null); return Optional.ofNullable(si.get()).orElseGet(up); } @Nullable @VisibleForTesting Resource<ServiceInstance> getServiceInstance(CloudFoundrySpace space, @Nullable String serviceInstanceName) throws CloudFoundryApiException { if (isBlank(serviceInstanceName)) { throw new CloudFoundryApiException("Please specify a name for the service being sought"); } List<String> queryParams = singletonList("name IN " + serviceInstanceName); List<Resource<ServiceInstance>> serviceInstances = collectPageResources("service instances by space and name", pg -> api.all(pg, space.getId(), queryParams)); return getValidServiceInstance(space, serviceInstanceName, serviceInstances); } @Nullable private Resource<UserProvidedServiceInstance> getUserProvidedServiceInstance(CloudFoundrySpace space, @Nullable String serviceInstanceName) throws CloudFoundryApiException { if (isBlank(serviceInstanceName)) { throw new CloudFoundryApiException("Please specify a name for the service being sought"); } List<String> queryParams = new ArrayList<>(); queryParams.add("name IN " + serviceInstanceName); queryParams.add("space_guid:" + space.getId()); queryParams.add("organization_guid:" + space.getOrganization().getId()); List<Resource<UserProvidedServiceInstance>> services = collectPageResources("service instances by space and name", pg -> api.allUserProvided(pg, queryParams)); return getValidServiceInstance(space, serviceInstanceName, services); } private <T> Resource<T> getValidServiceInstance(CloudFoundrySpace space, @Nullable String serviceInstanceName, List<Resource<T>> serviceInstances) { if (serviceInstances.isEmpty()) { return null; } if (serviceInstances.size() > 1) { throw new CloudFoundryApiException(serviceInstances.size() + " service instances found with name '" + serviceInstanceName + "' in space " + space.getName() + ", but expected only 1"); } return serviceInstances.get(0); } public ServiceInstanceResponse destroyServiceInstance(CloudFoundrySpace space, String serviceInstanceName) throws CloudFoundryApiException { Resource<ServiceInstance> serviceInstance = getServiceInstance(space, serviceInstanceName); if (serviceInstance != null) { String serviceInstanceId = serviceInstance.getMetadata().getGuid(); destroyServiceInstance( pg -> api.getBindingsForServiceInstance(serviceInstanceId, pg, null), () -> api.destroyServiceInstance(serviceInstanceId)); return new ServiceInstanceResponse() .setServiceInstanceId(serviceInstanceId) .setServiceInstanceName(serviceInstanceName) .setType(DELETE) .setState(IN_PROGRESS); } else { Resource<UserProvidedServiceInstance> userProvidedServiceInstance = getUserProvidedServiceInstance(space, serviceInstanceName); if (userProvidedServiceInstance == null) { throw new CloudFoundryApiException("No service instances with name '" + serviceInstanceName + "' found in space " + space.getName()); } String userProvidedServiceInstanceId = userProvidedServiceInstance.getMetadata().getGuid(); destroyServiceInstance( pg -> api.getBindingsForUserProvidedServiceInstance(userProvidedServiceInstanceId, pg, null), () -> api.destroyUserProvidedServiceInstance(userProvidedServiceInstanceId)); return new ServiceInstanceResponse() .setServiceInstanceId(userProvidedServiceInstanceId) .setServiceInstanceName(serviceInstanceName) .setType(DELETE) .setState(NOT_FOUND); } } private void destroyServiceInstance(Function<Integer, Page<ServiceBinding>> fetchPage, Runnable delete) { List<Resource<ServiceBinding>> serviceBindings = collectPageResources("service bindings", fetchPage); if (!serviceBindings.isEmpty()) { throw new CloudFoundryApiException("Unable to destroy service instance while " + serviceBindings.size() + " service binding(s) exist"); } safelyCall(delete::run); } public ServiceInstanceResponse createServiceInstance( String newServiceInstanceName, String serviceName, String servicePlanName, Set<String> tags, Map<String, Object> parameters, CloudFoundrySpace space) throws CloudFoundryApiException, ResourceNotFoundException { List<CloudFoundryServicePlan> cloudFoundryServicePlans = findAllServicePlansByServiceName(serviceName); if (cloudFoundryServicePlans.isEmpty()) { throw new ResourceNotFoundException("No plans available for service name '" + serviceName + "'"); } String servicePlanId = cloudFoundryServicePlans.stream() .filter(plan -> plan.getName().equals(servicePlanName)) .findAny() .orElseThrow(() -> new ResourceNotFoundException("Service '" + serviceName + "' does not have a matching plan '" + servicePlanName + "'")) .getId(); CreateServiceInstance command = new CreateServiceInstance(); command.setName(newServiceInstanceName); command.setSpaceGuid(space.getId()); command.setServicePlanGuid(servicePlanId); command.setTags(tags); command.setParameters(parameters); ServiceInstanceResponse response = createServiceInstance( command, api::createServiceInstance, api::updateServiceInstance, c -> getServiceInstance(space, c.getName()), (c, r) -> { if (!r.getEntity().getServicePlanGuid().equals(c.getServicePlanGuid())) { throw new CloudFoundryApiException("A service with name '" + c.getName() + "' exists but has a different plan"); } }, space ); response.setState(IN_PROGRESS); return response; } public ServiceInstanceResponse createUserProvidedServiceInstance( String newUserProvidedServiceInstanceName, String syslogDrainUrl, Set<String> tags, Map<String, Object> credentials, String routeServiceUrl, CloudFoundrySpace space) throws CloudFoundryApiException, ResourceNotFoundException { CreateUserProvidedServiceInstance command = new CreateUserProvidedServiceInstance(); command.setName(newUserProvidedServiceInstanceName); command.setSyslogDrainUrl(syslogDrainUrl); command.setTags(tags); command.setCredentials(credentials); command.setRouteServiceUrl(routeServiceUrl); command.setSpaceGuid(space.getId()); ServiceInstanceResponse response = createServiceInstance( command, api::createUserProvidedServiceInstance, api::updateUserProvidedServiceInstance, c -> getUserProvidedServiceInstance(space, c.getName()), (c, r) -> { }, space ); response.setState(SUCCEEDED); return response; } private <T extends AbstractCreateServiceInstance, S extends AbstractServiceInstance> ServiceInstanceResponse createServiceInstance(T command, Function<T, Resource<S>> create, BiFunction<String, T, Resource<S>> update, Function<T, Resource<S>> getServiceInstance, BiConsumer<T, Resource<S>> updateValidation, CloudFoundrySpace space) { String serviceInstanceId; LastOperation.Type operationType; try { serviceInstanceId = safelyCall(() -> create.apply(command)).map(res -> res.getMetadata().getGuid()) .orElseThrow(() -> new CloudFoundryApiException("service instance '" + command.getName() + "' not found")); operationType = CREATE; } catch (CloudFoundryApiException cfe) { if (cfe.getErrorCode() == SERVICE_ALREADY_EXISTS) { Resource<S> serviceInstance = getServiceInstance.apply(command); if (serviceInstance == null) { throw new CloudFoundryApiException("No service instances with name '" + command.getName() + "' found in space " + space.getName()); } updateValidation.accept(command, serviceInstance); serviceInstanceId = safelyCall(() -> update.apply(serviceInstance.getMetadata().getGuid(), command)) .map(res -> res.getMetadata().getGuid()) .orElseThrow(() -> new CloudFoundryApiException("Service instance '" + command.getName() + "' not found")); operationType = UPDATE; } else { throw cfe; } } return new ServiceInstanceResponse() .setServiceInstanceId(serviceInstanceId) .setServiceInstanceName(command.getName()) .setType(operationType); } }
46.357798
175
0.734679
ced39c7dfc7c6bb1c9cee9022d0ac5fb99fdf78f
2,747
package ubiquigame.games.curve_fever; import java.util.ArrayList; import java.util.List; import java.util.Random; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.glutils.FrameBuffer; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.ScreenUtils; import ubiquigame.common.Player; import ubiquigame.common.constants.PlayerIdentifier; public class Board { private int culledBoarder = 100; private Random rng = new Random(); List<Puk> puks = new ArrayList<>(); private SpriteBatch spriteBatch = new SpriteBatch(); private Vector2 size = new Vector2(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); private FrameBuffer frameBuffer; private TextureRegion bufferRegion; private Pixmap pixMapLastFrame; public Board(Player[] players) { for (int i = 0; i < 1; i++) { Color gdxColor = Utils.getGdxColor(PlayerIdentifier.values()[i].color); puks.add(new Puk(players[i], this, new Vector2(size).scl(rng.nextFloat(), rng.nextFloat()), gdxColor)); } initFrameBuffer(); } public void update(float delta) { for (Puk puk : puks) { puk.update(delta); } } public void render(float delta) { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); frameBuffer.begin(); for (Puk puk : puks) { puk.render(delta); } if (pixMapLastFrame != null) { pixMapLastFrame.dispose(); } frameBuffer.end(); frameBuffer.begin(); spriteBatch.begin(); spriteBatch.draw(bufferRegion, frameBuffer.getWidth() - culledBoarder, 0,culledBoarder, frameBuffer.getHeight() ); spriteBatch.end(); pixMapLastFrame = ScreenUtils.getFrameBufferPixmap(0, 0, frameBuffer.getWidth(), frameBuffer.getHeight()); frameBuffer.end(); spriteBatch.begin(); spriteBatch.draw(bufferRegion, -culledBoarder, -culledBoarder, bufferRegion.getRegionWidth() - culledBoarder, bufferRegion.getRegionHeight() - culledBoarder); spriteBatch.end(); } private void initFrameBuffer() { if (frameBuffer == null) { frameBuffer = new FrameBuffer(Format.RGBA8888, (int) size.x + culledBoarder * 2, (int) size.y + culledBoarder * 2, false); bufferRegion = new TextureRegion(frameBuffer.getColorBufferTexture()); } } public Vector2 getSize() { return size; } public FrameBuffer getBackBuffer() { return frameBuffer; } public Pixmap getPixMapLastFrame() { return pixMapLastFrame; } public TextureRegion getBufferRegion() { return bufferRegion; } public SpriteBatch getSpriteBatch() { return spriteBatch; } }
26.931373
116
0.740808
2d6693d058c0db81d511487b3ab3edb015ca6784
4,222
/* * Copyright 2015-2016 Smithsonian Institution. * * 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/ * * This software and accompanying documentation is supplied without * warranty of any kind. The copyright holder and the Smithsonian Institution: * (1) expressly disclaim any warranties, express or implied, including but not * limited to any implied warranties of merchantability, fitness for a * particular purpose, title or non-infringement; (2) do not assume any legal * liability or responsibility for the accuracy, completeness, or usefulness of * the software; (3) do not represent that use of the software would not * infringe privately owned rights; (4) do not warrant that the software * is error-free or will be maintained, supported, updated or enhanced; * (5) will not be liable for any indirect, incidental, consequential special * or punitive damages of any kind or nature, including but not limited to lost * profits or loss of data, on any basis arising from contract, tort or * otherwise, even if any of the parties has been warned of the possibility of * such loss or damage. * * This distribution includes several third-party libraries, each with their own * license terms. For a complete copy of all copyright and license terms, including * those of third-party libraries, please see the product release notes. */ package edu.si.sidora.excel2tabular; import static edu.si.sidora.excel2tabular.UnitTestUtilities.iterateOver; import static org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BLANK; import static org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class TabularRowTest { private static final String TEST_STRING_VALUE = "Some string value."; private static final String TEST_STRING_PRINTED_VALUE = "\"" + TEST_STRING_VALUE + "\""; @Mock private Row mockRow; @Mock private Cell mockEmptyCell, stringCell; @Test public void testEmptyRow() { when(mockRow.getLastCellNum()).thenReturn((short) 0); assertEquals("", new TabularRow(mockRow).toString()); } @Test public void testOtherKindOfEmptyRow() { when(mockRow.iterator()).thenAnswer(iterateOver()); assertEquals("", new TabularRow(mockRow).toString()); } @Test public void testSingleEmptyCell() { when(mockRow.getLastCellNum()).thenReturn((short) 1); when(mockEmptyCell.getCellType()).thenReturn(CELL_TYPE_BLANK); when(mockRow.getCell(0)).thenReturn(mockEmptyCell); assertEquals("", new TabularRow(mockRow).toString()); } public void testSingleNullCell() { when(mockRow.getLastCellNum()).thenReturn((short) 1); when(mockRow.getCell(0)).thenReturn(null); assertEquals("", new TabularRow(mockRow).toString()); } @Test public void testSingleStringCell() { when(stringCell.getStringCellValue()).thenReturn(TEST_STRING_VALUE); when(stringCell.getCellType()).thenReturn(CELL_TYPE_STRING); when(mockRow.getLastCellNum()).thenReturn((short) 1); when(mockRow.getCell(0)).thenReturn(stringCell); assertEquals(TEST_STRING_PRINTED_VALUE, new TabularRow(mockRow).toString()); } @Test public void testTwoStringCells() { when(stringCell.getStringCellValue()).thenReturn(TEST_STRING_VALUE); when(stringCell.getCellType()).thenReturn(CELL_TYPE_STRING); when(mockRow.getLastCellNum()).thenReturn((short) 2); when(mockRow.getCell(0)).thenReturn(stringCell); when(mockRow.getCell(1)).thenReturn(stringCell); final String testValue = TEST_STRING_PRINTED_VALUE + "," + TEST_STRING_PRINTED_VALUE; assertEquals(testValue, new TabularRow(mockRow).toString()); } }
41.392157
93
0.731881
eda6c3492b13f4f001401836b000829f262a28f8
17,464
package com.checkmarx.intellij.tool.window; import com.checkmarx.intellij.*; import com.checkmarx.intellij.commands.results.ResultGetState; import com.checkmarx.intellij.commands.results.Results; import com.checkmarx.intellij.components.TreeUtils; import com.checkmarx.intellij.project.ProjectResultsService; import com.checkmarx.intellij.settings.SettingsListener; import com.checkmarx.intellij.settings.global.GlobalSettingsComponent; import com.checkmarx.intellij.settings.global.GlobalSettingsConfigurable; import com.checkmarx.intellij.settings.global.GlobalSettingsState; import com.checkmarx.intellij.tool.window.actions.filter.FilterBaseAction; import com.checkmarx.intellij.tool.window.actions.selection.ResetSelectionAction; import com.checkmarx.intellij.tool.window.actions.selection.RootGroup; import com.checkmarx.intellij.tool.window.results.tree.ResultsTreeFactory; import com.checkmarx.intellij.tool.window.results.tree.nodes.ResultNode; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.ActionGroup; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.ActionToolbar; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.SimpleToolWindowPanel; import com.intellij.openapi.ui.Splitter; import com.intellij.ui.OnePixelSplitter; import com.intellij.ui.SearchTextField; import com.intellij.ui.components.JBLabel; import com.intellij.ui.treeStructure.Tree; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.util.messages.Topic; import com.intellij.util.ui.JBUI; import lombok.SneakyThrows; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.*; import java.util.List; import java.util.regex.Pattern; import static com.intellij.util.ui.JBUI.Panels.simplePanel; /** * Handles drawing the checkmarx tool window. * UI and internal state should only be manipulated in the single threaded context of the swing EDT, through * {@link ApplicationManager#getApplication()} and * {@link com.intellij.openapi.application.Application#invokeLater(Runnable)}. * Any async calls on other threads should be effectively static or this class will need synchronization! */ public class CxToolWindowPanel extends SimpleToolWindowPanel implements Disposable { private static final Logger LOGGER = Utils.getLogger(CxToolWindowPanel.class); // pattern for validating UUIDs provided in the scan id field private static final Pattern uuidPattern = Pattern.compile( "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"); // UI state // divides the main panel in tree|details sections private final OnePixelSplitter treeDetailsSplitter = new OnePixelSplitter(false, 0.3f); // divides the tree section in scanIdField|resultsTree sections private final OnePixelSplitter scanTreeSplitter = new OnePixelSplitter(true, 0.1f); // field to input a scan id private SearchTextField scanIdField = new SearchTextField(); // Internal state private final List<GroupBy> groupByList = new ArrayList<>(GroupBy.DEFAULT_GROUP_BY); private ResultGetState currentState = new ResultGetState(); private Tree currentTree = null; private boolean getResultsInProgress = false; private RootGroup rootGroup; private final Project project; // service for indexing current results private final ProjectResultsService projectResultsService; /** * Creates the tool window with the settings panel or the results panel * * @param project current project */ public CxToolWindowPanel(@NotNull Project project) { super(false, true); this.project = project; this.projectResultsService = project.getService(ProjectResultsService.class); Runnable r = () -> { if (new GlobalSettingsComponent().isValid()) { drawMainPanel(); } else { drawAuthPanel(); projectResultsService.indexResults(project, Results.emptyResults); } }; ApplicationManager.getApplication() .getMessageBus() .connect(this) .subscribe(SettingsListener.SETTINGS_APPLIED, r::run); ApplicationManager.getApplication().getMessageBus().connect(this).subscribe(FilterBaseAction.FILTER_CHANGED, this::changeFilter); r.run(); } /** * Creates the main panel UI for results. */ private void drawMainPanel() { removeAll(); ActionToolbar mainToolbar = getActionToolbar(); ResetSelectionAction resetSelectionAction = (ResetSelectionAction) mainToolbar.getActions() .stream() .filter(a -> a instanceof ResetSelectionAction) .findFirst() .orElse(null); // root group for project - branch - scan selection rootGroup = new RootGroup(project, resetSelectionAction); // listener to get results when enter is pressed on scan id field scanIdField = new SearchTextField(); scanIdField.addKeyboardListener(new OnEnterGetResults()); // split vertical the scan id field and the panel for results tree scanTreeSplitter.setResizeEnabled(false); scanTreeSplitter.setDividerPositionStrategy(Splitter.DividerPositionStrategy.KEEP_FIRST_SIZE); scanTreeSplitter.setLackOfSpaceStrategy(Splitter.LackOfSpaceStrategy.HONOR_THE_FIRST_MIN_SIZE); scanTreeSplitter.setFirstComponent(simplePanel(scanIdField)); scanTreeSplitter.setSecondComponent(simplePanel()); // split horizontal the scan id field/results tree and the result details panel treeDetailsSplitter.setFirstComponent(scanTreeSplitter); treeDetailsSplitter.setSecondComponent(simplePanel()); // set content and main toolbar SimpleToolWindowPanel treePanel = new SimpleToolWindowPanel(true, true); treePanel.setToolbar(getActionToolbar(rootGroup, true).getComponent()); treePanel.setContent(treeDetailsSplitter); setContent(treePanel); setToolbar(mainToolbar.getComponent()); } /** * Draw a panel with logo and a button to settings, when settings are invalid */ private void drawAuthPanel() { removeAll(); JPanel wrapper = new JPanel(new GridBagLayout()); JPanel panel = new JPanel(new GridLayoutManager(2, 1, JBUI.emptyInsets(), -1, -1)); GridConstraints constraints = new GridConstraints(); constraints.setRow(0); panel.add(new JBLabel(CxIcons.CHECKMARX_80), constraints); JButton comp = new JButton(Bundle.message(Resource.OPEN_SETTINGS_BUTTON)); comp.addActionListener(e -> ShowSettingsUtil.getInstance() .showSettingsDialog(project, GlobalSettingsConfigurable.class)); constraints = new GridConstraints(); constraints.setRow(1); panel.add(comp, constraints); wrapper.add(panel); setContent(wrapper); } @Override public void dispose() { } /** * Trigger drawing the results by a selection * * @param scanId selected scan id */ public void selectScan(String scanId) { if (Utils.validThread()) { triggerDrawResultsTree(scanId, false); } } /** * Expand all rows in the results tree. * Can only be done in the context of the Swing EDT and when a get for results is not in progress. */ public void expandAll() { if (Utils.validThread() && !getResultsInProgress && currentTree != null) { for (int i = 0; i < currentTree.getRowCount(); i++) { currentTree.expandRow(i); } } } /** * Collapse all rows in the results tree. * Can only be done in the context of the Swing EDT and when a get for results is not in progress. */ public void collapseAll() { if (Utils.validThread() && !getResultsInProgress && currentTree != null) { for (int i = 0; i < currentTree.getRowCount(); i++) { currentTree.collapseRow(i); } treeDetailsSplitter.setSecondComponent(simplePanel()); } } /** * Add or remove a groupBy to the list for applying * * @param groupBy groupBy * @param selected whether it is selected (add) or deselected (remove) */ public void changeGroupBy(GroupBy groupBy, boolean selected) { if (!Utils.validThread()) { return; } if (selected) { groupByList.add(groupBy); groupByList.sort(Enum::compareTo); } else { groupByList.remove(groupBy); } drawTree(); } public void changeFilter() { if (!Utils.validThread()) { return; } drawTree(); } /** * Refresh and redraw the panel. * Getting and setting the same content forces swing to redraw without rebuilding all the objects. */ public void refreshPanel() { if (!Utils.validThread()) { return; } Optional.ofNullable(getContent()).ifPresent(this::setContent); } /** * Completely reset the main panel state */ public void resetPanel() { if (!Utils.validThread()) { return; } rootGroup.setEnabled(false); currentState = new ResultGetState(); projectResultsService.indexResults(project, Results.emptyResults); scanIdField.setText(""); scanTreeSplitter.setSecondComponent(simplePanel()); treeDetailsSplitter.setSecondComponent(simplePanel()); rootGroup.reset(); } /** * Trigger drawing results for a given scan id. * Validates the following before triggering: * - The thread is the Swing EDT thread; * - An async call to get results is not in progress; * - the scan id has changed * - the scan id is a valid UUID or blank (latest) * * @param scanIdValue scan id to get results */ private void triggerDrawResultsTree(String scanIdValue, boolean overrideSelections) { if (!Utils.validThread() || getResultsInProgress || Objects.equals(scanIdValue, currentState.getScanIdFieldValue())) { return; } currentState = new ResultGetState(); if (!StringUtils.isBlank(scanIdValue) && !uuidPattern.matcher(scanIdValue).matches()) { currentState.setMessage(Bundle.message(Resource.INVALID_SCAN_ID)); updateDisplay(); return; } // disable selections while in progress rootGroup.setEnabled(false); LOGGER.info("Getting results for scan " + scanIdValue); getResultsInProgress = true; currentState.setMessage(Bundle.message(Resource.GETTING_RESULTS)); updateDisplay(); // updates to variables wrapped in an invokeLater call so the Swing EDT performs the update // in a single threaded manner Results.getResults(scanIdValue) .thenAcceptAsync((newState) -> ApplicationManager.getApplication().invokeLater(() -> { currentState = newState; if (overrideSelections) { // don't enable rootGroup immediately, override is async and will enable when done rootGroup.override(currentState.getScanId()); } else { // re-enable selections rootGroup.setEnabled(true); } getResultsInProgress = false; updateDisplay(); })); } /** * Update the display with the current state */ private void updateDisplay() { if (!Utils.validThread()) { return; } projectResultsService.indexResults(project, currentState.getResultOutput()); if (currentState.getMessage() != null) { LOGGER.info(String.format("Cannot show results: %s", currentState.getMessage())); scanTreeSplitter.setSecondComponent(TreeUtils.labelTreePanel(currentState.getMessage())); } else { LOGGER.info("Updating state for scan " + currentState.getScanId()); drawTree(); } } /** * Draw the results tree */ private void drawTree() { if (!Utils.validThread() || currentState.getScanId() == null) { return; } currentTree = ResultsTreeFactory.buildResultsTree(currentState.getScanId(), currentState.getResultOutput(), project, groupByList, GlobalSettingsState.getInstance().getFilters(), currentState.isLatest()); currentTree.addTreeSelectionListener(new OnSelectShowDetail()); scanTreeSplitter.setSecondComponent(TreeUtils.treePanel(currentTree)); } /** * {@link TreeSelectionListener} to show details of a selected result on the right component of the tool window. */ private class OnSelectShowDetail implements TreeSelectionListener { @SneakyThrows @Override public void valueChanged(TreeSelectionEvent e) { TreePath path = e.getNewLeadSelectionPath(); if (path != null) { Object selected = path.getLastPathComponent(); Tree tree = (Tree) e.getSource(); if (tree.getModel().isLeaf(selected) && selected instanceof ResultNode) { ResultNode resultNode = (ResultNode) selected; treeDetailsSplitter.setSecondComponent(resultNode.buildResultPanel(() -> { ApplicationManager.getApplication().invokeLater(() -> { drawTree(); DefaultMutableTreeNode root = (DefaultMutableTreeNode) currentTree.getModel().getRoot(); Enumeration<TreeNode> enumeration = root.depthFirstEnumeration(); while (enumeration.hasMoreElements()) { TreeNode treeNode = enumeration.nextElement(); if (tree.getModel().isLeaf(treeNode) && treeNode instanceof ResultNode) { ResultNode node = (ResultNode) treeNode; if (node.getResult() == resultNode.getResult()) { currentTree.expandPath(new TreePath(node.getPath()).getParentPath()); break; } } } valueChanged(new TreeSelectionEvent(currentTree, path, true, e.getOldLeadSelectionPath(), e.getNewLeadSelectionPath())); }); }, () -> refreshPanel())); } } } } @NotNull private static ActionToolbar getActionToolbar() { ActionGroup group = (ActionGroup) ActionManager.getInstance().getAction(Constants.ACTION_GROUP_ID); return getActionToolbar(group, false); } @NotNull private static ActionToolbar getActionToolbar(ActionGroup group, boolean horizontal) { ActionToolbar toolbar = ActionManager.getInstance() .createActionToolbar(Constants.TOOL_WINDOW_ID, group, horizontal); toolbar.setTargetComponent(toolbar.getComponent()); return toolbar; } /** * {@link KeyListener} to get results for the scan id in scanIdField on {@link KeyEvent#VK_ENTER}. */ private class OnEnterGetResults implements KeyListener { @Override public void keyTyped(KeyEvent e) { // do nothing } @Override public void keyPressed(KeyEvent e) { // do nothing } @Override public void keyReleased(KeyEvent e) { if (e.getExtendedKeyCode() == KeyEvent.VK_ENTER) { triggerDrawResultsTree(scanIdField.getText().trim(), true); } } } public interface CxRefreshHandler { void refresh(); } }
39.069351
148
0.624427
0f1b535f39ca8cf20ac1d18833e436dcbe8c04d4
4,210
package com.weique.commonres.utils.commonutils; import com.jess.arms.integration.IRepositoryManager; import com.jess.arms.mvp.IView; import com.weique.commonres.base.BaseResponse; import com.weique.commonres.base.commonbean.QuestionBean; import com.weique.commonres.base.commonbean.UploadFileRsponseBean; import com.weique.commonres.constans.Constants; import com.weique.commonres.service.CommonRequestService; import com.weique.commonres.utils.globalutils.NetworkUtils; import com.weique.commonres.utils.globalutils.SignUtil; import com.weique.commonres.utils.globalutils.UserInfoUtils; import java.io.File; import java.util.List; import java.util.Map; import io.reactivex.Observable; import io.reactivex.annotations.Nullable; import me.jessyan.rxerrorhandler.core.RxErrorHandler; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; /** * @author GK * @description: 所有公共网络请求写在这里 * @date :2020/8/16 10:26 * !!! 公共请求的 返回对象放到 com.weique.commonres.base.commonbean 文件夹下 */ public class CommonNetworkRequest { /**上传文件 * @param mErrorHandler mErrorHandler 错误回调 * @param mRootView mRootView * @param mRepositoryManager mRepositoryManager * @param handle handle */ public static void upLoadFile( List<String> compressPaths, RxErrorHandler mErrorHandler, IView mRootView, IRepositoryManager mRepositoryManager, @Nullable NetworkUtils.ProgressMonitorHandle<List<UploadFileRsponseBean>> handle) { try { MultipartBody.Builder builder = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart(Constants.USER_ID, StringUtil.setText(UserInfoUtils.getInstance().getUserInfo().getUid())); for (String s : compressPaths) { File file = new File(s); String parse = ""; if (s.endsWith(Constants.PNG)) { parse = "image/png"; } else if (s.endsWith(Constants.JPG)) { parse = "image/JPG"; } else if (s.endsWith(Constants.JPEG)) { parse = "image/jpeg"; } else { parse = "application/octet-stream"; } RequestBody requestFile = RequestBody.create(MediaType.parse(parse), file); builder.addFormDataPart("file", file.getName(), requestFile); } Observable<BaseResponse<List<UploadFileRsponseBean>>> baseBeanObservable = mRepositoryManager. obtainRetrofitService(CommonRequestService.class). uploadFile(builder.build()); NetworkUtils.commonGetNetworkData(baseBeanObservable, mErrorHandler, mRootView, handle,true); } catch (Exception e) { e.printStackTrace(); } } /** * @param map 公共请求 * @param path 动态的url * @param mErrorHandler mErrorHandler 错误处理 * @param mRootView mRootView Viw对象 * @param mRepositoryManager mRepositoryManager 接口调用管理者 * @param handle handle 回调 */ public static void commonRequestOne(Map<String, Object> map, String path, RxErrorHandler mErrorHandler, IView mRootView, IRepositoryManager mRepositoryManager, @Nullable NetworkUtils.ProgressMonitorHandle<QuestionBean> handle,boolean showLoading) { try { Observable<BaseResponse<QuestionBean>> observable = mRepositoryManager .obtainRetrofitService(CommonRequestService.class) .commonRequestGet(path, SignUtil.addParamSign(map)); NetworkUtils.commonGetNetworkData(observable, mErrorHandler, mRootView, handle,showLoading); } catch (Exception e) { e.printStackTrace(); } } }
42.959184
128
0.607363
1c2db69ac865fd2e42267dcc4f26bc19f452c736
2,692
package com.silverbullet.msg.ws.service.impl; import com.silverbullet.msg.ws.service.IWSMessageService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import javax.websocket.Session; import java.io.IOException; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.atomic.AtomicInteger; /** * Created by jeffyuan on 2018/11/21. */ @Service public class WSMessageService implements IWSMessageService { private static final Logger logger = LoggerFactory.getLogger(WSMessageService.class); // 记录当前session数量 private static final AtomicInteger onlineCount = new AtomicInteger(0); // 记录当前session private static CopyOnWriteArraySet<Session> sessionSet = new CopyOnWriteArraySet<Session>(); /** * 连接msg * * @param session */ @Override public void connectMsg(Session session) { sessionSet.add(session); int cnt = onlineCount.incrementAndGet(); // 在线数加1 } /** * 断开msg * * @param session */ @Override public void unConnectMsg(Session session) { sessionSet.remove(session); int cnt = onlineCount.decrementAndGet(); } /** * 返回连接的session个数 * * @return */ @Override public int getSessionSize() { return onlineCount.get(); } /** * 发送消息 * * @param session * @param message */ @Override public void sendMessage(Session session, String message) { try { session.getBasicRemote().sendText(String.format("%s (From Server,Session ID=%s)", message, session.getId())); } catch (IOException e) { logger.error("发送消息出错:{}", e.getMessage()); e.printStackTrace(); } } /** * 广播消息 * * @param message * @throws IOException */ @Override public void broadCastInfo(String message) throws IOException { for (Session session : sessionSet) { if(session.isOpen()){ sendMessage(session, message); } } } /** * 按照sessionid发布消息 * * @param sessionId * @param message * @throws IOException */ @Override public void sendMessage(String sessionId, String message) throws IOException { Session session = null; for (Session s : sessionSet) { if(s.getId().equals(sessionId)){ session = s; break; } } if(session!=null){ sendMessage(session, message); } else{ logger.warn("没有找到你指定ID的会话:{}",sessionId); } } }
23.008547
121
0.596954
d0b2de0d4865b7994e290a46da3cc58a7cc2065d
1,795
package org.keithkim.safeql.sample.projects; import org.jdbi.v3.core.mapper.reflect.ConstructorMapper; import org.keithkim.safeql.statement.TableDbRegistry; import java.util.ArrayList; import java.util.List; import java.util.Set; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toSet; public class Projects00 extends ArrayList<Project> { public Projects00() { super(); } public Projects00(List<Project> projects) { super(projects); } public Set<Long> ids() { return this.stream().map(project -> project.row.id).collect(toSet()); } public Projects00 whereAccountIdIn(Set<Long> accountIds) { List<Project> projects = TableDbRegistry.using(singletonList(new Account.Table("account", null)), handle -> { handle.registerRowMapper(ConstructorMapper.factory(Project.class)); return handle.createQuery("SELECT * FROM project WHERE account_id IN (<account_ids>)") .bindList("account_ids", new ArrayList<>(accountIds)) .mapTo(Project.class) .list(); }); return new Projects00(projects); } public Projects00 where(String cond) { List<Project> projects = TableDbRegistry.using(singletonList(new Project.Table("project", null)), handle -> { handle.registerRowMapper(ConstructorMapper.factory(Project.class)); String whereClause = ""; if (cond != null && !cond.isEmpty()) { whereClause = " WHERE " + cond; } return handle.createQuery("SELECT * FROM project"+ whereClause) .mapTo(Project.class) .list(); }); return new Projects00(projects); } }
35.196078
117
0.632869
69657d67785863cc65b89c574b5d42803a3274aa
159
package com.artclod.common.base; public interface Product extends Iterable<Object> { public int productArity(); public Object productElement(int n); }
15.9
51
0.761006
0c89e98d14584b19d5c26205f26d32a17f046762
3,058
package com.fdreyfs.tenancy.demo; import java.util.HashMap; import java.util.Map; import javax.persistence.EntityManagerFactory; import javax.persistence.spi.PersistenceProvider; import javax.sql.DataSource; import org.eclipse.persistence.config.BatchWriting; import org.eclipse.persistence.config.PersistenceUnitProperties; import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.vendor.AbstractJpaVendorAdapter; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.jta.JtaTransactionManager; import com.fdreyfs.tenancy.eclipselink.EclipseLinkMultiTenantProvider; import com.fdreyfs.tenancy.eclipselink.EclipseLinkTenantPerEMFJpaVendorAdapter; import com.fdreyfs.tenancy.resolver.DefaultCurrentTenantResolver; @Configuration @EnableTransactionManagement @EnableJpaRepositories public class MultiTenancyConfiguration extends JpaBaseConfiguration { protected MultiTenancyConfiguration(DataSource dataSource, JpaProperties properties, ObjectProvider<JtaTransactionManager> jtaTransactionManagerProvider) { super(dataSource, properties, jtaTransactionManagerProvider); } @Bean public PlatformTransactionManager transactionManager(EntityManagerFactory emf) { final JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(emf); return transactionManager; } @Bean(destroyMethod="destroy") public PersistenceProvider persistenceProvider() { EclipseLinkMultiTenantProvider eclipseLinkMultiTenantProvider = new EclipseLinkMultiTenantProvider(); eclipseLinkMultiTenantProvider.setCurrentTenantResolver(new DefaultCurrentTenantResolver()); return eclipseLinkMultiTenantProvider; } @Override protected AbstractJpaVendorAdapter createJpaVendorAdapter() { EclipseLinkTenantPerEMFJpaVendorAdapter eclipseLinkTenantPerEMFJpaVendorAdapter = new EclipseLinkTenantPerEMFJpaVendorAdapter(); eclipseLinkTenantPerEMFJpaVendorAdapter.setPersistenceProvider(persistenceProvider()); return eclipseLinkTenantPerEMFJpaVendorAdapter; } @Override protected Map<String, Object> getVendorProperties() { final Map<String, Object> ret = new HashMap<>(); ret.put(PersistenceUnitProperties.LOGGING_LEVEL, "FINE"); ret.put(PersistenceUnitProperties.LOGGING_PARAMETERS, "true"); ret.put(PersistenceUnitProperties.BATCH_WRITING, BatchWriting.JDBC); return ret; } }
44.318841
136
0.816874
47b5c6532dd2343a13ce9914530c605aad6c9603
1,515
/** * 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 com.alibaba.cloudapi.client.constant; import java.nio.charset.Charset; /** * Created by fred on 16/9/7. */ public class Constants { //编码UTF-8 public static final Charset CLOUDAPI_ENCODING = Charset.forName("UTF-8"); //Header头的编码 public static final Charset CLOUDAPI_HEADER_ENCODING = Charset.forName("ISO-8859-1"); //UserAgent public static final String CLOUDAPI_USER_AGENT = "ALIYUN-ANDROID-DEMO"; //换行符 public static final String CLOUDAPI_LF = "\n"; //参与签名的系统Header前缀,只有指定前缀的Header才会参与到签名中 public static final String CLOUDAPI_CA_HEADER_TO_SIGN_PREFIX_SYSTEM = "X-Ca-"; //签名版本号 public static final String CLOUDAPI_CA_VERSION_VALUE = "1"; }
35.232558
89
0.738614
552c7a1ee071b6310e09427472a15ac6fb80a5b0
1,519
package mage.cards.w; import java.util.UUID; import mage.MageInt; import mage.abilities.common.DealsDamageToOpponentTriggeredAbility; import mage.abilities.effects.common.PutCardFromHandOntoBattlefieldEffect; import mage.abilities.keyword.DoubleStrikeAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.filter.common.FilterCreatureCard; /** * * @author North */ public final class WarrenInstigator extends CardImpl { private static final FilterCreatureCard filter = new FilterCreatureCard("a Goblin creature card"); static { filter.add(SubType.GOBLIN.getPredicate()); } public WarrenInstigator(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{R}{R}"); this.subtype.add(SubType.GOBLIN); this.subtype.add(SubType.BERSERKER); this.power = new MageInt(1); this.toughness = new MageInt(1); this.addAbility(DoubleStrikeAbility.getInstance()); // Whenever Warren Instigator deals damage to an opponent, you may put a Goblin creature card from your hand onto the battlefield. this.addAbility(new DealsDamageToOpponentTriggeredAbility(new PutCardFromHandOntoBattlefieldEffect(filter), false)); } private WarrenInstigator(final WarrenInstigator card) { super(card); } @Override public WarrenInstigator copy() { return new WarrenInstigator(this); } }
30.38
138
0.738644