hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e0889ad647fef49997cffeb5995c9fd3ff69765
3,858
java
Java
sdk/src/main/java/com/vk/api/sdk/queries/users/UsersGetSubscriptionsQueryWithExtended.java
KokorinIlya/vk-java-sdk
8d21f9b32b46db09defa9b9dd2647cd18a5116e7
[ "MIT" ]
1
2021-06-13T03:57:42.000Z
2021-06-13T03:57:42.000Z
sdk/src/main/java/com/vk/api/sdk/queries/users/UsersGetSubscriptionsQueryWithExtended.java
vadimgurov/vk-java-sdk
bd4da82881dc5101cc82629cf64b08019d18ac06
[ "MIT" ]
null
null
null
sdk/src/main/java/com/vk/api/sdk/queries/users/UsersGetSubscriptionsQueryWithExtended.java
vadimgurov/vk-java-sdk
bd4da82881dc5101cc82629cf64b08019d18ac06
[ "MIT" ]
1
2018-10-01T09:43:32.000Z
2018-10-01T09:43:32.000Z
35.072727
156
0.697512
3,618
package com.vk.api.sdk.queries.users; import com.vk.api.sdk.client.AbstractQueryBuilder; import com.vk.api.sdk.client.VkApiClient; import com.vk.api.sdk.client.actors.ServiceActor; import com.vk.api.sdk.client.actors.UserActor; import com.vk.api.sdk.objects.users.responses.GetSubscriptionsExtendedResponse; import java.util.Collections; import java.util.List; /** * Query for Users.getSubscriptions method */ public class UsersGetSubscriptionsQueryWithExtended extends AbstractQueryBuilder<UsersGetSubscriptionsQueryWithExtended, GetSubscriptionsExtendedResponse> { /** * Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters * * @param client VK API client * @param actor actor with access token */ public UsersGetSubscriptionsQueryWithExtended(VkApiClient client, UserActor actor) { super(client, "users.getSubscriptions", GetSubscriptionsExtendedResponse.class); accessToken(actor.getAccessToken()); extended(true); } /** * Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters * * @param client VK API client */ public UsersGetSubscriptionsQueryWithExtended(VkApiClient client, ServiceActor actor) { super(client, "users.getSubscriptions", GetSubscriptionsExtendedResponse.class); accessToken(actor.getAccessToken()); clientSecret(actor.getClientSecret()); extended(true); } /** * User ID. * * @param value value of "user id" parameter. Minimum is 0. * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern. */ public UsersGetSubscriptionsQueryWithExtended userId(Integer value) { return unsafeParam("user_id", value); } /** * Return a combined list of users and communities * * @param value value of "extended" parameter. * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern. */ protected UsersGetSubscriptionsQueryWithExtended extended(Boolean value) { return unsafeParam("extended", value); } /** * Offset needed to return a specific subset of subscriptions. * * @param value value of "offset" parameter. Minimum is 0. * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern. */ public UsersGetSubscriptionsQueryWithExtended offset(Integer value) { return unsafeParam("offset", value); } /** * Number of users and communities to return. * * @param value value of "count" parameter. Maximum is 200. Minimum is 0. By default 20. * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern. */ public UsersGetSubscriptionsQueryWithExtended count(Integer value) { return unsafeParam("count", value); } /** * Set fields * * @param value value of "fields" parameter. * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern. */ public UsersGetSubscriptionsQueryWithExtended fields(UserField... value) { return unsafeParam("fields", value); } /** * Set fields * * @param value value of "fields" parameter. * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern. */ public UsersGetSubscriptionsQueryWithExtended fields(List<UserField> value) { return unsafeParam("fields", value); } @Override protected UsersGetSubscriptionsQueryWithExtended getThis() { return this; } @Override protected List<String> essentialKeys() { return Collections.EMPTY_LIST; } }
3e088a30f2642ee363db644dcca4bd48bb7c2b40
190
java
Java
src/main/java/com/vrdete/email/constant/IResultCode.java
Lozt4r/email-sdk
de3d6776a146a9bf853386370cc9fe20ae933f59
[ "MIT" ]
null
null
null
src/main/java/com/vrdete/email/constant/IResultCode.java
Lozt4r/email-sdk
de3d6776a146a9bf853386370cc9fe20ae933f59
[ "MIT" ]
null
null
null
src/main/java/com/vrdete/email/constant/IResultCode.java
Lozt4r/email-sdk
de3d6776a146a9bf853386370cc9fe20ae933f59
[ "MIT" ]
null
null
null
14.615385
51
0.710526
3,619
package com.vrdete.email.constant; import java.io.Serializable; /** * @author fu */ public interface IResultCode extends Serializable { String getMessage(); String getCode(); }
3e088a4bfe789a516768fcfd7a6910bf7c54a460
6,073
java
Java
app/src/main/java/com/github/ggggxiaolong/customview/trapezoid/TrapezoidView.java
ggggxiaolong/CustomView
c7698eb65e32a50863be35090827dd7f71a295c3
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/github/ggggxiaolong/customview/trapezoid/TrapezoidView.java
ggggxiaolong/CustomView
c7698eb65e32a50863be35090827dd7f71a295c3
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/github/ggggxiaolong/customview/trapezoid/TrapezoidView.java
ggggxiaolong/CustomView
c7698eb65e32a50863be35090827dd7f71a295c3
[ "Apache-2.0" ]
null
null
null
33.185792
99
0.668204
3,620
package com.github.ggggxiaolong.customview.trapezoid; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.support.annotation.Nullable; import android.support.v4.util.Preconditions; import android.text.TextPaint; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.view.View; import com.github.ggggxiaolong.customview.R; import java.util.Collections; import java.util.List; /** * @author mrtan on 10/10/17. */ public class TrapezoidView extends View { private TextPaint mTextPaint; private Paint mPaint; private int textColor, textSize;//字体大小颜色 final private float DEFAULT_MIN_WIDTH = 1.0f / 4;//默认最小宽度 final private int divider; //每个Item之间的间隔 private int minWidth; //最小Item的宽度 private int perItemWidth;//每个item的value的值对应的宽度 private int itemHeight;//Item的高度 private int mWidth, mHeight; //View测量之后的宽高 private List<TrapezoidBean> mItems; private Path mPath; private int mTextX, mTextHeight; private String TAG = "TrapView"; public TrapezoidView(Context context) { this(context, null); } public TrapezoidView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public TrapezoidView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TrapezoidView); textColor = a.getColor(R.styleable.TrapezoidView_android_textColor, Color.WHITE); divider = a.getDimensionPixelSize(R.styleable.TrapezoidView_android_dividerHeight, 0); minWidth = a.getDimensionPixelSize(R.styleable.TrapezoidView_android_minWidth, 0); textSize = a.getDimensionPixelSize(R.styleable.TrapezoidView_android_textSize, 0); a.recycle(); init(); } private void init() { mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.LINEAR_TEXT_FLAG); mTextPaint.setColor(textColor); if (textSize != 0) mTextPaint.setTextSize(textSize); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG); mPaint.setStyle(Paint.Style.FILL); mPath = new Path(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mWidth = w; mHeight = h; mTextX = mWidth / 2; if (minWidth == 0) minWidth = (int) (mWidth * DEFAULT_MIN_WIDTH);//最小宽度 initData(); } private void initData() { //如果设置了字体大小,最小宽度要大于等于最小值字的长度 if (mItems == null || mItems.isEmpty()) return; int size = mItems.size(); if (textSize != 0) { String title = mItems.get(size - 1).title; int textWidth = (int) mTextPaint.measureText(title) + dp2px(getContext(), 2); if (minWidth < textWidth) minWidth = textWidth; } //计算每个Item的高度 itemHeight = (mHeight - divider * (size - 1)) / size; //如果没有设置字体的大小按照item的大小 if (textSize == 0) { textSize = itemHeight - dp2px(getContext(), 2); mTextPaint.setTextSize(textSize); } //计算每份item的value的宽度 if (size == 1) { perItemWidth = 0; } else { perItemWidth = (mWidth - minWidth) / (mItems.get(size - 1).value - mItems.get(0).value) / 2; } //计算字体想对于梯形的高度 final Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics(); mTextHeight = (int) (itemHeight - fontMetrics.descent - fontMetrics.ascent) / 2; //Log.i(TAG, "minWidth:" + minWidth); //Log.i(TAG, "textSize:" + textSize); //Log.i(TAG, "perItemWidth:" + perItemWidth); //Log.i(TAG, "itemHeight:" + itemHeight); //Log.i(TAG, "mTextX:" + mTextX); //Log.i(TAG, "divider:" + divider); //Log.i(TAG, "mTextHeight:" + mTextHeight); } public void setItems(List<TrapezoidBean> items) { if (items == null) throw new IllegalArgumentException("data can't be null"); mItems = items; Collections.sort(mItems, TrapezoidBean.comparator()); initData(); } public static int dp2px(Context context, float dpValue) { DisplayMetrics metric = context.getResources().getDisplayMetrics(); return (int) (dpValue * metric.density + 0.5f); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mItems == null || mItems.isEmpty()) return; int lastLeft = 0, lastRight = mWidth, lastTop = 0; int left; int right; int top; int bottom; int gap = 0; if (mItems.size() == 1) { TrapezoidBean bean = mItems.get(0); left = 0; right = mWidth; top = 0; bottom = mHeight; drawTrapezoid(canvas, left, right, top, bottom, gap, bean); } else { TrapezoidBean bean = mItems.get(0); TrapezoidBean next; int index = 1; for (; index < mItems.size(); index++) { next = mItems.get(index); gap = (next.value - bean.value) * perItemWidth; bottom = lastTop + itemHeight; drawTrapezoid(canvas, lastLeft, lastRight, lastTop, bottom, gap, bean); lastLeft += gap; lastRight -= gap; lastTop = bottom + divider; bean = next; } //画最后一个 drawTrapezoid(canvas, lastLeft, lastRight, lastTop, lastTop + itemHeight, 0, bean); } } private void drawTrapezoid(Canvas canvas, int left, int right, int top, int bottom, int gap, TrapezoidBean bean) { //文字的位置 int textY = top + mTextHeight; //Log.i(TAG, "left:" + left); //Log.i(TAG, "right:" + right); //Log.i(TAG, "top:" + top); //Log.i(TAG, "bottom:" + bottom); //Log.i(TAG, "gap:" + gap); //Log.i(TAG, "textY:" + textY); //画图形 mPath.reset(); mPath.moveTo(left, top); mPath.lineTo(right, top); mPath.lineTo(right - gap, bottom); mPath.lineTo(left + gap, bottom); mPath.close(); mPaint.setColor(bean.color); canvas.drawPath(mPath, mPaint); mTextPaint.setTextAlign(Paint.Align.CENTER); canvas.drawText(bean.title, mTextX, textY, mTextPaint); } }
3e088b7292e7ca2dd39679444fe80a4b89a3d3cf
495
java
Java
src/AST/CharacterLiteral.java
coffee-cup/unnamed-language
9a598c261772bdede53f2c6194d0a8bfabb0e2bd
[ "Apache-2.0" ]
null
null
null
src/AST/CharacterLiteral.java
coffee-cup/unnamed-language
9a598c261772bdede53f2c6194d0a8bfabb0e2bd
[ "Apache-2.0" ]
null
null
null
src/AST/CharacterLiteral.java
coffee-cup/unnamed-language
9a598c261772bdede53f2c6194d0a8bfabb0e2bd
[ "Apache-2.0" ]
null
null
null
18.333333
63
0.606061
3,621
package AST; import Types.CharType; import Types.Type; public class CharacterLiteral extends Literal { private char value; public CharacterLiteral(char value, int line, int offset) { this.value = value; this.line = line; this.offset = offset; } public char getValue() { return value; } public Type getType() { return CharType.getInstance(); } public <T> T accept(Visitor<T> v) { return v.visit(this); } }
3e088b8565f2a97db9dc31cf4b9b7e940a5e308e
8,351
java
Java
core/java/android/view/textclassifier/TextClassifierEventTronLogger.java
rio-31/android_frameworks_base-1
091a068a3288d27d77636708679dde58b7b7fd25
[ "Apache-2.0" ]
164
2015-01-05T16:49:11.000Z
2022-03-29T20:40:27.000Z
core/java/android/view/textclassifier/TextClassifierEventTronLogger.java
rio-31/android_frameworks_base-1
091a068a3288d27d77636708679dde58b7b7fd25
[ "Apache-2.0" ]
127
2015-01-12T12:02:32.000Z
2021-11-28T08:46:25.000Z
core/java/android/view/textclassifier/TextClassifierEventTronLogger.java
rio-31/android_frameworks_base-1
091a068a3288d27d77636708679dde58b7b7fd25
[ "Apache-2.0" ]
1,141
2015-01-01T22:54:40.000Z
2022-02-09T22:08:26.000Z
44.420213
115
0.699557
3,622
/* * 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.view.textclassifier; import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TEXTCLASSIFIER_MODEL; import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TEXT_CLASSIFIER_FIRST_ENTITY_TYPE; import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TEXT_CLASSIFIER_SCORE; import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TEXT_CLASSIFIER_SECOND_ENTITY_TYPE; import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TEXT_CLASSIFIER_SESSION_ID; import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TEXT_CLASSIFIER_THIRD_ENTITY_TYPE; import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TEXT_CLASSIFIER_WIDGET_TYPE; import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.FIELD_TEXT_CLASSIFIER_WIDGET_VERSION; import android.metrics.LogMaker; import com.android.internal.annotations.VisibleForTesting; import com.android.internal.logging.MetricsLogger; import com.android.internal.logging.nano.MetricsProto.MetricsEvent; import com.android.internal.util.Preconditions; /** * Log {@link TextClassifierEvent} by using Tron, only support language detection and * conversation actions. * * @hide */ public final class TextClassifierEventTronLogger { private static final String TAG = "TCEventTronLogger"; private final MetricsLogger mMetricsLogger; public TextClassifierEventTronLogger() { this(new MetricsLogger()); } @VisibleForTesting public TextClassifierEventTronLogger(MetricsLogger metricsLogger) { mMetricsLogger = Preconditions.checkNotNull(metricsLogger); } /** Emits a text classifier event to the logs. */ public void writeEvent(TextClassifierEvent event) { Preconditions.checkNotNull(event); int category = getCategory(event); if (category == -1) { Log.w(TAG, "Unknown category: " + event.getEventCategory()); return; } final LogMaker log = new LogMaker(category) .setSubtype(getLogType(event)) .addTaggedData(FIELD_TEXT_CLASSIFIER_SESSION_ID, event.getResultId()) .addTaggedData(FIELD_TEXTCLASSIFIER_MODEL, getModelName(event)); if (event.getScores().length >= 1) { log.addTaggedData(FIELD_TEXT_CLASSIFIER_SCORE, event.getScores()[0]); } String[] entityTypes = event.getEntityTypes(); // The old logger does not support a field of list type, and thus workaround by store them // in three separate fields. This is not an issue with the new logger. if (entityTypes.length >= 1) { log.addTaggedData(FIELD_TEXT_CLASSIFIER_FIRST_ENTITY_TYPE, entityTypes[0]); } if (entityTypes.length >= 2) { log.addTaggedData(FIELD_TEXT_CLASSIFIER_SECOND_ENTITY_TYPE, entityTypes[1]); } if (entityTypes.length >= 3) { log.addTaggedData(FIELD_TEXT_CLASSIFIER_THIRD_ENTITY_TYPE, entityTypes[2]); } TextClassificationContext eventContext = event.getEventContext(); if (eventContext != null) { log.addTaggedData(FIELD_TEXT_CLASSIFIER_WIDGET_TYPE, eventContext.getWidgetType()); log.addTaggedData(FIELD_TEXT_CLASSIFIER_WIDGET_VERSION, eventContext.getWidgetVersion()); log.setPackageName(eventContext.getPackageName()); } mMetricsLogger.write(log); debugLog(log); } private static String getModelName(TextClassifierEvent event) { if (event.getModelName() != null) { return event.getModelName(); } return SelectionSessionLogger.SignatureParser.getModelName(event.getResultId()); } private static int getCategory(TextClassifierEvent event) { switch (event.getEventCategory()) { case TextClassifierEvent.CATEGORY_CONVERSATION_ACTIONS: return MetricsEvent.CONVERSATION_ACTIONS; case TextClassifierEvent.CATEGORY_LANGUAGE_DETECTION: return MetricsEvent.LANGUAGE_DETECTION; } return -1; } private static int getLogType(TextClassifierEvent event) { switch (event.getEventType()) { case TextClassifierEvent.TYPE_SMART_ACTION: return MetricsEvent.ACTION_TEXT_SELECTION_SMART_SHARE; case TextClassifierEvent.TYPE_ACTIONS_SHOWN: return MetricsEvent.ACTION_TEXT_CLASSIFIER_ACTIONS_SHOWN; case TextClassifierEvent.TYPE_MANUAL_REPLY: return MetricsEvent.ACTION_TEXT_CLASSIFIER_MANUAL_REPLY; case TextClassifierEvent.TYPE_ACTIONS_GENERATED: return MetricsEvent.ACTION_TEXT_CLASSIFIER_ACTIONS_GENERATED; default: return MetricsEvent.VIEW_UNKNOWN; } } private String toCategoryName(int category) { switch (category) { case MetricsEvent.CONVERSATION_ACTIONS: return "conversation_actions"; case MetricsEvent.LANGUAGE_DETECTION: return "language_detection"; } return "unknown"; } private String toEventName(int logType) { switch (logType) { case MetricsEvent.ACTION_TEXT_SELECTION_SMART_SHARE: return "smart_share"; case MetricsEvent.ACTION_TEXT_CLASSIFIER_ACTIONS_SHOWN: return "actions_shown"; case MetricsEvent.ACTION_TEXT_CLASSIFIER_MANUAL_REPLY: return "manual_reply"; case MetricsEvent.ACTION_TEXT_CLASSIFIER_ACTIONS_GENERATED: return "actions_generated"; } return "unknown"; } private void debugLog(LogMaker log) { if (!Log.ENABLE_FULL_LOGGING) { return; } final String id = String.valueOf(log.getTaggedData(FIELD_TEXT_CLASSIFIER_SESSION_ID)); final String categoryName = toCategoryName(log.getCategory()); final String eventName = toEventName(log.getSubtype()); final String widgetType = String.valueOf(log.getTaggedData(FIELD_TEXT_CLASSIFIER_WIDGET_TYPE)); final String widgetVersion = String.valueOf(log.getTaggedData(FIELD_TEXT_CLASSIFIER_WIDGET_VERSION)); final String model = String.valueOf(log.getTaggedData(FIELD_TEXTCLASSIFIER_MODEL)); final String firstEntityType = String.valueOf(log.getTaggedData(FIELD_TEXT_CLASSIFIER_FIRST_ENTITY_TYPE)); final String secondEntityType = String.valueOf(log.getTaggedData(FIELD_TEXT_CLASSIFIER_SECOND_ENTITY_TYPE)); final String thirdEntityType = String.valueOf(log.getTaggedData(FIELD_TEXT_CLASSIFIER_THIRD_ENTITY_TYPE)); final String score = String.valueOf(log.getTaggedData(FIELD_TEXT_CLASSIFIER_SCORE)); StringBuilder builder = new StringBuilder(); builder.append("writeEvent: "); builder.append("id=").append(id); builder.append(", category=").append(categoryName); builder.append(", eventName=").append(eventName); builder.append(", widgetType=").append(widgetType); builder.append(", widgetVersion=").append(widgetVersion); builder.append(", model=").append(model); builder.append(", firstEntityType=").append(firstEntityType); builder.append(", secondEntityType=").append(secondEntityType); builder.append(", thirdEntityType=").append(thirdEntityType); builder.append(", score=").append(score); Log.v(TAG, builder.toString()); } }
3e088b86bdacc4ec30457e2d1b3ae1f716ebc32c
4,143
java
Java
moquette-common/src/main/java/io/moquette/BrokerConstants.java
irubant/moquette
0f2c393817aa70cce5dc6f876d6d8839fabc13f6
[ "ECL-2.0", "Apache-2.0" ]
38
2017-09-25T08:23:49.000Z
2020-02-25T15:13:46.000Z
moquette-common/src/main/java/io/moquette/BrokerConstants.java
irubant/moquette
0f2c393817aa70cce5dc6f876d6d8839fabc13f6
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
moquette-common/src/main/java/io/moquette/BrokerConstants.java
irubant/moquette
0f2c393817aa70cce5dc6f876d6d8839fabc13f6
[ "ECL-2.0", "Apache-2.0" ]
23
2017-10-20T09:50:02.000Z
2020-02-10T04:00:22.000Z
57.541667
109
0.776732
3,623
/* * Copyright (c) 2012-2017 The original author or authors * ------------------------------------------------------ * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.moquette; import java.io.File; public final class BrokerConstants { public static final String INTERCEPT_HANDLER_PROPERTY_NAME = "intercept.handler"; public static final String BROKER_INTERCEPTOR_THREAD_POOL_SIZE = "intercept.thread_pool.size"; public static final String PERSISTENT_STORE_PROPERTY_NAME = "persistent_store"; public static final String AUTOSAVE_INTERVAL_PROPERTY_NAME = "autosave_interval"; public static final String PASSWORD_FILE_PROPERTY_NAME = "password_file"; public static final String PORT_PROPERTY_NAME = "port"; public static final String HOST_PROPERTY_NAME = "host"; public static final String DEFAULT_MOQUETTE_STORE_MAP_DB_FILENAME = "moquette_store.mapdb"; public static final String DEFAULT_PERSISTENT_PATH = System.getProperty("user.dir") + File.separator + DEFAULT_MOQUETTE_STORE_MAP_DB_FILENAME; public static final String WEB_SOCKET_PORT_PROPERTY_NAME = "websocket_port"; public static final String HTTP_PORT_PROPERTY_NAME = "http_port"; public static final String WSS_PORT_PROPERTY_NAME = "secure_websocket_port"; public static final String SSL_PORT_PROPERTY_NAME = "ssl_port"; public static final String JKS_PATH_PROPERTY_NAME = "jks_path"; public static final String KEY_STORE_PASSWORD_PROPERTY_NAME = "key_store_password"; public static final String KEY_MANAGER_PASSWORD_PROPERTY_NAME = "key_manager_password"; public static final String ALLOW_ANONYMOUS_PROPERTY_NAME = "allow_anonymous"; public static final String ALLOW_ZERO_BYTE_CLIENT_ID_PROPERTY_NAME = "allow_zero_byte_client_id"; public static final String ACL_FILE_PROPERTY_NAME = "acl_file"; public static final String AUTHORIZATOR_CLASS_NAME = "authorizator_class"; public static final String AUTHENTICATOR_CLASS_NAME = "authenticator_class"; public static final String DB_AUTHENTICATOR_DRIVER = "authenticator.db.driver"; public static final String DB_AUTHENTICATOR_URL = "authenticator.db.url"; public static final String DB_AUTHENTICATOR_QUERY = "authenticator.db.query"; public static final String DB_AUTHENTICATOR_DIGEST = "authenticator.db.digest"; public static final String DB_AUTHORIZATOR_DRIVER = "authorizator.db.driver"; public static final String DB_AUTHORIZATOR_URL = "authorizator.db.url"; public static final String DB_AUTHORIZATOR_QUERY = "authorizator.db.query"; public static final String DB_AUTHORIZATOR_DIGEST = "authorizator.db.digest"; public static final int PORT = 1883; public static final int WEBSOCKET_PORT = 8080; public static final int HTTP_PORT = 8088; public static final String DISABLED_PORT_BIND = "disabled"; public static final String HOST = "0.0.0.0"; public static final String NEED_CLIENT_AUTH = "need_client_auth"; public static final String HAZELCAST_CONFIGURATION = "hazelcast.configuration"; public static final String NETTY_SO_BACKLOG_PROPERTY_NAME = "netty.so_backlog"; public static final String NETTY_SO_REUSEADDR_PROPERTY_NAME = "netty.so_reuseaddr"; public static final String NETTY_TCP_NODELAY_PROPERTY_NAME = "netty.tcp_nodelay"; public static final String NETTY_SO_KEEPALIVE_PROPERTY_NAME = "netty.so_keepalive"; public static final String NETTY_CHANNEL_TIMEOUT_SECONDS_PROPERTY_NAME = "netty.channel_timeout.seconds"; public static final String NETTY_EPOLL_PROPERTY_NAME = "netty.epoll"; public static final String STORAGE_CLASS_NAME = "storage_class"; private BrokerConstants() { } }
3e088c184adf04c8b5c53733395c59379bb5531e
2,482
java
Java
src/test/java/edu/harvard/iq/dataverse/api/AbstractApiBeanTest.java
vishalbelsare/dataverse
823d0f95e9bdc2951816bfc31b7234accb66aa01
[ "Apache-2.0" ]
681
2015-01-07T14:18:29.000Z
2022-03-28T12:26:27.000Z
src/test/java/edu/harvard/iq/dataverse/api/AbstractApiBeanTest.java
vishalbelsare/dataverse
823d0f95e9bdc2951816bfc31b7234accb66aa01
[ "Apache-2.0" ]
7,286
2015-01-04T06:45:45.000Z
2022-03-31T22:57:24.000Z
src/test/java/edu/harvard/iq/dataverse/api/AbstractApiBeanTest.java
vishalbelsare/dataverse
823d0f95e9bdc2951816bfc31b7234accb66aa01
[ "Apache-2.0" ]
433
2015-01-14T10:21:20.000Z
2022-03-31T12:43:08.000Z
31.417722
110
0.707494
3,624
package edu.harvard.iq.dataverse.api; import edu.harvard.iq.dataverse.util.MockResponse; import java.io.StringReader; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonReader; import javax.json.JsonWriter; import javax.json.JsonWriterFactory; import javax.json.stream.JsonGenerator; import javax.ws.rs.core.Response; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; public class AbstractApiBeanTest { private static final Logger logger = Logger.getLogger(AbstractApiBeanTest.class.getCanonicalName()); AbstractApiBeanImpl sut; @Before public void before() { sut = new AbstractApiBeanImpl(); } @Test public void testParseBooleanOrDie_ok() throws Exception { assertTrue(sut.parseBooleanOrDie("1")); assertTrue(sut.parseBooleanOrDie("yes")); assertTrue(sut.parseBooleanOrDie("true")); assertFalse(sut.parseBooleanOrDie("false")); assertFalse(sut.parseBooleanOrDie("0")); assertFalse(sut.parseBooleanOrDie("no")); } @Test(expected = Exception.class) public void testParseBooleanOrDie_invalid() throws Exception { sut.parseBooleanOrDie("I'm not a boolean value!"); } @Test public void testFailIfNull_ok() throws Exception { sut.failIfNull(sut, ""); } @Test public void testMessagesNoJsonObject() { String message = "myMessage"; Response response = sut.ok(message); JsonReader jsonReader = Json.createReader(new StringReader((String) response.getEntity().toString())); JsonObject jsonObject = jsonReader.readObject(); Map<String, Boolean> config = new HashMap<>(); config.put(JsonGenerator.PRETTY_PRINTING, true); JsonWriterFactory jwf = Json.createWriterFactory(config); StringWriter sw = new StringWriter(); try (JsonWriter jsonWriter = jwf.createWriter(sw)) { jsonWriter.writeObject(jsonObject); } logger.info(sw.toString()); assertEquals(message, jsonObject.getJsonObject("data").getString("message")); } /** * dummy implementation */ public class AbstractApiBeanImpl extends AbstractApiBean { } }
3e088cc9441b08afc8aa55f3182f5107e740ca45
2,515
java
Java
Android/SharedPreferencesExample/app/src/main/java/com/learn/bella/sharedpreferencesexample/MainActivity.java
adamBellaPrivate/android-learing-beginner
514c98abb0174ca941b25cb98d7191db58f4f8a0
[ "MIT" ]
null
null
null
Android/SharedPreferencesExample/app/src/main/java/com/learn/bella/sharedpreferencesexample/MainActivity.java
adamBellaPrivate/android-learing-beginner
514c98abb0174ca941b25cb98d7191db58f4f8a0
[ "MIT" ]
null
null
null
Android/SharedPreferencesExample/app/src/main/java/com/learn/bella/sharedpreferencesexample/MainActivity.java
adamBellaPrivate/android-learing-beginner
514c98abb0174ca941b25cb98d7191db58f4f8a0
[ "MIT" ]
null
null
null
41.916667
164
0.699801
3,625
package com.learn.bella.sharedpreferencesexample; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private static final String NOTIFICATION_ALLOW_STATE = "shared.preferences.notification.allow.state"; private SharedPreferences ownSharedPreferences; private SharedPreferences defaultSharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ownSharedPreferences = getSharedPreferences("SharedPreferencesExample",MODE_PRIVATE); defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences( getBaseContext()); Button notificationButton = findViewById(R.id.notification_allow_button); notificationButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boolean oldValue = ownSharedPreferences.getBoolean(NOTIFICATION_ALLOW_STATE,false); SharedPreferences.Editor editor = ownSharedPreferences.edit(); editor.putBoolean(NOTIFICATION_ALLOW_STATE,!oldValue); editor.commit(); Log.d("Shared Preferences","New state: " + String.valueOf(ownSharedPreferences.getBoolean(NOTIFICATION_ALLOW_STATE,false))); //---------- boolean oldEnabledNotification = defaultSharedPreferences.getBoolean("enableNotification",false); editor = defaultSharedPreferences.edit(); editor.putBoolean("enableNotification",!oldEnabledNotification); editor.commit(); Log.d("Shared Preferences", "New state of default preferences: " + String.valueOf(defaultSharedPreferences.getBoolean("enableNotification",false))); } }); Button settingsButton = findViewById(R.id.settings_button); settingsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getFragmentManager().beginTransaction().addToBackStack("MyPreferenceFragment") .replace(android.R.id.content, new MyPreferenceFragment()).commit(); } }); } }
3e088d244cb18393a5b453a195a6d777cac3253b
5,126
java
Java
apache-jmeter-3.1/test/src/org/apache/jmeter/junit/JMeterTestCaseJUnit3.java
yuyupapa/osc
1fb74576020827ba39529c0b2ebed441b4721c47
[ "Apache-2.0" ]
1
2021-09-03T07:38:40.000Z
2021-09-03T07:38:40.000Z
test/src/org/apache/jmeter/junit/JMeterTestCaseJUnit3.java
lanye1990/ApacheJmeter
d81376a80069b7e36ed2698ff2b10610027f9877
[ "Apache-2.0" ]
null
null
null
test/src/org/apache/jmeter/junit/JMeterTestCaseJUnit3.java
lanye1990/ApacheJmeter
d81376a80069b7e36ed2698ff2b10610027f9877
[ "Apache-2.0" ]
null
null
null
37.97037
93
0.599493
3,626
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.junit; import java.io.File; import java.nio.charset.Charset; import java.util.Collection; import java.util.LinkedList; import java.util.Locale; import java.util.MissingResourceException; import org.apache.jmeter.engine.util.CompoundVariable; import org.apache.jmeter.functions.AbstractFunction; import org.apache.jmeter.functions.InvalidVariableException; import org.apache.jmeter.util.JMeterUtils; import junit.framework.TestCase; /* * Extend JUnit TestCase to provide common setup */ public abstract class JMeterTestCaseJUnit3 extends TestCase { // Used by findTestFile private static final String filePrefix; public JMeterTestCaseJUnit3() { super(); } public JMeterTestCaseJUnit3(String name) { super(name); } /* * If not running under AllTests.java, make sure that the properties (and * log file) are set up correctly. * * N.B. In order for this to work correctly, the JUnit test must be started * in the bin directory, and all the JMeter jars (plus any others needed at * run-time) need to be on the classpath. * */ static { if (JMeterUtils.getJMeterProperties() == null) { String file = "jmeter.properties"; File f = new File(file); if (!f.canRead()) { System.out.println("Can't find " + file + " - trying bin directory"); file = "bin/" + file;// JMeterUtils assumes Unix-style separators filePrefix = "bin/"; } else { filePrefix = ""; } // Used to be done in initializeProperties String home=new File(System.getProperty("user.dir"),filePrefix).getParent(); System.out.println("Setting JMeterHome: "+home); JMeterUtils.setJMeterHome(home); System.setProperty("jmeter.home", home); // needed for scripts JMeterUtils jmu = new JMeterUtils(); try { jmu.initializeProperties(file); } catch (MissingResourceException e) { System.out.println("** Can't find resources - continuing anyway **"); } System.out.println("JMeterVersion="+JMeterUtils.getJMeterVersion()); logprop("java.version"); logprop("java.vm.name"); logprop("java.vendor"); logprop("java.home"); logprop("file.encoding"); // Display actual encoding used (will differ if file.encoding is not recognised) System.out.println("default encoding="+Charset.defaultCharset()); logprop("user.home"); logprop("user.dir"); logprop("user.language"); logprop("user.region"); logprop("user.country"); logprop("user.variant"); System.out.println("Locale="+Locale.getDefault().toString()); logprop("java.class.version"); logprop("java.awt.headless"); logprop("os.name"); logprop("os.version"); logprop("os.arch"); logprop("java.class.path"); } else { filePrefix = ""; } } private static void logprop(String prop) { System.out.println(prop + "=" + System.getProperty(prop)); } // Helper method to find a file protected static File findTestFile(String file) { File f = new File(file); if (filePrefix.length() > 0 && !f.isAbsolute()) { f = new File(filePrefix, file);// Add the offset } return f; } protected void checkInvalidParameterCounts(AbstractFunction func, int minimum) throws Exception { Collection<CompoundVariable> parms = new LinkedList<>(); for (int c = 0; c < minimum; c++) { try { func.setParameters(parms); fail("Should have generated InvalidVariableException for " + parms.size() + " parameters"); } catch (InvalidVariableException ignored) { } parms.add(new CompoundVariable()); } func.setParameters(parms); } }
3e088df91b0fb33c6090c466bfa39976274d62ec
949
java
Java
auxiliary_services/ARS-L-label-matching/shared/feign-client/src/main/java/de/buw/tmdt/plasma/ars/labeling/lm/shared/feignclient/LabelMatchingFeignConfiguration.java
tmdt-buw/plasma
ce977d051bd1e8aa0d9de1f3280ba487fbabbae9
[ "Apache-2.0" ]
2
2020-12-17T19:07:37.000Z
2022-03-16T09:21:40.000Z
auxiliary_services/ARS-L-label-matching/shared/feign-client/src/main/java/de/buw/tmdt/plasma/ars/labeling/lm/shared/feignclient/LabelMatchingFeignConfiguration.java
tmdt-buw/plasma
ce977d051bd1e8aa0d9de1f3280ba487fbabbae9
[ "Apache-2.0" ]
null
null
null
auxiliary_services/ARS-L-label-matching/shared/feign-client/src/main/java/de/buw/tmdt/plasma/ars/labeling/lm/shared/feignclient/LabelMatchingFeignConfiguration.java
tmdt-buw/plasma
ce977d051bd1e8aa0d9de1f3280ba487fbabbae9
[ "Apache-2.0" ]
1
2020-12-27T20:52:32.000Z
2020-12-27T20:52:32.000Z
35.148148
76
0.818757
3,627
package de.buw.tmdt.plasma.ars.labeling.lm.shared.feignclient; import feign.auth.BasicAuthRequestInterceptor; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @EnableFeignClients("de.buw.tmdt.plasma.ars.labeling.lm.shared.feignclient") @Configuration public class LabelMatchingFeignConfiguration { @Bean public CloseableHttpClient client() { return HttpClients.createDefault(); } @Bean public BasicAuthRequestInterceptor getDataModelingServiceAuthInterceptor( @Value("${plasma.ars.labeling.lm.user}") String user, @Value("${plasma.ars.labeling.lm.password}") String password ) { return new BasicAuthRequestInterceptor(user, password); } }
3e088e20c62689d192bca62c1d279d7b39e75b31
4,443
java
Java
src/main/java/de/gerdiproject/bookmark/backend/BookmarkPersistenceConstants.java
GeRDI-Project/PersistenceAPI_Bookmark
b913a714c6924757fa0ebe8db6e527bdd4dff643
[ "Apache-2.0" ]
null
null
null
src/main/java/de/gerdiproject/bookmark/backend/BookmarkPersistenceConstants.java
GeRDI-Project/PersistenceAPI_Bookmark
b913a714c6924757fa0ebe8db6e527bdd4dff643
[ "Apache-2.0" ]
null
null
null
src/main/java/de/gerdiproject/bookmark/backend/BookmarkPersistenceConstants.java
GeRDI-Project/PersistenceAPI_Bookmark
b913a714c6924757fa0ebe8db6e527bdd4dff643
[ "Apache-2.0" ]
null
null
null
46.28125
154
0.66194
3,628
/** * Copyright 2018 Nelson Tavares de Sousa * * 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 de.gerdiproject.bookmark.backend; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import com.mongodb.MongoCredential; /** * This class contains all the constants required for this software to work. * * @author Nelson Tavares de Sousa * */ @SuppressWarnings("PMD.LongVariable") public final class BookmarkPersistenceConstants { // MongoDB Constants static final int MONGO_DB_PORT = Integer.parseInt( System.getenv().getOrDefault("BOOKMARK_MONGODB_PORT", "27017")); static final String MONGO_DB_COLLECTION_NAME = System.getenv() .getOrDefault("BOOKMARK_MONGODB_COLLECTION_NAME", "collections"); static final String MONGO_DB_DB_NAME = System.getenv() .getOrDefault("BOOKMARK_MONGODB_DB_NAME", "select"); static final String MONGO_DB_HOSTNAME = System.getenv() .getOrDefault("BOOKMARK_MONGODB_DB_HOSTNAME", "localhost"); static final String MONGO_DB_ADMIN_DB_NAME = System.getenv() .getOrDefault("BOOKMARK_MONGODB_ADMIN_DB_NAME", "admin"); static final String MONGO_DB_USER = System.getenv() .getOrDefault("BOOKMARK_MONGODB_USERNAME", "admin"); static final String MONGO_DB_PASSWORD = System.getenv() .getOrDefault("BOOKMARK_MONGODB_PASSWORD", ""); static final MongoCredential MONGO_DB_CREDENTIAL = MongoCredential .createCredential(MONGO_DB_USER, MONGO_DB_ADMIN_DB_NAME, MONGO_DB_PASSWORD.toCharArray()); // Elasticsearch Constants static final String GERDI_ES_HOSTNAME = System.getenv() .getOrDefault("GERDI_ES_HOSTNAME", "localhost"); static final String GERDI_ES_INDEXNAME = System.getenv() .getOrDefault("GERDI_ES_INDEXNAME", "gerdi"); static final int GERDI_ES_PORT = Integer .parseInt(System.getenv().getOrDefault("GERDI_ES_PORT", "9200")); static final RestHighLevelClient ES_CLIENT = new RestHighLevelClient( RestClient.builder( new HttpHost(GERDI_ES_HOSTNAME, GERDI_ES_PORT, "http"))); // Other stuff public static final String APPLICATION_JSON = "application/json"; public static final String DATE_STRING = "yyyy-MM-dd HH:mm:ss"; public static final String PATH_PREFIX = "/api/v1/collections"; // MongoDB Field Names public static final String DB_COLLECTION_FIELD_NAME = "collectionName"; public static final String DB_USER_ID_FIELD_NAME = "userId"; public static final String DB_DOCS_FIELD_NAME = "docs"; public static final String DB_UID_FIELD_NAME = "_id"; // Param Constants public static final String PARAM_COLLECTION_NAME = "collectionId"; // Response Field Names public static final String RESPONSE_UID_FIELD_NAME = "_id"; public static final String RESPONSE_NAME_FIELD_NAME = "name"; public static final String RESPONSE_SOURCE_FIELD_NAME = "_source"; // Request Field Names public static final String REQUEST_DOCS_FIELD_NAME = "docs"; public static final String REQUEST_NAME_FIELD_NAME = "name"; // OpenID Infos public static final String OPENID_JWK_ENDPOINT = System.getenv() .getOrDefault("OPENID_JWK_ENDPOINT", "http://keycloak-http.default.svc.cluster.local/admin/auth/realms/master/protocol/openid-connect/certs"); private BookmarkPersistenceConstants() { } }
3e088fba3bdb7542e62bc68ede1fd9b30d60461d
133
java
Java
src/StockIT-v1-release_source_from_JADX/sources/androidx/sqlite/p007db/C0470R.java
atul-vyshnav/2021_IBM_Code_Challenge_StockIT
25c26a4cc59a3f3e575f617b59acc202ee6ee48a
[ "Apache-2.0" ]
1
2021-11-23T10:12:35.000Z
2021-11-23T10:12:35.000Z
src/StockIT-v2-release_source_from_JADX/sources/androidx/sqlite/p007db/C0470R.java
atul-vyshnav/2021_IBM_Code_Challenge_StockIT
25c26a4cc59a3f3e575f617b59acc202ee6ee48a
[ "Apache-2.0" ]
null
null
null
src/StockIT-v2-release_source_from_JADX/sources/androidx/sqlite/p007db/C0470R.java
atul-vyshnav/2021_IBM_Code_Challenge_StockIT
25c26a4cc59a3f3e575f617b59acc202ee6ee48a
[ "Apache-2.0" ]
1
2021-10-01T13:14:19.000Z
2021-10-01T13:14:19.000Z
16.625
40
0.676692
3,629
package androidx.sqlite.p007db; /* renamed from: androidx.sqlite.db.R */ public final class C0470R { private C0470R() { } }
3e089022d958150bb9bcc5c9a4813f4ba986a7b7
1,674
java
Java
src/main/java/com/laytonsmith/core/PermissionsResolver.java
Jessassin/commandhelper
270f1e86f10d57e52425382871b6ee26262dbc31
[ "MIT" ]
null
null
null
src/main/java/com/laytonsmith/core/PermissionsResolver.java
Jessassin/commandhelper
270f1e86f10d57e52425382871b6ee26262dbc31
[ "MIT" ]
null
null
null
src/main/java/com/laytonsmith/core/PermissionsResolver.java
Jessassin/commandhelper
270f1e86f10d57e52425382871b6ee26262dbc31
[ "MIT" ]
null
null
null
22.621622
85
0.692354
3,630
package com.laytonsmith.core; /** * A permissions resolver resolves whether a particular user (stored as a string) has * various permissions to do certain things, as well as polling for information * about the user. * @author lsmith */ public interface PermissionsResolver { public static final String GLOBAL_PERMISSION = "*"; /** * Returns true if this user is in the specified group. * @param user * @param group * @return */ boolean inGroup(String user, String group); /** * Returns true if the user has the specified permission. <code>data</code> * is used by the particular instance if more data is needed. * @param user * @param permission * @param data * @return */ boolean hasPermission(String user, String permission, Object data); /** * Returns true if the user has the specified permission. * @param user * @param permission * @return */ boolean hasPermission(String user, String permission); /** * Returns a list of groups the user is in. * @param user * @return */ String[] getGroups(String user); /** * A very permissive resolver, which always returns true for hasPermission. * The "user" isn't in any groups. */ public static class PermissiveResolver implements PermissionsResolver{ @Override public boolean inGroup(String user, String group) { return false; } @Override public boolean hasPermission(String user, String permission, Object data) { return true; } @Override public boolean hasPermission(String user, String permission) { return true; } @Override public String[] getGroups(String user) { return new String[]{}; } } }
3e08903218cf96c32ee49f0eee4b5761eca3c009
2,976
java
Java
raptor/src/main/java/raptor/alias/ShowTagsAlias.java
mipper/raptor-chess-interface
cb4a6af53fa6cc9b60de3b01c4586153447d1ba9
[ "BSD-3-Clause" ]
12
2015-04-07T17:57:23.000Z
2021-03-21T21:40:09.000Z
raptor/src/main/java/raptor/alias/ShowTagsAlias.java
mipper/raptor-chess-interface
cb4a6af53fa6cc9b60de3b01c4586153447d1ba9
[ "BSD-3-Clause" ]
7
2015-06-16T21:37:34.000Z
2021-03-12T18:49:03.000Z
raptor/src/main/java/raptor/alias/ShowTagsAlias.java
mipper/raptor-chess-interface
cb4a6af53fa6cc9b60de3b01c4586153447d1ba9
[ "BSD-3-Clause" ]
6
2016-05-28T23:32:51.000Z
2021-01-25T04:47:46.000Z
45.090909
758
0.726142
3,631
/** * New BSD License * http://www.opensource.org/licenses/bsd-license.php * Copyright 2009-2011 RaptorProject (http://code.google.com/p/raptor-chess-interface/) * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the RaptorProject nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package raptor.alias; import java.util.Arrays; import org.apache.commons.lang.StringUtils; import raptor.service.UserTagService; import raptor.swt.chat.ChatConsoleController; public class ShowTagsAlias extends RaptorAlias { public ShowTagsAlias() { super("=tag", "Shows the all of the users currently tagged.", "=tags"); } @Override public RaptorAliasResult apply(ChatConsoleController controller, String command) { if (command.equalsIgnoreCase("=tag")) { StringBuilder builder = new StringBuilder(1000); String[] tags = UserTagService.getInstance().getTags(); Arrays.sort(tags); builder.append("Available Tags: "); for (String tag : tags) { builder.append(tag).append(" "); } builder.append("\n\nTagged users:\n"); for (String tag : tags) { String[] users = UserTagService.getInstance() .getUsersInTag(tag); if (users.length > 0) { builder.append(tag).append(":\n"); Arrays.sort(users); int counter = 0; for (int i = 0; i < users.length; i++) { builder.append(StringUtils.rightPad(users[i], 20)); counter++; if (counter == 3) { counter = 0; builder.append("\n"); } } builder.append("\n\n"); } } return new RaptorAliasResult(null, builder.toString().trim()); } return null; } }
3e0890ba5e443552958b7071f291cedb1f6e6d9d
7,495
java
Java
src/main/java/lwjgui/util/gdx/RandomXS128.java
C0de5mith/LWJGUI
923a57a13d075f0da44b4a0ed32f014d5166cfef
[ "MIT" ]
123
2018-06-30T04:06:42.000Z
2022-03-29T17:30:32.000Z
src/main/java/lwjgui/util/gdx/RandomXS128.java
C0de5mith/LWJGUI
923a57a13d075f0da44b4a0ed32f014d5166cfef
[ "MIT" ]
21
2018-07-11T18:08:21.000Z
2022-02-28T23:37:30.000Z
src/main/java/lwjgui/util/gdx/RandomXS128.java
C0de5mith/LWJGUI
923a57a13d075f0da44b4a0ed32f014d5166cfef
[ "MIT" ]
26
2018-07-11T17:50:38.000Z
2022-03-29T17:30:34.000Z
37.853535
129
0.678052
3,632
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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 lwjgui.util.gdx; import java.util.Random; /** This class implements the xorshift128+ algorithm that is a very fast, top-quality 64-bit pseudo-random number generator. The * quality of this PRNG is much higher than {@link Random}'s, and its cycle length is 2<sup>128</sup>&nbsp;&minus;&nbsp;1, which * is more than enough for any single-thread application. More details and algorithms can be found <a * href="http://xorshift.di.unimi.it/">here</a>. * <p> * Instances of RandomXS128 are not thread-safe. * * @author Inferno * @author davebaol */ public class RandomXS128 extends Random { /** Normalization constant for double. */ private static final double NORM_DOUBLE = 1.0 / (1L << 53); /** Normalization constant for float. */ private static final double NORM_FLOAT = 1.0 / (1L << 24); /** The first half of the internal state of this pseudo-random number generator. */ private long seed0; /** The second half of the internal state of this pseudo-random number generator. */ private long seed1; /** Creates a new random number generator. This constructor sets the seed of the random number generator to a value very likely * to be distinct from any other invocation of this constructor. * <p> * This implementation creates a {@link Random} instance to generate the initial seed. */ public RandomXS128 () { setSeed(new Random().nextLong()); } /** Creates a new random number generator using a single {@code long} seed. * @param seed the initial seed */ public RandomXS128 (long seed) { setSeed(seed); } /** Creates a new random number generator using two {@code long} seeds. * @param seed0 the first part of the initial seed * @param seed1 the second part of the initial seed */ public RandomXS128 (long seed0, long seed1) { setState(seed0, seed1); } /** Returns the next pseudo-random, uniformly distributed {@code long} value from this random number generator's sequence. * <p> * Subclasses should override this, as this is used by all other methods. */ @Override public long nextLong () { long s1 = this.seed0; final long s0 = this.seed1; this.seed0 = s0; s1 ^= s1 << 23; return (this.seed1 = (s1 ^ s0 ^ (s1 >>> 17) ^ (s0 >>> 26))) + s0; } /** This protected method is final because, contrary to the superclass, it's not used anymore by the other methods. */ @Override protected final int next (int bits) { return (int)(nextLong() & ((1L << bits) - 1)); } /** Returns the next pseudo-random, uniformly distributed {@code int} value from this random number generator's sequence. * <p> * This implementation uses {@link #nextLong()} internally. */ @Override public int nextInt () { return (int)nextLong(); } /** Returns a pseudo-random, uniformly distributed {@code int} value between 0 (inclusive) and the specified value (exclusive), * drawn from this random number generator's sequence. * <p> * This implementation uses {@link #nextLong()} internally. * @param n the positive bound on the random number to be returned. * @return the next pseudo-random {@code int} value between {@code 0} (inclusive) and {@code n} (exclusive). */ @Override public int nextInt (final int n) { return (int)nextLong(n); } /** Returns a pseudo-random, uniformly distributed {@code long} value between 0 (inclusive) and the specified value (exclusive), * drawn from this random number generator's sequence. The algorithm used to generate the value guarantees that the result is * uniform, provided that the sequence of 64-bit values produced by this generator is. * <p> * This implementation uses {@link #nextLong()} internally. * @param n the positive bound on the random number to be returned. * @return the next pseudo-random {@code long} value between {@code 0} (inclusive) and {@code n} (exclusive). */ public long nextLong (final long n) { if (n <= 0) throw new IllegalArgumentException("n must be positive"); for (;;) { final long bits = nextLong() >>> 1; final long value = bits % n; if (bits - value + (n - 1) >= 0) return value; } } /** Returns a pseudo-random, uniformly distributed {@code double} value between 0.0 and 1.0 from this random number generator's * sequence. * <p> * This implementation uses {@link #nextLong()} internally. */ @Override public double nextDouble () { return (nextLong() >>> 11) * NORM_DOUBLE; } /** Returns a pseudo-random, uniformly distributed {@code float} value between 0.0 and 1.0 from this random number generator's * sequence. * <p> * This implementation uses {@link #nextLong()} internally. */ @Override public float nextFloat () { return (float)((nextLong() >>> 40) * NORM_FLOAT); } /** Returns a pseudo-random, uniformly distributed {@code boolean } value from this random number generator's sequence. * <p> * This implementation uses {@link #nextLong()} internally. */ @Override public boolean nextBoolean () { return (nextLong() & 1) != 0; } /** Generates random bytes and places them into a user-supplied byte array. The number of random bytes produced is equal to the * length of the byte array. * <p> * This implementation uses {@link #nextLong()} internally. */ @Override public void nextBytes (final byte[] bytes) { int n = 0; int i = bytes.length; while (i != 0) { n = i < 8 ? i : 8; // min(i, 8); for (long bits = nextLong(); n-- != 0; bits >>= 8) bytes[--i] = (byte)bits; } } /** Sets the internal seed of this generator based on the given {@code long} value. * <p> * The given seed is passed twice through a hash function. This way, if the user passes a small value we avoid the short * irregular transient associated with states having a very small number of bits set. * @param seed a nonzero seed for this generator (if zero, the generator will be seeded with {@link Long#MIN_VALUE}). */ @Override public void setSeed (final long seed) { long seed0 = murmurHash3(seed == 0 ? Long.MIN_VALUE : seed); setState(seed0, murmurHash3(seed0)); } /** Sets the internal state of this generator. * @param seed0 the first part of the internal state * @param seed1 the second part of the internal state */ public void setState (final long seed0, final long seed1) { this.seed0 = seed0; this.seed1 = seed1; } /** * Returns the internal seeds to allow state saving. * @param seed must be 0 or 1, designating which of the 2 long seeds to return * @return the internal seed that can be used in setState */ public long getState(int seed) { return seed == 0 ? seed0 : seed1; } private final static long murmurHash3 (long x) { x ^= x >>> 33; x *= 0xff51afd7ed558ccdL; x ^= x >>> 33; x *= 0xc4ceb9fe1a85ec53L; x ^= x >>> 33; return x; } }
3e0891a0233e24a13423d0696d6856c87e9f2582
250
java
Java
performance/src/main/java/victor/perf/leaks/BigObject200KBApprox.java
AdrianaDinca/training
d8d20aa7db9d26b12f7163a70108e6ea22cc5c50
[ "MIT" ]
null
null
null
performance/src/main/java/victor/perf/leaks/BigObject200KBApprox.java
AdrianaDinca/training
d8d20aa7db9d26b12f7163a70108e6ea22cc5c50
[ "MIT" ]
null
null
null
performance/src/main/java/victor/perf/leaks/BigObject200KBApprox.java
AdrianaDinca/training
d8d20aa7db9d26b12f7163a70108e6ea22cc5c50
[ "MIT" ]
null
null
null
25
62
0.728
3,633
package victor.perf.leaks; import java.util.Date; import java.util.Random; public class BigObject200KBApprox { private static Random r = new Random(); public Date date = new Date(); public int[] largeArray = new int[(40 + r.nextInt(20))*1024]; }
3e089314a21f3f5611a36795ec8b7641de21906f
2,266
java
Java
src/main/java/day1_08_20210401/src/com/atguigu/exer/StudentTest1.java
liguangyuaaa/bigdatajava
607dafb501e26c890c95ebddcef108c113a47a5b
[ "Apache-2.0" ]
null
null
null
src/main/java/day1_08_20210401/src/com/atguigu/exer/StudentTest1.java
liguangyuaaa/bigdatajava
607dafb501e26c890c95ebddcef108c113a47a5b
[ "Apache-2.0" ]
null
null
null
src/main/java/day1_08_20210401/src/com/atguigu/exer/StudentTest1.java
liguangyuaaa/bigdatajava
607dafb501e26c890c95ebddcef108c113a47a5b
[ "Apache-2.0" ]
null
null
null
19.534483
58
0.589585
3,634
package day1_08_20210401.src.com.atguigu.exer; /* * 4. 对象数组题目: 定义类Student,包含三个属性:学号number(int),年级state(int),成绩score(int)。 创建20个学生对象,学号为1到20,年级和成绩都由随机数确定。 问题一:打印出3年级(state值为3)的学生信息。 问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息 提示: 1) 生成随机数:Math.random(),返回值类型double; 2) 四舍五入取整:Math.round(double d),返回值类型long。 * * * 此代码是对StudentTest.java的改进:将操作数组的功能封装到方法中。 * */ public class StudentTest1 { public static void main(String[] args) { //声明Student类型的数组 Student1[] stus = new Student1[20]; for(int i = 0;i < stus.length;i++){ //给数组元素赋值 stus[i] = new Student1(); //给Student对象的属性赋值 stus[i].number = (i + 1); //年级:[1,6] stus[i].state = (int)(Math.random() * (6 - 1 + 1) + 1); //成绩:[0,100] stus[i].score = (int)(Math.random() * (100 - 0 + 1)); } StudentTest1 test = new StudentTest1(); //遍历学生数组 test.print(stus); System.out.println("********************"); //问题一:打印出3年级(state值为3)的学生信息。 test.searchState(stus, 3); System.out.println("********************"); //问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息 test.sort(stus); //遍历学生数组 test.print(stus); } /** * * @Description 遍历Student1[]数组的操作 * @author shkstart * @date 2019年1月15日下午5:10:19 * @param stus */ public void print(Student1[] stus){ for(int i = 0;i <stus.length;i++){ System.out.println(stus[i].info()); } } /** * * @Description 查找Stduent数组中指定年级的学生信息 * @author shkstart * @date 2019年1月15日下午5:08:08 * @param stus 要查找的数组 * @param state 要找的年级 */ public void searchState(Student1[] stus,int state){ for(int i = 0;i <stus.length;i++){ if(stus[i].state == state){ System.out.println(stus[i].info()); } } } /** * * @Description 给Student1数组排序 * @author shkstart * @date 2019年1月15日下午5:09:46 * @param stus */ public void sort(Student1[] stus){ for(int i = 0;i < stus.length - 1;i++){ for(int j = 0;j < stus.length - 1 - i;j++){ if(stus[j].score > stus[j + 1].score){ //如果需要换序,交换的是数组的元素:Student对象!!! Student1 temp = stus[j]; stus[j] = stus[j + 1]; stus[j + 1] = temp; } } } } } class Student1{ int number;//学号 int state;//年级 int score;//成绩 //显示学生信息的方法 public String info(){ return "学号:" + number + ",年级:" + state + ",成绩:" + score; } }
3e0895105f9d45d3e71d7565ac4ffb3c667e1f30
1,776
java
Java
tempest/src/test/java/app/cash/tempest/interop/InteropTestModule.java
JohnFultonian/tempest
6094dbbad97532ba054ab00108f62cb617ce4a05
[ "Apache-2.0" ]
null
null
null
tempest/src/test/java/app/cash/tempest/interop/InteropTestModule.java
JohnFultonian/tempest
6094dbbad97532ba054ab00108f62cb617ce4a05
[ "Apache-2.0" ]
null
null
null
tempest/src/test/java/app/cash/tempest/interop/InteropTestModule.java
JohnFultonian/tempest
6094dbbad97532ba054ab00108f62cb617ce4a05
[ "Apache-2.0" ]
null
null
null
33.509434
75
0.756194
3,635
/* * Copyright 2020 Square 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 app.cash.tempest.interop; import app.cash.tempest.LogicalDb; import app.cash.tempest.urlshortener.java.AliasDb; import app.cash.tempest.urlshortener.java.AliasItem; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.google.inject.Provides; import com.google.inject.Singleton; import kotlin.jvm.internal.Reflection; import misk.MiskTestingServiceModule; import com.google.inject.AbstractModule; import misk.aws.dynamodb.testing.DockerDynamoDbModule; import misk.aws.dynamodb.testing.DynamoDbTable; public class InteropTestModule extends AbstractModule { @Override protected void configure() { install(new MiskTestingServiceModule()); install( new DockerDynamoDbModule( new DynamoDbTable( Reflection.createKotlinClass(AliasItem.class), (createTableRequest) -> createTableRequest ) ) ); } @Provides @Singleton AliasDb provideJAliasDb(AmazonDynamoDB amazonDynamoDB) { var dynamoDbMapper = new DynamoDBMapper(amazonDynamoDB); return LogicalDb.create(AliasDb.class, dynamoDbMapper); } }
3e0895934b8f96f4a175d596d073683106811312
5,159
java
Java
Mage.Sets/src/mage/cards/o/OpalPalace.java
Emigara/mage
2783199b735b35c718db3bff85a3505793920ca9
[ "MIT" ]
2
2020-04-04T22:36:47.000Z
2020-04-04T22:57:35.000Z
Mage.Sets/src/mage/cards/o/OpalPalace.java
Emigara/mage
2783199b735b35c718db3bff85a3505793920ca9
[ "MIT" ]
43
2020-07-27T06:53:24.000Z
2022-03-28T23:03:21.000Z
Mage.Sets/src/mage/cards/o/OpalPalace.java
Emigara/mage
2783199b735b35c718db3bff85a3505793920ca9
[ "MIT" ]
2
2020-01-30T01:09:39.000Z
2020-02-20T02:08:24.000Z
35.57931
272
0.657298
3,636
package mage.cards.o; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.costs.common.TapSourceCost; import mage.abilities.costs.mana.GenericManaCost; import mage.abilities.effects.ReplacementEffectImpl; import mage.abilities.mana.ColorlessManaAbility; import mage.abilities.mana.CommanderColorIdentityManaAbility; import mage.cards.Card; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.*; import mage.counters.CounterType; import mage.game.Game; import mage.game.events.EntersTheBattlefieldEvent; import mage.game.events.GameEvent; import mage.game.events.GameEvent.EventType; import mage.game.permanent.Permanent; import mage.game.stack.Spell; import mage.players.Player; import mage.watchers.Watcher; import mage.watchers.common.CommanderPlaysCountWatcher; import java.util.ArrayList; import java.util.List; import java.util.UUID; /** * @author LevelX2 */ public final class OpalPalace extends CardImpl { public OpalPalace(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.LAND}, ""); // {T}: Add {C}. this.addAbility(new ColorlessManaAbility()); // {1}, {tap}: Add one mana of any color in your commander's color identity. If you spend this mana to cast your commander, it enters the battlefield with a number of +1/+1 counters on it equal to the number of times it's been cast from the command zone this game. Ability ability = new CommanderColorIdentityManaAbility(new GenericManaCost(1)); ability.addCost(new TapSourceCost()); this.addAbility(ability, new OpalPalaceWatcher(ability.getOriginalId().toString())); ability = new SimpleStaticAbility(Zone.ALL, new OpalPalaceEntersBattlefieldEffect()); ability.setRuleVisible(false); this.addAbility(ability); } public OpalPalace(final OpalPalace card) { super(card); } @Override public OpalPalace copy() { return new OpalPalace(this); } } class OpalPalaceWatcher extends Watcher { private List<UUID> commanderId = new ArrayList<>(); private final String originalId; public OpalPalaceWatcher(String originalId) { super(WatcherScope.CARD); this.originalId = originalId; } public boolean manaUsedToCastCommander(UUID id){ return commanderId.contains(id); } @Override public void watch(GameEvent event, Game game) { if (event.getType() == GameEvent.EventType.MANA_PAID) { if (event.getData() != null && event.getData().equals(originalId)) { Spell spell = game.getStack().getSpell(event.getTargetId()); if (spell != null) { Card card = spell.getCard(); if (card != null) { for (UUID playerId : game.getPlayerList()) { Player player = game.getPlayer(playerId); if (player != null) { if (game.getCommandersIds(player).contains(card.getId())) { commanderId.add(card.getId()); break; } } } } } } } } @Override public void reset() { super.reset(); commanderId.clear(); } } class OpalPalaceEntersBattlefieldEffect extends ReplacementEffectImpl { public OpalPalaceEntersBattlefieldEffect() { super(Duration.EndOfGame, Outcome.BoostCreature, false); staticText = "If you spend this mana to cast your commander, it enters the battlefield with a number of +1/+1 counters on it equal to the number of times it's been cast from the command zone this game"; } private OpalPalaceEntersBattlefieldEffect(OpalPalaceEntersBattlefieldEffect effect) { super(effect); } @Override public boolean checksEventType(GameEvent event, Game game) { return event.getType() == EventType.ENTERS_THE_BATTLEFIELD; } @Override public boolean applies(GameEvent event, Ability source, Game game) { OpalPalaceWatcher watcher = game.getState().getWatcher(OpalPalaceWatcher.class, source.getSourceId()); return watcher != null && watcher.manaUsedToCastCommander(event.getTargetId()); } @Override public boolean replaceEvent(GameEvent event, Ability source, Game game) { Permanent permanent = ((EntersTheBattlefieldEvent) event).getTarget(); if (permanent != null) { CommanderPlaysCountWatcher watcher = game.getState().getWatcher(CommanderPlaysCountWatcher.class); int castCount = watcher.getPlaysCount(permanent.getId()); if (castCount > 0) { permanent.addCounters(CounterType.P1P1.createInstance(castCount), source, game); } } return false; } @Override public OpalPalaceEntersBattlefieldEffect copy() { return new OpalPalaceEntersBattlefieldEffect(this); } }
3e08960c07599a9cd2c3886b054daf256ee582e1
1,133
java
Java
app/src/main/java/com/assignment/speedchecker/util/progressloading/indicators/LineScalePulseOutRapidIndicator.java
arunmobiledev/SpeedChecker
3b4fd10217c2ba3cff7aa210d018867e5b0f365f
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/assignment/speedchecker/util/progressloading/indicators/LineScalePulseOutRapidIndicator.java
arunmobiledev/SpeedChecker
3b4fd10217c2ba3cff7aa210d018867e5b0f365f
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/assignment/speedchecker/util/progressloading/indicators/LineScalePulseOutRapidIndicator.java
arunmobiledev/SpeedChecker
3b4fd10217c2ba3cff7aa210d018867e5b0f365f
[ "Apache-2.0" ]
null
null
null
31.472222
84
0.619594
3,637
package com.assignment.speedchecker.util.progressloading.indicators; import android.animation.ValueAnimator; import java.util.ArrayList; /** * Created by Jack on 2015/10/19. */ public class LineScalePulseOutRapidIndicator extends LineScaleIndicator { @Override public ArrayList<ValueAnimator> onCreateAnimators() { ArrayList<ValueAnimator> animators=new ArrayList<>(); long[] delays=new long[]{400,200,0,200,400}; for (int i = 0; i < 5; i++) { final int index=i; ValueAnimator scaleAnim=ValueAnimator.ofFloat(1,0.4f,1); scaleAnim.setDuration(1000); scaleAnim.setRepeatCount(-1); scaleAnim.setStartDelay(delays[i]); addUpdateListener(scaleAnim,new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { scaleYFloats[index] = (float) animation.getAnimatedValue(); postInvalidate(); } }); animators.add(scaleAnim); } return animators; } }
3e08963fea52ac73b578c05ffa22dc6af520fd8f
2,378
java
Java
src/graph/ReconstructItinerary.java
gitmichaelz/LeetCodeByTags
0a1ce6deff430271909ecd3b7346cd1d54844b7a
[ "Apache-2.0" ]
null
null
null
src/graph/ReconstructItinerary.java
gitmichaelz/LeetCodeByTags
0a1ce6deff430271909ecd3b7346cd1d54844b7a
[ "Apache-2.0" ]
null
null
null
src/graph/ReconstructItinerary.java
gitmichaelz/LeetCodeByTags
0a1ce6deff430271909ecd3b7346cd1d54844b7a
[ "Apache-2.0" ]
null
null
null
44.867925
259
0.671993
3,638
package graph; import java.util.*; /** * You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. * * All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. * * For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"]. * * You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once. * * * * Example 1: * * Input: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]] * Output: ["JFK","MUC","LHR","SFO","SJC"] */ public class ReconstructItinerary { //这个题是欧拉路径(Eulerian path),即在有环的情况下,如何恰好只走过每一条边然后经过每一个点(点可以重复访问,路径只能走一遍。路径是有方向的)visits every edge exactly once (allowing for revisiting vertices)。比如图的形状是"6"这样的,假设需要从环跟分叉的交点开始出发,我们一直按照贪心dfs,即从该点走字典路径最小的路径,如果走到某个dead end, 走不下去了,这说明该点一定是所有遍历的终点,我们逆序把他加到结果集。然后 //回溯到父节点,继续这样的走法。需要注意的是,走过的路径需要删除,以免重复访问。 //参考 https://www.youtube.com/watch?v=4udFSOWQpdg 花花视频下面的评论 //以及 https://www.youtube.com/watch?v=kZXsB3WemYY public List<String> findItinerary(List<List<String>> tickets) { LinkedList<String> res = new LinkedList<>(); Map<String, PriorityQueue<String>> graph = new HashMap<>();//因为需要按字典序最小的路径,所以用PQ buildGraph(tickets, graph); dfs(graph, "JFK", res); return res; } private void dfs(Map<String, PriorityQueue<String>> graph, String from, LinkedList<String> res) { PriorityQueue<String> destinations = graph.get(from); while(destinations != null && !destinations.isEmpty()) { String to = destinations.poll();//poll(),删除走过的路径,以免回溯到父节点重复访问。 dfs(graph, to, res); } res.addFirst(from); } private void buildGraph(List<List<String>> tickets, Map<String, PriorityQueue<String>> graph) { for(List<String> ticket : tickets) { String from = ticket.get(0); String to = ticket.get(1); PriorityQueue<String> destinations = graph.computeIfAbsent(from, k -> new PriorityQueue<>()); destinations.offer(to); } } }
3e08965694a6a2f49bbe54a0de323e7b5c673627
5,901
java
Java
app/src/main/java/net/validcat/fishing/ListActivity.java
lamrak/Capstone-Projec
0ca7c69a393e29766b88720469899b884876aeb7
[ "MIT" ]
null
null
null
app/src/main/java/net/validcat/fishing/ListActivity.java
lamrak/Capstone-Projec
0ca7c69a393e29766b88720469899b884876aeb7
[ "MIT" ]
null
null
null
app/src/main/java/net/validcat/fishing/ListActivity.java
lamrak/Capstone-Projec
0ca7c69a393e29766b88720469899b884876aeb7
[ "MIT" ]
null
null
null
40.417808
132
0.635486
3,639
package net.validcat.fishing; import android.Manifest; import android.app.ActivityOptions; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.util.Pair; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import net.validcat.fishing.data.Constants; import net.validcat.fishing.fragments.ListFragment; import butterknife.Bind; import butterknife.ButterKnife; public class ListActivity extends AppCompatActivity implements ListFragment.IClickListener { public static final String LOG_TAG = ListActivity.class.getSimpleName(); public static final String KEY_CLICKED_FRAGMENT = "clicked_fragment"; public static final String F_DETAIL_TAG = "detail_fragment"; @Bind(R.id.fab_add_fishing) FloatingActionButton fabAddFishing; private boolean isTwoPanel; private static final String TAG = "detail_fragment"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list_activity); ButterKnife.bind(this); if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { Log.d(LOG_TAG, "WRITE_EXTERNAL_STORAGE is not granted"); // Should we show an explanation? if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { Log.d(LOG_TAG, "WRITE_EXTERNAL_STORAGE is requested"); ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, Constants.PERMISSIONS_REQUEST_WRITE_STORAGE); // } } } fabAddFishing.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivityForResult(new Intent(ListActivity.this, AddNewFishingActivity.class), Constants.ITEM_REQUEST); } }); // if (findViewById(R.id.detail_fragment) != null) { // isTwoPanel = true; // if (savedInstanceState == null) { // getSupportFragmentManager().beginTransaction() // .replace(R.id.detail_container, new DetailFragment(), F_DETAIL_TAG) // .commit(); // // ListFragment lf = (ListFragment) getSupportFragmentManager() // .findFragmentById(R.id.list_fragment); // //lf.setUseTabLayout(!twoPane); // } // } else { // getSupportFragmentManager().beginTransaction() // .add(R.id.fragment_movies, new ListFragment()) // .commit(); isTwoPanel = false; getSupportActionBar().setElevation(0f); // } // getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS); // Transition transition = getWindow().setSharedElementEnterTransition(transition); // getWindow().setSharedElementExitTransition(transition); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { switch (requestCode) { case Constants.PERMISSIONS_REQUEST_WRITE_STORAGE: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { } else { Toast.makeText(this, R.string.storage_permissoin_denied, Toast.LENGTH_SHORT).show(); } break; } } } @Override public void onItemClicked(long clickedItemId, View... sharedView) { // if (isTwoPanel) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { startActivity(new Intent(ListActivity.this, DetailActivity.class) .putExtra(Constants.DETAIL_KEY, clickedItemId), ActivityOptions.makeSceneTransitionAnimation(this, new Pair<>(sharedView[0], sharedView[0].getTransitionName()), new Pair<>(sharedView[1], sharedView[1].getTransitionName()), new Pair<>(sharedView[2], sharedView[2].getTransitionName())).toBundle()); } else startActivity(new Intent(ListActivity.this, DetailActivity.class).putExtra(Constants.DETAIL_KEY, clickedItemId)); // } else { // Bundle args = new Bundle(); // args.putLong(KEY_CLICKED_FRAGMENT, clickedItemId); // // Fragment df = new DetailFragment(); // df.setArguments(args); // getSupportFragmentManager().beginTransaction().replace(R.id.detail_container, df, TAG).commit(); // } } public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main_list, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.action_settings: startActivity(new Intent(this, SettingsActivity.class)); break; default: break; } return super.onOptionsItemSelected(menuItem); } }
3e0896ab083a755b7a20086433897c1cbec26b7b
633
java
Java
src/main/java/me/spazzylemons/toastersimulator/mixin/client/BipedArmorLayerMixin.java
spazzylemons/ToasterSimulator
a71ffc5b3a493cee1ef2547c988d8419d67c844b
[ "MIT" ]
1
2021-05-14T20:37:06.000Z
2021-05-14T20:37:06.000Z
src/main/java/me/spazzylemons/toastersimulator/mixin/client/BipedArmorLayerMixin.java
spazzylemons/ToasterSimulator
a71ffc5b3a493cee1ef2547c988d8419d67c844b
[ "MIT" ]
null
null
null
src/main/java/me/spazzylemons/toastersimulator/mixin/client/BipedArmorLayerMixin.java
spazzylemons/ToasterSimulator
a71ffc5b3a493cee1ef2547c988d8419d67c844b
[ "MIT" ]
null
null
null
31.65
88
0.810427
3,640
package me.spazzylemons.toastersimulator.mixin.client; import net.minecraft.client.renderer.entity.layers.BipedArmorLayer; import net.minecraft.client.renderer.entity.model.BipedModel; import net.minecraft.entity.LivingEntity; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; @OnlyIn(Dist.CLIENT) @Mixin(BipedArmorLayer.class) public interface BipedArmorLayerMixin<T extends LivingEntity, A extends BipedModel<T>> { @Accessor A getInnerModel(); @Accessor A getOuterModel(); }
3e08974935ca37bd0019ba448c7e026947fdcfa7
4,102
java
Java
src/main/java/com/hemant/jlambda/model/LambdaConfig.java
hemantgs/jlambda
fb5c2de0d28e92326f59da3edb035c8170cb8dd7
[ "Apache-2.0" ]
1
2020-10-03T04:31:53.000Z
2020-10-03T04:31:53.000Z
src/main/java/com/hemant/jlambda/model/LambdaConfig.java
hemantgs/jlambda
fb5c2de0d28e92326f59da3edb035c8170cb8dd7
[ "Apache-2.0" ]
5
2020-10-02T17:17:50.000Z
2020-10-31T13:03:46.000Z
src/main/java/com/hemant/jlambda/model/LambdaConfig.java
hemantgs/jlambda
fb5c2de0d28e92326f59da3edb035c8170cb8dd7
[ "Apache-2.0" ]
4
2020-10-03T14:58:40.000Z
2020-10-20T15:00:21.000Z
22.662983
77
0.655046
3,641
/* * Copyright 2020 hemantgs * * 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.hemant.jlambda.model; public class LambdaConfig { private String name; private String executionRole; private String awsAccessKey; private String awsAccessSecret; private String profile; private String handler; private String region; private String memory; private String timeout = "60"; private String runTimeout = "3"; private String description; private String version; private String vpcSubnets; private String vpcSecurityGroups; private String tracingConfig; private String logRetentionDays; private String layers; public String getLayers() { return layers; } public void setLayers(String layers) { this.layers = layers; } public String getTimeout() { return timeout; } public void setTimeout(String timeout) { this.timeout = timeout; } public String getRunTimeout() { return runTimeout; } public void setRunTimeout(String runTimeout) { this.runTimeout = runTimeout; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getVpcSubnets() { return vpcSubnets; } public void setVpcSubnets(String vpcSubnets) { this.vpcSubnets = vpcSubnets; } public String getVpcSecurityGroups() { return vpcSecurityGroups; } public void setVpcSecurityGroups(String vpcSecurityGroups) { this.vpcSecurityGroups = vpcSecurityGroups; } public String getTracingConfig() { return tracingConfig; } public void setTracingConfig(String tracingConfig) { this.tracingConfig = tracingConfig; } public String getLogRetentionDays() { return logRetentionDays; } public void setLogRetentionDays(String logRetentionDays) { this.logRetentionDays = logRetentionDays; } public String getMemory() { return memory; } public void setMemory(String memory) { this.memory = memory; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public String getHandler() { return handler; } public void setHandler(String handler) { this.handler = handler; } public String getProfile() { return profile; } public void setProfile(String profile) { this.profile = profile; } public String getAwsAccessKey() { return awsAccessKey; } public void setAwsAccessKey(String awsAccessKey) { this.awsAccessKey = awsAccessKey; } public String getAwsAccessSecret() { return awsAccessSecret; } public void setAwsAccessSecret(String awsAccessSecret) { this.awsAccessSecret = awsAccessSecret; } public LambdaConfig(String name) { this.name = name; } public LambdaConfig() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getExecutionRole() { return executionRole; } public void setExecutionRole(String executionRole) { this.executionRole = executionRole; } }
3e0898951c1d4ab0286e10f4465eb11b6c1e786b
786
java
Java
Capsloc/src/main/java/com/brentonbostick/capsloc/world/cars/Engine.java
bostick/Deadlock
da3b86ff878b337d5dd6d50b09096f89aa9e940d
[ "MIT" ]
null
null
null
Capsloc/src/main/java/com/brentonbostick/capsloc/world/cars/Engine.java
bostick/Deadlock
da3b86ff878b337d5dd6d50b09096f89aa9e940d
[ "MIT" ]
null
null
null
Capsloc/src/main/java/com/brentonbostick/capsloc/world/cars/Engine.java
bostick/Deadlock
da3b86ff878b337d5dd6d50b09096f89aa9e940d
[ "MIT" ]
null
null
null
25.354839
52
0.824427
3,642
package com.brentonbostick.capsloc.world.cars; import com.brentonbostick.capsloc.world.World; public abstract class Engine { public double maxSpeed; protected double maxRadsPerMeter; protected double maxAcceleration; protected double frictionForwardImpulseCoefficient; protected double frictionLateralImpulseCoefficient; protected double frictionAngularImpulseCoefficient; protected double driveForwardImpulseCoefficient; protected double driveLateralImpulseCoefficient; protected double brakeForwardImpulseCoefficient; protected double brakeLateralImpulseCoefficient; protected double turnAngularImpulseCoefficient; World world; Car c; protected Engine(World world, Car c) { this.world = world; this.c = c; } public abstract void preStep(double t); }
3e08999d940f8fce072d31d8cf1b33bc16c72af3
2,494
java
Java
app/src/main/java/com/amadeus/feelens/ProfileActivity.java
ProjectAmadeus/amadeus
92339da3af73647a574b35716d40d382c5def74c
[ "Apache-2.0" ]
3
2018-10-07T19:16:21.000Z
2018-10-08T17:42:34.000Z
app/src/main/java/com/amadeus/feelens/ProfileActivity.java
ProjectAmadeus/amadeus
92339da3af73647a574b35716d40d382c5def74c
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/amadeus/feelens/ProfileActivity.java
ProjectAmadeus/amadeus
92339da3af73647a574b35716d40d382c5def74c
[ "Apache-2.0" ]
null
null
null
30.414634
103
0.684844
3,643
package com.amadeus.feelens; import android.content.Intent; import android.media.Image; import android.support.annotation.NonNull; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import com.amadeus.feelens.adapters.MyPagerAdapter; import com.firebase.ui.auth.AuthUI; import com.google.android.gms.tasks.OnCompleteListener; import com.google.firebase.auth.FirebaseAuth; //TODO: Remover os fragmentos ja estabelecidos e implementar as novas convencoes de design com CardView public class ProfileActivity extends AppCompatActivity { private TabLayout tabLayout; private ViewPager viewPager; private ImageButton btnBack, btnSettings; private Button btnSignOut; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); // Configuração dos botões superiores btnBack = (ImageButton)findViewById(R.id.imgBtnBack); btnSettings = (ImageButton)findViewById(R.id.imgBtnSettings); btnSignOut = (Button)findViewById(R.id.btnSignOut); // Botão para voltar btnBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(ProfileActivity.this, MainActivity.class); ProfileActivity.this.startActivity(i); } }); // Botão para ir às configurações btnSettings.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Intent i = new Intent(ProfileActivity.this, SettingsActivity.class); // ProfileActivity.this.startActivity(i); } }); //Botão para deslogar btnSignOut.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { signOut(); } }); } public void signOut() { FirebaseAuth.getInstance().signOut(); //Redireciona para a tela de login Intent returnToLogin = new Intent(ProfileActivity.this, LoginActivity.class); ProfileActivity.this.startActivity(returnToLogin); } }
3e089adfddeadb9357bd246c23797f1007d848cf
1,430
java
Java
sample2/src/main/java/com/example/sample2/MainActivity.java
iNdieboyjeff/ViewPagerIndicatorExtensions
4363c1dd0e7ef74098fcb232e0d4c552e3b8eee8
[ "Apache-2.0" ]
1
2015-07-24T02:08:49.000Z
2015-07-24T02:08:49.000Z
sample2/src/main/java/com/example/sample2/MainActivity.java
iNdieboyjeff/ViewPagerIndicatorExtensions
4363c1dd0e7ef74098fcb232e0d4c552e3b8eee8
[ "Apache-2.0" ]
null
null
null
sample2/src/main/java/com/example/sample2/MainActivity.java
iNdieboyjeff/ViewPagerIndicatorExtensions
4363c1dd0e7ef74098fcb232e0d4c552e3b8eee8
[ "Apache-2.0" ]
null
null
null
35.75
90
0.755944
3,644
package com.example.sample2; import android.graphics.Color; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.view.View; import android.view.Menu; import android.view.MenuItem; import util.android.textviews.TypefaceSpan; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); setActionBarTitle(); } private void setActionBarTitle() { if (getSupportActionBar() == null) return; TypefaceSpan span = new TypefaceSpan(this, "Audiowide-Regular"); ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.CYAN); SpannableString title = new SpannableString("ViewPagerIndicator2"); title.setSpan(span, 0, title.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); title.setSpan(colorSpan, 9, title.length()-1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); getSupportActionBar().setTitle(title); } }
3e089aebdc12be528c0216c036a39c565e1d1e9e
2,120
java
Java
ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/aspect/MetricsLog.java
onap/portal-sdk
dcdf1bb1838de59e16c63ab37b29fb913efe2f69
[ "Apache-2.0", "CC-BY-4.0" ]
2
2021-07-29T08:00:40.000Z
2021-10-15T16:42:33.000Z
ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/aspect/MetricsLog.java
onap/portal-sdk
dcdf1bb1838de59e16c63ab37b29fb913efe2f69
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/logging/aspect/MetricsLog.java
onap/portal-sdk
dcdf1bb1838de59e16c63ab37b29fb913efe2f69
[ "Apache-2.0", "CC-BY-4.0" ]
2
2019-12-04T08:06:59.000Z
2021-07-29T08:01:11.000Z
42.4
77
0.666509
3,645
/* * ============LICENSE_START========================================== * ONAP Portal SDK * =================================================================== * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * =================================================================== * * Unless otherwise specified, all software contained herein is licensed * under the Apache License, Version 2.0 (the "License"); * you may not use this software 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. * * Unless otherwise specified, all documentation contained herein is licensed * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); * you may not use this documentation except in compliance with the License. * You may obtain a copy of the License at * * https://creativecommons.org/licenses/by/4.0/ * * Unless required by applicable law or agreed to in writing, documentation * 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. * * ============LICENSE_END============================================ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. */ package org.onap.portalsdk.core.logging.aspect; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface MetricsLog { String value() default ""; }
3e089b60d389e66a360846c582bba486ecbfc7fa
1,360
java
Java
java/src/main/java/TennisGame2.java
joshiash/Tennis-Refactoring-Kata
c9738219c47c54ea86d4f336cb0334a256c80d63
[ "MIT" ]
null
null
null
java/src/main/java/TennisGame2.java
joshiash/Tennis-Refactoring-Kata
c9738219c47c54ea86d4f336cb0334a256c80d63
[ "MIT" ]
null
null
null
java/src/main/java/TennisGame2.java
joshiash/Tennis-Refactoring-Kata
c9738219c47c54ea86d4f336cb0334a256c80d63
[ "MIT" ]
null
null
null
29.565217
93
0.6
3,646
import static java.lang.Math.abs; public class TennisGame2 implements TennisGame { private int p1Point; private int p2Point; final private String player1Name; final private String player2Name; private static final String[] SCORE = new String[]{"Love", "Fifteen", "Thirty", "Forty"}; public TennisGame2(String player1Name, String player2Name) { this.player1Name = player1Name; this.player2Name = player2Name; } public String getScore(){ if (p1Point == p2Point) { return getScoreForEqual(p1Point); } if(p1Point >= 4 || p2Point >= 4) { return getScoreAdvantageOrWin(p1Point, p2Point); } return SCORE[p1Point] + "-" + SCORE[p2Point]; } private String getScoreAdvantageOrWin(int p1Point, int p2Point) { final int pointDiff = p1Point - p2Point; String player = pointDiff > 0 ? player1Name : player2Name; String text = abs(pointDiff) >= 2 ? "Win for " : "Advantage "; return text + player; } private static String getScoreForEqual(final int point) { if (point >= 3) { return "Deuce"; } return SCORE[point] + "-All"; } public void wonPoint(String player) { if (player == player1Name) p1Point++; else p2Point++; } }
3e089db5125c7d415c3880eed73ded3cbf868fe7
1,766
java
Java
ExtractedJars/Shopkick_com.shopkick.app/javafiles/com/appscend/media/APSMediaPlayer$11.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
3
2019-05-01T09:22:08.000Z
2019-07-06T22:21:59.000Z
ExtractedJars/Shopkick_com.shopkick.app/javafiles/com/appscend/media/APSMediaPlayer$11.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
null
null
null
ExtractedJars/Shopkick_com.shopkick.app/javafiles/com/appscend/media/APSMediaPlayer$11.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
1
2020-11-26T12:22:02.000Z
2020-11-26T12:22:02.000Z
30.448276
74
0.58607
3,647
// 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.appscend.media; import com.appscend.media.events.APSMediaEvent; // Referenced classes of package com.appscend.media: // APSMediaPlayer class APSMediaPlayer$11 implements Runnable { public void run() { APSMediaEvent apsmediaevent = val$event; // 0 0:aload_0 // 1 1:getfield #23 <Field APSMediaEvent val$event> // 2 4:astore_1 apsmediaevent.preloadPoint = val$currentPlaybackTime; // 3 5:aload_1 // 4 6:aload_0 // 5 7:getfield #25 <Field int val$currentPlaybackTime> // 6 10:i2l // 7 11:putfield #36 <Field long APSMediaEvent.preloadPoint> apsmediaevent.preload(); // 8 14:aload_1 // 9 15:invokevirtual #39 <Method void APSMediaEvent.preload()> // 10 18:return } final APSMediaPlayer this$0; final int val$currentPlaybackTime; final APSMediaEvent val$event; APSMediaPlayer$11() { this$0 = final_apsmediaplayer; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #21 <Field APSMediaPlayer this$0> val$event = apsmediaevent; // 3 5:aload_0 // 4 6:aload_2 // 5 7:putfield #23 <Field APSMediaEvent val$event> val$currentPlaybackTime = I.this; // 6 10:aload_0 // 7 11:iload_3 // 8 12:putfield #25 <Field int val$currentPlaybackTime> super(); // 9 15:aload_0 // 10 16:invokespecial #28 <Method void Object()> // 11 19:return } }
3e089ecd61c02a036bdfd3ee8e3a27ae9cb60c14
3,477
java
Java
ws-services/src/main/java/org/dcm/services/model/FieldDescriptor.java
mhapanow/iseries-ws
dfab8c9f70ce5f4bb426be1b3a9b89dae4a2375a
[ "Apache-2.0" ]
null
null
null
ws-services/src/main/java/org/dcm/services/model/FieldDescriptor.java
mhapanow/iseries-ws
dfab8c9f70ce5f4bb426be1b3a9b89dae4a2375a
[ "Apache-2.0" ]
null
null
null
ws-services/src/main/java/org/dcm/services/model/FieldDescriptor.java
mhapanow/iseries-ws
dfab8c9f70ce5f4bb426be1b3a9b89dae4a2375a
[ "Apache-2.0" ]
null
null
null
19.868571
128
0.673282
3,648
package org.dcm.services.model; import java.io.Serializable; public class FieldDescriptor implements Serializable, IArray { private static final long serialVersionUID = 1L; public static final String TYPE_CHAR = "CHAR"; public static final String TYPE_ARRAY = "ARRAY"; public static final String TYPE_ZONED = "ZONED"; private String iSeriesName; private String iSeriesDescription; private String jsonName; private String type; private IArray arrayOf; private int length; private int decimals; public FieldDescriptor() { super(); } public FieldDescriptor(String iSeriesName, String iSeriesDescription, String jsonName, String type, int length, int decimals) { super(); this.iSeriesName = iSeriesName; this.iSeriesDescription = iSeriesDescription; this.jsonName = jsonName; this.type = type; this.length = length; this.decimals = decimals; } /** * @return the iSeriesName */ public String getiSeriesName() { return iSeriesName; } /** * @param iSeriesName the iSeriesName to set */ public void setiSeriesName(String iSeriesName) { this.iSeriesName = iSeriesName; } /** * @return the iSeriesDescription */ public String getiSeriesDescription() { return iSeriesDescription; } /** * @param iSeriesDescription the iSeriesDescription to set */ public void setiSeriesDescription(String iSeriesDescription) { this.iSeriesDescription = iSeriesDescription; } /** * @return the jsonName */ public String getJsonName() { return jsonName; } /** * @param jsonName the jsonName to set */ public void setJsonName(String jsonName) { this.jsonName = jsonName; } /** * @return the type */ public String getType() { return type; } /** * @param type the type to set */ public void setType(String type) { this.type = type; } /** * @return the length */ public int getLength() { return length; } /** * @param length the length to set */ public void setLength(int length) { this.length = length; } /** * @return the decimals */ public int getDecimals() { return decimals; } /** * @param decimals the decimals to set */ public void setDecimals(int decimals) { this.decimals = decimals; } /** * @return the arrayOf */ public IArray getArrayOf() { return arrayOf; } /** * @param arrayOf the arrayOf to set */ public void setArrayOf(IArray arrayOf) { this.arrayOf = arrayOf; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((iSeriesName == null) ? 0 : iSeriesName.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FieldDescriptor other = (FieldDescriptor) obj; if (iSeriesName == null) { if (other.iSeriesName != null) return false; } else if (!iSeriesName.equals(other.iSeriesName)) return false; return true; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "FieldDescriptor [iSeriesName=" + iSeriesName + ", iSeriesDescription=" + iSeriesDescription + ", jsonName=" + jsonName + ", type=" + type + ", arrayOf=" + arrayOf + ", length=" + length + ", decimals=" + decimals + "]"; } }
3e089f80983ebd7f1810fc9fedefb17f0f550922
2,229
java
Java
AlgorithmJavaVersion/src/DataStructure/stackHeapQueue/queue/LinkedQueuelj.java
ljfirst/Practice-in-Algorithm
88fddd36150abf7bc86fc842c8c66309a7e9b587
[ "Apache-2.0" ]
17
2019-11-09T10:56:22.000Z
2022-03-24T12:22:36.000Z
AlgorithmJavaVersion/src/DataStructure/stackHeapQueue/queue/LinkedQueuelj.java
ljfirst/Practice-in-Algorithm
88fddd36150abf7bc86fc842c8c66309a7e9b587
[ "Apache-2.0" ]
1
2021-08-04T08:25:14.000Z
2021-08-04T08:25:14.000Z
AlgorithmJavaVersion/src/DataStructure/stackHeapQueue/queue/LinkedQueuelj.java
ljfirst/Practice-in-Algorithm
88fddd36150abf7bc86fc842c8c66309a7e9b587
[ "Apache-2.0" ]
5
2019-01-09T06:06:42.000Z
2019-10-21T07:36:54.000Z
21.490385
54
0.531544
3,649
package DataStructure.stackHeapQueue.queue; import DataStructure.arrayANDlist.list.Nodelj; /** * @author liujun * @version 1.0 * @date 2019-11-09 22:56 * @author-Email [email protected] * @description 链队列 */ public class LinkedQueuelj implements Queuelj { public int queueRealsize; public int queueMaxsize; public Nodelj front; public Nodelj tail; public LinkedQueuelj() { //默认初始值为32 this.queueMaxsize = 32; new LinkedQueuelj(queueMaxsize); } public LinkedQueuelj(int num) { this.queueRealsize = 0; this.queueMaxsize = num; this.front = this.tail = null; } @Override public boolean offer(int value) { //队空判断 if (this.queueRealsize == this.queueMaxsize) { resize(); } Nodelj linkedQueueNode = new Nodelj(value); if (this.queueRealsize == 0) { this.front = linkedQueueNode; } else { this.tail.next = linkedQueueNode; } this.tail = linkedQueueNode; this.queueRealsize++; return true; } @Override public int poll() { int value = Integer.MIN_VALUE; //判空 if (!empty()) { value = this.front.value; this.front = front.next; this.queueRealsize--; } return value; } @Override public int peek() { int value = Integer.MIN_VALUE; //判空 if (!empty()) { value = this.front.value; } return value; } @Override public int getRealsize() { return this.queueRealsize; } @Override public int getMaxsize() { return this.queueMaxsize; } @Override public void resize() { this.queueMaxsize <<= 1; } @Override public boolean search(int x) { if (!empty()) { Nodelj node = this.front; while (node.next != null) { if (node.value == x) { return true; } node = node.next; } } return false; } @Override public boolean empty() { return this.queueRealsize == 0; } }
3e089f8bf7e3b67a8acab0ef8ad96429ecf96f59
3,795
java
Java
weevent-client/src/main/java/com/webank/weevent/sdk/jsonrpc/IBrokerRpc.java
jackqqxu/WeEvent
be9772e2a465123078a9443b136425a9018a218c
[ "Apache-2.0" ]
1
2019-11-10T17:25:56.000Z
2019-11-10T17:25:56.000Z
weevent-client/src/main/java/com/webank/weevent/sdk/jsonrpc/IBrokerRpc.java
bgazmend/WeEvent
48b03b13cafafca9cbf43d94fa2b8e175b34190d
[ "Apache-2.0" ]
null
null
null
weevent-client/src/main/java/com/webank/weevent/sdk/jsonrpc/IBrokerRpc.java
bgazmend/WeEvent
48b03b13cafafca9cbf43d94fa2b8e175b34190d
[ "Apache-2.0" ]
null
null
null
39.123711
123
0.650856
3,650
package com.webank.weevent.sdk.jsonrpc; import java.util.List; import java.util.Map; import com.webank.weevent.sdk.BrokerException; import com.webank.weevent.sdk.SendResult; import com.webank.weevent.sdk.TopicInfo; import com.webank.weevent.sdk.TopicPage; import com.webank.weevent.sdk.WeEvent; import com.googlecode.jsonrpc4j.JsonRpcParam; import com.googlecode.jsonrpc4j.JsonRpcService; /** * Interface for RpcJson. * It's different from java interface, do not extends directly. * * @author matthewliu * @since 2018/11/21 */ @JsonRpcService("/jsonrpc") public interface IBrokerRpc { // Interface for producer. default SendResult publish(@JsonRpcParam(value = "topic") String topic, @JsonRpcParam(value = "groupId") String groupId, @JsonRpcParam(value = "content") byte[] content, @JsonRpcParam(value = "extensions") Map<String, String> extensions) throws BrokerException { return null; } default SendResult publish(@JsonRpcParam(value = "topic") String topic, @JsonRpcParam(value = "content") byte[] content, @JsonRpcParam(value = "extensions") Map<String, String> extensions) throws BrokerException { return null; } default SendResult publish(@JsonRpcParam(value = "topic") String topic, @JsonRpcParam(value = "content") byte[] content) throws BrokerException { return null; } default SendResult publish(@JsonRpcParam(value = "topic") String topic, @JsonRpcParam(value = "groupId") String groupId, @JsonRpcParam(value = "content") byte[] content) throws BrokerException { return null; } // The following is interface for IEventTopic. boolean open(@JsonRpcParam(value = "topic") String topic, @JsonRpcParam(value = "groupId") String groupId) throws BrokerException; default boolean open(@JsonRpcParam(value = "topic") String topic) throws BrokerException { return false; } boolean close(@JsonRpcParam(value = "topic") String topic, @JsonRpcParam(value = "groupId") String groupId) throws BrokerException; default boolean close(@JsonRpcParam(value = "topic") String topic) throws BrokerException { return false; } boolean exist(@JsonRpcParam(value = "topic") String topic, @JsonRpcParam(value = "groupId") String groupId) throws BrokerException; default boolean exist(@JsonRpcParam(value = "topic") String topic) throws BrokerException { return false; } TopicPage list(@JsonRpcParam(value = "pageIndex") Integer pageIndex, @JsonRpcParam(value = "pageSize") Integer pageSize, @JsonRpcParam(value = "groupId") String groupId) throws BrokerException; default TopicPage list(@JsonRpcParam(value = "pageIndex") Integer pageIndex, @JsonRpcParam(value = "pageSize") Integer pageSize) throws BrokerException { return null; } TopicInfo state(@JsonRpcParam(value = "topic") String topic, @JsonRpcParam(value = "groupId") String groupId) throws BrokerException; default TopicInfo state(@JsonRpcParam(value = "topic") String topic) throws BrokerException { return null; } WeEvent getEvent(@JsonRpcParam(value = "eventId") String eventId, @JsonRpcParam(value = "groupId") String groupId) throws BrokerException; default WeEvent getEvent(@JsonRpcParam(value = "eventId") String eventId) throws BrokerException { return null; } List<String> listGroup() throws BrokerException; }
3e08a09177ebe8848054c23b5b717486de1f183e
3,125
java
Java
izpack-panel/src/main/java/com/izforge/izpack/panels/userinput/gui/rule/GUIRuleField.java
Datical/izpack
df3b864bf2c04ddde21d822ad60f58f6d6a7ca16
[ "Apache-2.0" ]
null
null
null
izpack-panel/src/main/java/com/izforge/izpack/panels/userinput/gui/rule/GUIRuleField.java
Datical/izpack
df3b864bf2c04ddde21d822ad60f58f6d6a7ca16
[ "Apache-2.0" ]
1
2021-08-02T17:26:26.000Z
2021-08-02T17:26:26.000Z
izpack-panel/src/main/java/com/izforge/izpack/panels/userinput/gui/rule/GUIRuleField.java
Datical/izpack
df3b864bf2c04ddde21d822ad60f58f6d6a7ca16
[ "Apache-2.0" ]
1
2021-01-12T11:39:34.000Z
2021-01-12T11:39:34.000Z
25.614754
91
0.6336
3,651
/* * IzPack - Copyright 2001-2012 Julien Ponge, All Rights Reserved. * * http://izpack.org/ * http://izpack.codehaus.org/ * * Copyright 2012 Tim Anderson * * 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.izforge.izpack.panels.userinput.gui.rule; import javax.swing.JTextField; import com.izforge.izpack.api.handler.Prompt; import com.izforge.izpack.panels.userinput.field.Field; import com.izforge.izpack.panels.userinput.field.ValidationStatus; import com.izforge.izpack.panels.userinput.field.rule.RuleField; import com.izforge.izpack.panels.userinput.gui.GUIField; /** * Rule field view. * * @author Tim Anderson */ public class GUIRuleField extends GUIField { /** * The component. */ private final RuleInputField component; /** * Constructs a {@code GUIRuleField}. * * @param field the field */ public GUIRuleField(RuleField field) { super(field); component = new RuleInputField(field); int id = 1; for (JTextField input : component.getInputFields()) { input.setName(field.getVariable() + "." + id); ++id; } addField(component); } /** * Returns the text from the display, according to the field's formatting convention. * * @return the formatted text */ public String getValue() { return component.getText(); } /** * Returns each sub-field value. * * @return the sub-field values */ public String[] getValues() { return component.getValues(); } /** * Sets the sub-field values. * * @param values the sub-field values */ public void setValues(String... values) { component.setValues(values); } /** * Updates the field from the view. * * @param prompt the prompt to display messages * @param skipValidation set to true when wanting to save field data without validating * @return {@code true} if the field was updated, {@code false} if the view is invalid */ @Override public boolean updateField(Prompt prompt, boolean skipValidation) { boolean result = false; Field field = getField(); ValidationStatus status = field.validate(component.getValues()); if (skipValidation || status.isValid()) { field.setValue(component.getText()); result = true; } else if (status.getMessage() != null) { prompt.warn(status.getMessage()); } return result; } }
3e08a19b7b855a19fe3caacc0292f5c5d69c408b
556
java
Java
gmall-index/src/main/java/com/atguigu/gmall/index/config/RedissonConfig.java
joedyli/gmall
1bc90df263f9b919d1c2f09ac32bc3bac1795a90
[ "Apache-2.0" ]
3
2019-11-18T09:45:24.000Z
2021-01-09T06:36:05.000Z
gmall-index/src/main/java/com/atguigu/gmall/index/config/RedissonConfig.java
joedyli/gmall
1bc90df263f9b919d1c2f09ac32bc3bac1795a90
[ "Apache-2.0" ]
3
2021-03-19T20:22:38.000Z
2021-09-20T20:56:55.000Z
gmall-index/src/main/java/com/atguigu/gmall/index/config/RedissonConfig.java
joedyli/gmall
1bc90df263f9b919d1c2f09ac32bc3bac1795a90
[ "Apache-2.0" ]
1
2019-10-03T05:31:16.000Z
2019-10-03T05:31:16.000Z
27.8
75
0.739209
3,652
package com.atguigu.gmall.index.config; import org.redisson.Redisson; import org.redisson.api.RedissonClient; import org.redisson.config.Config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class RedissonConfig { @Bean public RedissonClient redissonClient(){ Config config = new Config(); // 可以用"rediss://"来启用SSL连接 config.useSingleServer().setAddress("redis://172.16.116.100:6379"); return Redisson.create(config); } }
3e08a1ac44ee9ed783273949b0eb4fff28a9cece
2,619
java
Java
src/highscores/Score.java
xp710/Turbo-Shit-Extreme
278f141c26dfdebedc9e312c71664af00f9c80ab
[ "MIT" ]
null
null
null
src/highscores/Score.java
xp710/Turbo-Shit-Extreme
278f141c26dfdebedc9e312c71664af00f9c80ab
[ "MIT" ]
null
null
null
src/highscores/Score.java
xp710/Turbo-Shit-Extreme
278f141c26dfdebedc9e312c71664af00f9c80ab
[ "MIT" ]
null
null
null
25.427184
101
0.547537
3,653
package edu.stuy.starlorn.highscores; import java.text.DecimalFormat; import java.util.Date; public class Score implements Comparable { private String _name; private long _score; private int _level, _wave; private Date _date; public Score(String name, long score, int level, int wave, Date date) { _name = name; _score = score; _level = level; _wave = wave; _date = date; } public void setName(String name) { _name = name; } public String getName() { return _name; } public void setScore(long score) { _score = score; } public long getScore() { return _score; } public String getFormattedScore() { DecimalFormat formatter = new DecimalFormat("#,###"); return formatter.format(_score); } public void setLevel(int level) { _level = level; } public int getLevel() { return _level; } public void setWave(int wave) { _wave = wave; } public int getWave() { return _wave; } public void setDate(Date date) { _date = date; } public Date getDate() { return _date; } public String serialize() { String serial = "%s : %d : %d : %d : %d"; String name = getName().replace(":", "\\:").replace("\n", " "); return String.format(serial, name, getScore(), getLevel(), getWave(), getDate().getTime()); } public static Score deserialize(String input) { String[] data = input.split(" : "); if (data.length != 5) { System.out.println("Some line in the scores file isn't formatted right. I'll ignore it"); return null; } // We escape their colons when saving, so unescape them when loading String name = data[0].replace("\\:", ":"); long score = Long.parseLong(data[1]); int level = Integer.parseInt(data[2]); int wave = Integer.parseInt(data[3]); long time = Long.parseLong(data[4]); return new Score(name, score, level, wave, new Date(time)); } @Override public int compareTo(Object o) { if (o instanceof Score) { long otherScore = ((Score) o).getScore(); if (otherScore > _score) return -1; else if (otherScore < _score) return 1; else { return -_date.compareTo(((Score) o).getDate()); } } else throw new IllegalArgumentException("Expected Score"); } }
3e08a3f2999cd90265b263d5ffc3a38c160428dd
795
java
Java
src/main/java/id/ac/tazkia/akademik/aplikasiakademik/dao/TahunAkademikDao.java
dimashadiwibowo/aplikasi-akademik
b9b1e49a109b0745d3f650fde15b3497c4761a82
[ "Apache-2.0" ]
1
2018-07-12T01:56:04.000Z
2018-07-12T01:56:04.000Z
src/main/java/id/ac/tazkia/akademik/aplikasiakademik/dao/TahunAkademikDao.java
dimashadiwibowo/aplikasi-akademik
b9b1e49a109b0745d3f650fde15b3497c4761a82
[ "Apache-2.0" ]
null
null
null
src/main/java/id/ac/tazkia/akademik/aplikasiakademik/dao/TahunAkademikDao.java
dimashadiwibowo/aplikasi-akademik
b9b1e49a109b0745d3f650fde15b3497c4761a82
[ "Apache-2.0" ]
null
null
null
49.6875
160
0.861635
3,654
package id.ac.tazkia.akademik.aplikasiakademik.dao; import id.ac.tazkia.akademik.aplikasiakademik.entity.StatusRecord; import id.ac.tazkia.akademik.aplikasiakademik.entity.TahunAkademik; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.PagingAndSortingRepository; import java.util.List; public interface TahunAkademikDao extends PagingAndSortingRepository<TahunAkademik, String> { Page<TahunAkademik> findByStatusNotInOrderByKodeTahunAkademikDesc(StatusRecord status, Pageable page); TahunAkademik findByStatus(StatusRecord status); Page<TahunAkademik> findByStatusNotInAndNamaTahunAkademikContainingIgnoreCaseOrderByKodeTahunAkademikDesc(StatusRecord status,String search, Pageable page); }
3e08a42860d81896740ada5f92097700182d4185
198
java
Java
src/main/java/com/xray/tutorials/pages/LoginResultsPage.java
Xray-App/tutorial-java-cucumber-selenium
ab2817db77499ab44721a8eeed9406b6c34c993c
[ "BSD-3-Clause" ]
null
null
null
src/main/java/com/xray/tutorials/pages/LoginResultsPage.java
Xray-App/tutorial-java-cucumber-selenium
ab2817db77499ab44721a8eeed9406b6c34c993c
[ "BSD-3-Clause" ]
null
null
null
src/main/java/com/xray/tutorials/pages/LoginResultsPage.java
Xray-App/tutorial-java-cucumber-selenium
ab2817db77499ab44721a8eeed9406b6c34c993c
[ "BSD-3-Clause" ]
null
null
null
14.142857
49
0.767677
3,655
package com.xray.tutorials.pages; import org.openqa.selenium.WebDriver; public class LoginResultsPage extends Page { public LoginResultsPage(WebDriver webDriver){ super(webDriver); } }
3e08a48e3c9f7f1350c428883f34bcceb44177f4
2,412
java
Java
src/test/java/seedu/address/logic/commands/EditRoomCommandTest.java
teekoksiang/tp
35478f267805d0b181d04ede70415a6d4cc3cf87
[ "MIT" ]
null
null
null
src/test/java/seedu/address/logic/commands/EditRoomCommandTest.java
teekoksiang/tp
35478f267805d0b181d04ede70415a6d4cc3cf87
[ "MIT" ]
198
2020-09-16T15:40:19.000Z
2020-11-09T15:05:10.000Z
src/test/java/seedu/address/logic/commands/EditRoomCommandTest.java
teekoksiang/tp
35478f267805d0b181d04ede70415a6d4cc3cf87
[ "MIT" ]
5
2020-09-10T06:14:35.000Z
2020-09-12T14:04:55.000Z
35.470588
96
0.726368
3,656
package seedu.address.logic.commands; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static seedu.address.testutil.Assert.assertThrows; import static seedu.address.testutil.TypicalPersons.getTypicalAddressBook; import org.junit.jupiter.api.Test; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.UserPrefs; public class EditRoomCommandTest { private Model model = new ModelManager(getTypicalAddressBook(), new UserPrefs()); @Test public void execute_validRoomRange_success() throws CommandException { CommandResult commandResult = new EditRoomCommand(1, 99).execute(model); // compare output assertEquals(String.format(EditRoomCommand.MESSAGE_EDIT_ROOM_SUCCESS, 1, 99), commandResult.getFeedbackToUser()); } @Test public void execute_invalidMinRoom_throwsCommandException() { EditRoomCommand editRoomCommand = new EditRoomCommand(0, 20); assertThrows(CommandException.class, String.format(EditRoomCommand.MESSAGE_INVALID_MIN_ROOM, UserPrefs.MIN_ALLOWED_ROOMS, UserPrefs.MAX_ALLOWED_ROOMS), () -> editRoomCommand.execute(model)); } @Test public void execute_invalidMaxRoom_throwsCommandException() { EditRoomCommand editRoomCommand = new EditRoomCommand(1, 101); assertThrows(CommandException.class, String.format(EditRoomCommand.MESSAGE_INVALID_MAX_ROOM, UserPrefs.MIN_ALLOWED_ROOMS, UserPrefs.MAX_ALLOWED_ROOMS), () -> editRoomCommand.execute(model)); } @Test public void equals() { final EditRoomCommand standardCommand = new EditRoomCommand(1, 20); // same values -> equals assertEquals(standardCommand, new EditRoomCommand(1, 20)); // different values -> not equals assertNotEquals(standardCommand, new EditRoomCommand(1, 10)); assertNotEquals(standardCommand, new EditRoomCommand(2, 20)); // same object -> equals assertEquals(standardCommand, standardCommand); // null -> not equals assertNotEquals(null, standardCommand); // different types -> not equals assertNotEquals(standardCommand, new ClearCommand()); } }
3e08a5b53b353ede75f221e2154e868e08969848
7,330
java
Java
src/java/com/echothree/model/control/offer/server/logic/UseLogic.java
echothreellc/echothree
1744df7654097cc000e5eca32de127b5dc745302
[ "Apache-2.0" ]
1
2020-09-01T08:39:01.000Z
2020-09-01T08:39:01.000Z
src/java/com/echothree/model/control/offer/server/logic/UseLogic.java
echothreellc/echothree
1744df7654097cc000e5eca32de127b5dc745302
[ "Apache-2.0" ]
null
null
null
src/java/com/echothree/model/control/offer/server/logic/UseLogic.java
echothreellc/echothree
1744df7654097cc000e5eca32de127b5dc745302
[ "Apache-2.0" ]
1
2020-05-31T08:34:46.000Z
2020-05-31T08:34:46.000Z
44.695122
131
0.693452
3,657
// -------------------------------------------------------------------------------- // Copyright 2002-2021 Echo Three, LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // -------------------------------------------------------------------------------- package com.echothree.model.control.offer.server.logic; import com.echothree.control.user.offer.common.spec.UseUniversalSpec; import com.echothree.model.control.core.common.ComponentVendors; import com.echothree.model.control.core.common.EntityTypes; import com.echothree.model.control.core.common.exception.InvalidParameterCountException; import com.echothree.model.control.core.server.logic.EntityInstanceLogic; import com.echothree.model.control.offer.common.exception.CannotDeleteUseInUseException; import com.echothree.model.control.offer.common.exception.DuplicateUseNameException; import com.echothree.model.control.offer.common.exception.UnknownDefaultUseException; import com.echothree.model.control.offer.common.exception.UnknownUseNameException; import com.echothree.model.control.offer.server.control.OfferUseControl; import com.echothree.model.control.offer.server.control.UseControl; import com.echothree.model.data.core.server.entity.EntityInstance; import com.echothree.model.data.offer.server.entity.Use; import com.echothree.model.data.offer.server.entity.UseType; import com.echothree.model.data.offer.server.value.UseDetailValue; import com.echothree.model.data.party.server.entity.Language; import com.echothree.util.common.message.ExecutionErrors; import com.echothree.util.common.persistence.BasePK; import com.echothree.util.server.control.BaseLogic; import com.echothree.util.server.message.ExecutionErrorAccumulator; import com.echothree.util.server.persistence.EntityPermission; import com.echothree.util.server.persistence.Session; public class UseLogic extends BaseLogic { private UseLogic() { super(); } private static class UseLogicHolder { static UseLogic instance = new UseLogic(); } public static UseLogic getInstance() { return UseLogicHolder.instance; } public Use createUse(final ExecutionErrorAccumulator eea, final String useName, final UseType useType, final Boolean isDefault, final Integer sortOrder, final Language language, final String description, final BasePK createdBy) { var useControl = Session.getModelController(UseControl.class); var use = useControl.getUseByName(useName); if(use == null) { use = useControl.createUse(useName, useType, isDefault, sortOrder, createdBy); if(description != null) { useControl.createUseDescription(use, language, description, createdBy); } } else { handleExecutionError(DuplicateUseNameException.class, eea, ExecutionErrors.DuplicateUseName.name(), useName); } return use; } public Use getUseByName(final ExecutionErrorAccumulator eea, final String useName, final EntityPermission entityPermission) { var useControl = Session.getModelController(UseControl.class); var use = useControl.getUseByName(useName, entityPermission); if(use == null) { handleExecutionError(UnknownUseNameException.class, eea, ExecutionErrors.UnknownUseName.name(), useName); } return use; } public Use getUseByName(final ExecutionErrorAccumulator eea, final String useName) { return getUseByName(eea, useName, EntityPermission.READ_ONLY); } public Use getUseByNameForUpdate(final ExecutionErrorAccumulator eea, final String useName) { return getUseByName(eea, useName, EntityPermission.READ_WRITE); } public Use getUseByUniversalSpec(final ExecutionErrorAccumulator eea, final UseUniversalSpec universalSpec, boolean allowDefault, final EntityPermission entityPermission) { var useControl = Session.getModelController(UseControl.class); var useName = universalSpec.getUseName(); var parameterCount = (useName == null ? 0 : 1) + EntityInstanceLogic.getInstance().countPossibleEntitySpecs(universalSpec); Use use = null; switch(parameterCount) { case 0: if(allowDefault) { use = useControl.getDefaultUse(entityPermission); if(use == null) { handleExecutionError(UnknownDefaultUseException.class, eea, ExecutionErrors.UnknownDefaultUse.name()); } } else { handleExecutionError(InvalidParameterCountException.class, eea, ExecutionErrors.InvalidParameterCount.name()); } break; case 1: if(useName == null) { EntityInstance entityInstance = EntityInstanceLogic.getInstance().getEntityInstance(eea, universalSpec, ComponentVendors.ECHOTHREE.name(), EntityTypes.Use.name()); if(!eea.hasExecutionErrors()) { use = useControl.getUseByEntityInstance(entityInstance, entityPermission); } } else { use = getUseByName(eea, useName, entityPermission); } break; default: handleExecutionError(InvalidParameterCountException.class, eea, ExecutionErrors.InvalidParameterCount.name()); break; } return use; } public Use getUseByUniversalSpec(final ExecutionErrorAccumulator eea, final UseUniversalSpec universalSpec, boolean allowDefault) { return getUseByUniversalSpec(eea, universalSpec, allowDefault, EntityPermission.READ_ONLY); } public Use getUseByUniversalSpecForUpdate(final ExecutionErrorAccumulator eea, final UseUniversalSpec universalSpec, boolean allowDefault) { return getUseByUniversalSpec(eea, universalSpec, allowDefault, EntityPermission.READ_WRITE); } public void updateUseFromValue(UseDetailValue useDetailValue, BasePK updatedBy) { var useControl = Session.getModelController(UseControl.class); useControl.updateUseFromValue(useDetailValue, updatedBy); } public void deleteUse(final ExecutionErrorAccumulator eea, final Use use, final BasePK deletedBy) { var offerUseControl = Session.getModelController(OfferUseControl.class); if(offerUseControl.countOfferUsesByUse(use) == 0) { var useControl = Session.getModelController(UseControl.class); useControl.deleteUse(use, deletedBy); } else { handleExecutionError(CannotDeleteUseInUseException.class, eea, ExecutionErrors.CannotDeleteUseInUse.name()); } } }
3e08a61e587102a87570ebf12855d93f5a86eeb7
2,193
java
Java
src/main/java/com/novartis/pcs/ontology/service/util/StatusChecker.java
nikhitajatain/ontobrowser
b4b515a8c6e7e5d07f31cc2f62f33a4ed2a1c722
[ "Apache-2.0" ]
27
2015-05-09T23:34:48.000Z
2022-03-26T15:20:43.000Z
src/main/java/com/novartis/pcs/ontology/service/util/StatusChecker.java
nikhitajatain/ontobrowser
b4b515a8c6e7e5d07f31cc2f62f33a4ed2a1c722
[ "Apache-2.0" ]
5
2015-05-09T23:39:35.000Z
2019-08-22T12:28:52.000Z
src/main/java/com/novartis/pcs/ontology/service/util/StatusChecker.java
Novartis/ontobrowser
a0703f485ced29b73e3439bff674d3fa76f1f448
[ "Apache-2.0" ]
8
2017-05-14T17:36:13.000Z
2022-03-24T02:07:50.000Z
32.731343
103
0.732786
3,658
/* Copyright 2015 Novartis Institutes for Biomedical Research 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.novartis.pcs.ontology.service.util; import java.util.ArrayList; import java.util.Collection; import java.util.EnumSet; import java.util.HashSet; import java.util.Set; import com.novartis.pcs.ontology.entity.InvalidEntityException; import com.novartis.pcs.ontology.entity.VersionedEntity; import com.novartis.pcs.ontology.entity.VersionedEntity.Status; public class StatusChecker { private static final EnumSet<Status> valid = EnumSet.of(Status.PENDING, Status.APPROVED); public static <T extends VersionedEntity> boolean isValid(T entity) { return entity != null && valid.contains(entity.getStatus()); } public static <T extends VersionedEntity> void validate(T... entities) throws InvalidEntityException { for(T entity : entities) { if(!isValid(entity)) { throw entity != null ? new InvalidEntityException(entity, entity.getClass().getName() + " has invalid status: " + entity.getStatus()) : new InvalidEntityException(entity, "Entity not found"); } } } public static <T extends VersionedEntity> boolean removeInvalid(Collection<T> entities) { Set<T> invalid = new HashSet<T>(); for(T entity : entities) { if(!StatusChecker.isValid(entity)) { invalid.add(entity); } } return invalid.isEmpty() ? false : entities.removeAll(invalid); } public static <T extends VersionedEntity> Collection<T> valid(Collection<T> entities) { Collection<T> valid = new ArrayList<T>(); for(T entity : entities) { if(StatusChecker.isValid(entity)) { valid.add(entity); } } return valid; } }
3e08a634fdfe2a2c3ad41f51edfbaaee62938108
2,046
java
Java
main/plugins/org.talend.cwm.mip/src/orgomg/cwmx/foundation/er/ForeignKey.java
dmytro-sylaiev/tcommon-studio-se
b75fadfb9bd1a42897073fe2984f1d4fb42555bd
[ "Apache-2.0" ]
75
2015-01-29T03:23:32.000Z
2022-02-26T07:05:40.000Z
main/plugins/org.talend.cwm.mip/src/orgomg/cwmx/foundation/er/ForeignKey.java
dmytro-sylaiev/tcommon-studio-se
b75fadfb9bd1a42897073fe2984f1d4fb42555bd
[ "Apache-2.0" ]
813
2015-01-21T09:36:31.000Z
2022-03-30T01:15:29.000Z
main/plugins/org.talend.cwm.mip/src/orgomg/cwmx/foundation/er/ForeignKey.java
dmytro-sylaiev/tcommon-studio-se
b75fadfb9bd1a42897073fe2984f1d4fb42555bd
[ "Apache-2.0" ]
272
2015-01-08T06:47:46.000Z
2022-02-09T23:22:27.000Z
35.275862
187
0.665689
3,659
/** * <copyright> </copyright> * * $Id$ */ package orgomg.cwmx.foundation.er; import orgomg.cwm.foundation.keysindexes.KeyRelationship; /** * <!-- begin-user-doc --> A representation of the model object ' * <em><b>Foreign Key</b></em>'. <!-- end-user-doc --> * * <!-- begin-model-doc --> * A ForeignKey instance identifies a set of attributes in one Entity instance that uniquely identifies an instance of another Entity containing a matching primary or candidate key value. * <!-- end-model-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link orgomg.cwmx.foundation.er.ForeignKey#getRelationshipEnd <em>Relationship End</em>}</li> * </ul> * </p> * * @see orgomg.cwmx.foundation.er.ErPackage#getForeignKey() * @model * @generated */ public interface ForeignKey extends KeyRelationship { /** * Returns the value of the '<em><b>Relationship End</b></em>' reference. * It is bidirectional and its opposite is '{@link orgomg.cwmx.foundation.er.RelationshipEnd#getForeignKey <em>Foreign Key</em>}'. * <!-- begin-user-doc --> <!-- end-user-doc --> * <!-- begin-model-doc --> * Identifies the RelationshipEnd instance that this ForeignKey instance implements. * <!-- end-model-doc --> * @return the value of the '<em>Relationship End</em>' reference. * @see #setRelationshipEnd(RelationshipEnd) * @see orgomg.cwmx.foundation.er.ErPackage#getForeignKey_RelationshipEnd() * @see orgomg.cwmx.foundation.er.RelationshipEnd#getForeignKey * @model opposite="foreignKey" * @generated */ RelationshipEnd getRelationshipEnd(); /** * Sets the value of the '{@link orgomg.cwmx.foundation.er.ForeignKey#getRelationshipEnd <em>Relationship End</em>}' reference. * <!-- begin-user-doc --> <!-- * end-user-doc --> * @param value the new value of the '<em>Relationship End</em>' reference. * @see #getRelationshipEnd() * @generated */ void setRelationshipEnd(RelationshipEnd value); } // ForeignKey
3e08a70542c0376e8ca84a5b3c029568538889ca
2,145
java
Java
src/main/java/controller/login/LoginController.java
AP2020Fall/project-team-team-2
a59d42d550fcf2ec69bfba967d8d26bfcda7f664
[ "MIT" ]
3
2021-03-08T16:55:08.000Z
2021-03-26T14:46:19.000Z
src/main/java/controller/login/LoginController.java
AP2020Fall/project-team-team-2
a59d42d550fcf2ec69bfba967d8d26bfcda7f664
[ "MIT" ]
null
null
null
src/main/java/controller/login/LoginController.java
AP2020Fall/project-team-team-2
a59d42d550fcf2ec69bfba967d8d26bfcda7f664
[ "MIT" ]
null
null
null
34.047619
94
0.671329
3,660
package controller.login; import com.google.gson.Gson; import controller.Controller; import controller.ServerMasterController.ServerMasterController; import main.ClientInfo; import main.Token; import model.Account; import model.Admin; import model.Player; import java.util.Objects; public class LoginController extends Controller { private ClientInfo clientInfo; private Token token; public LoginController(ClientInfo clientInfo) { super(clientInfo); this.clientInfo = clientInfo; this.token = ServerMasterController.getCurrentToken(); } public void delete(String username) { //removes the username from the list and it is a player //throws NullPointerException if username is not a player Player player = Objects.requireNonNull(Player.getPlayerByUsername(username), "Username passed to LoginController.delete isn't a player or doesn't exist."); player.delete(); } public Boolean login(String username) { //logins into account //throws NullPointerException if username doesn't exist Account loggedIn = Account.getAccountByUsername(username); if(loggedIn == null) { System.err.println("Username passed to LoginController.login doesn't exist."); return false; } //if (clientInfo != null) { clientInfo.setLoggedInUsername(loggedIn.getUsername()); token.setLogin(loggedIn); loggedIn.setStatus("Online"); // } if (loggedIn instanceof Admin) { //new AdminMainMenuLayoutController().login((Admin) loggedIn); return true; } else if (loggedIn instanceof Player) { //new PlayerMainMenuLayoutController().login((Player) loggedIn); return false; } return false; } public void logout() { Account loggedIn = Account.getAccountByUsername(clientInfo.getLoggedInUsername()); if(loggedIn != null) loggedIn.setStatus("Offline"); clientInfo.unsetLoggedInUsername(); token.setLogout(); ServerMasterController.logout(); } }
3e08a7d4a5281b6536d9326400c652789cd71b43
2,621
java
Java
IntentServiceTest2/app/src/main/java/link/webarata3/dro/intentservicetest2/MainActivityFragment.java
webarata3/Android_sandbox
f389241ad3ff2102037eff246ed161b43df41578
[ "MIT" ]
null
null
null
IntentServiceTest2/app/src/main/java/link/webarata3/dro/intentservicetest2/MainActivityFragment.java
webarata3/Android_sandbox
f389241ad3ff2102037eff246ed161b43df41578
[ "MIT" ]
null
null
null
IntentServiceTest2/app/src/main/java/link/webarata3/dro/intentservicetest2/MainActivityFragment.java
webarata3/Android_sandbox
f389241ad3ff2102037eff246ed161b43df41578
[ "MIT" ]
null
null
null
31.202381
91
0.697825
3,661
package link.webarata3.dro.intentservicetest2; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.AppCompatTextView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; public class MainActivityFragment extends Fragment implements TestResultReceiver.Receiver { private AppCompatTextView textView; private AppCompatButton beginButton; private TestResultReceiver receiver; private OnFragmentInteractionListener onFragmentInteractionListener; public interface OnFragmentInteractionListener { void onClickBeginButton(); } public MainActivityFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View fragment = inflater.inflate(R.layout.fragment_main, container, false); textView = (AppCompatTextView) fragment.findViewById(R.id.textView); beginButton = (AppCompatButton) fragment.findViewById(R.id.beginButton); receiver = new TestResultReceiver(new Handler()); receiver.setReceiver(this); beginButton.setOnClickListener(view -> { onFragmentInteractionListener.onClickBeginButton(); }); return fragment; } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { onFragmentInteractionListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); onFragmentInteractionListener = null; } public void onClickBeginButton() { Toast.makeText(getActivity(), "Start", Toast.LENGTH_SHORT).show(); beginButton.setEnabled(false); Intent intent = new Intent(getActivity(), TestIntentService.class); intent.putExtra("receiver", receiver); getActivity().startService(intent); } @Override public void onReceiveResult(int resultCode, Bundle resultData) { int progress = resultData.getInt("progress"); textView.setText(progress+ "%"); if (progress == 100) { beginButton.setEnabled(true); } } }
3e08a8f6e97bea7022a76e9ae41ae54615cc3808
1,304
java
Java
app/src/main/java/com/wa/dev/edukasikomputer/BelajarKomputer/HardwareKomputer/PerangkatMasukan/YoutubeMouse.java
wibawabangkit/Edukasi-Komputer
9296aa4b45f22ed3c9b3ac61696e5465fb2ccedd
[ "MIT" ]
null
null
null
app/src/main/java/com/wa/dev/edukasikomputer/BelajarKomputer/HardwareKomputer/PerangkatMasukan/YoutubeMouse.java
wibawabangkit/Edukasi-Komputer
9296aa4b45f22ed3c9b3ac61696e5465fb2ccedd
[ "MIT" ]
null
null
null
app/src/main/java/com/wa/dev/edukasikomputer/BelajarKomputer/HardwareKomputer/PerangkatMasukan/YoutubeMouse.java
wibawabangkit/Edukasi-Komputer
9296aa4b45f22ed3c9b3ac61696e5465fb2ccedd
[ "MIT" ]
null
null
null
28.977778
85
0.699387
3,662
package com.wa.dev.edukasikomputer.BelajarKomputer.HardwareKomputer.PerangkatMasukan; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import android.webkit.WebView; import android.webkit.WebViewClient; import com.wa.dev.edukasikomputer.R; public class YoutubeMouse extends AppCompatActivity { @SuppressLint("SetJavaScriptEnabled") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_youtube_mouse); WebView web=(WebView)findViewById(R.id.mouseyu); web.getSettings().setJavaScriptEnabled(true); web.setWebViewClient(new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return super.shouldOverrideUrlLoading(view, url); } }); web.loadUrl("https://www.youtube.com/embed/aBSrF0_RTas"); } @Override public void onBackPressed() { super.onBackPressed(); Intent a = new Intent(YoutubeMouse.this, MouseAct.class); startActivity(a); finish(); } }
3e08a9294fdbf3e75020b3f30538d82c2a7e8945
2,299
java
Java
app/src/main/java/com/mfinance/everjoy/everjoy/dialog/base/BaseDialog.java
ngng1992/EvDemo
7bb238ca470e59e655da8f3ff4a9ae04614f82bd
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/mfinance/everjoy/everjoy/dialog/base/BaseDialog.java
ngng1992/EvDemo
7bb238ca470e59e655da8f3ff4a9ae04614f82bd
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/mfinance/everjoy/everjoy/dialog/base/BaseDialog.java
ngng1992/EvDemo
7bb238ca470e59e655da8f3ff4a9ae04614f82bd
[ "Apache-2.0" ]
null
null
null
25.831461
129
0.664202
3,663
package com.mfinance.everjoy.everjoy.dialog.base; import android.app.Dialog; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.view.Window; import com.mfinance.everjoy.R; import com.mfinance.everjoy.everjoy.dialog.impl.OnClickDialogOrFragmentViewListener; /** * 所有dialog基类 */ public abstract class BaseDialog extends Dialog { /** * 有黑色背景 */ protected static final int STYLE_DARK = R.style.BaseDialogDark; /** * 白色背景 */ protected static final int STYLE_BRIGHT = R.style.BaseDialog; protected Context context; protected OnClickDialogOrFragmentViewListener onClickDialogOrFragmentViewListener; public void setOnClickDialogOrFragmentViewListener(OnClickDialogOrFragmentViewListener onClickDialogOrFragmentViewListener) { this.onClickDialogOrFragmentViewListener = onClickDialogOrFragmentViewListener; } /** * 默认有黑色背景 */ public BaseDialog(Context context) { this(context, STYLE_DARK); this.context = context; } /** * 添加style */ public BaseDialog(Context context, int style) { super(context, style); this.context = context; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 在dialog外是否可以点击 setCanceledOnTouchOutside(canceledOnTouchOutside()); setCancelable(cancelable()); Window window = getWindow(); if (window != null) { window.setWindowAnimations(R.style.ScaleAnimationStyle); window.setBackgroundDrawable(new ColorDrawable()); boolean transparent = isTransparent(); if (transparent) { // 因为状态栏底色已经设置了白色,这里设置取消半透明色,会覆盖掉状态栏,看不到状态栏的时间显示等 window.setDimAmount(0f); } } } /** * 是否可以外部点击,默认true,dialog消失,子类实现返回false,dialog不消失 */ protected boolean canceledOnTouchOutside() { return true; } /** * 是否屏蔽返回键按钮,默认true,dialog消失,子类实现返回false,dialog不消失 */ protected boolean cancelable() { return true; } /** * 是否显示半透明遮罩,子类传true不显示半透明遮罩 */ protected boolean isTransparent() { return false; } }
3e08a94b913f8a2bd0dcd1b099a4b1394ea872c3
1,657
java
Java
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/material/WxMpNewsArticle.java
fanxiayang12/WxJava
9e0e09087bb9cef6f551d452012e7987d2ae63db
[ "Apache-2.0" ]
14,793
2018-12-21T13:57:01.000Z
2022-03-31T15:27:56.000Z
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/material/WxMpNewsArticle.java
fanxiayang12/WxJava
9e0e09087bb9cef6f551d452012e7987d2ae63db
[ "Apache-2.0" ]
1,323
2018-12-22T03:07:38.000Z
2022-03-31T15:01:31.000Z
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/material/WxMpNewsArticle.java
fanxiayang12/WxJava
9e0e09087bb9cef6f551d452012e7987d2ae63db
[ "Apache-2.0" ]
4,743
2018-12-22T02:43:09.000Z
2022-03-31T12:54:29.000Z
19.963855
68
0.657815
3,664
package me.chanjar.weixin.mp.bean.material; import lombok.Data; import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; import java.io.Serializable; /** * <pre> * 图文消息article. * 1. thumbMediaId (必填) 图文消息的封面图片素材id(必须是永久mediaID) * 2. author 图文消息的作者 * 3. title (必填) 图文消息的标题 * 4. contentSourceUrl 在图文消息页面点击“阅读原文”后的页面链接 * 5. content (必填) 图文消息页面的内容,支持HTML标签 * 6. digest 图文消息的描述 * 7. showCoverPic 是否显示封面,true为显示,false为不显示 * 8. url 点击图文消息跳转链接 * 9. need_open_comment(新增字段) 否 Uint32 是否打开评论,0不打开,1打开 * 10. only_fans_can_comment(新增字段) 否 Uint32 是否粉丝才可评论,0所有人可评论,1粉丝才可评论 * </pre> * * @author chanjarster */ @Data public class WxMpNewsArticle implements Serializable { private static final long serialVersionUID = -635384661692321171L; /** * (必填) 图文消息缩略图的media_id,可以在基础支持-上传多媒体文件接口中获得. */ private String thumbMediaId; /** * 图文消息的封面url. */ private String thumbUrl; /** * 图文消息的作者. */ private String author; /** * (必填) 图文消息的标题. */ private String title; /** * 在图文消息页面点击“阅读原文”后的页面链接. */ private String contentSourceUrl; /** * (必填) 图文消息页面的内容,支持HTML标签. */ private String content; /** * 图文消息的描述. */ private String digest; /** * 是否显示封面,true为显示,false为不显示. */ private boolean showCoverPic; /** * 点击图文消息跳转链接. */ private String url; /** * need_open_comment * 是否打开评论,0不打开,1打开. */ private Boolean needOpenComment; /** * only_fans_can_comment * 是否粉丝才可评论,0所有人可评论,1粉丝才可评论. */ private Boolean onlyFansCanComment; @Override public String toString() { return WxMpGsonBuilder.create().toJson(this); } }
3e08aae3efcff50b37c839e54c11ecdb7c5321fc
1,744
java
Java
Fundamentals/MergeSort.java
minju2655-cmis/APCS-minju2655-cmis
9adf22f9faf2885bda296e003f7dedb7e12f0518
[ "MIT" ]
null
null
null
Fundamentals/MergeSort.java
minju2655-cmis/APCS-minju2655-cmis
9adf22f9faf2885bda296e003f7dedb7e12f0518
[ "MIT" ]
null
null
null
Fundamentals/MergeSort.java
minju2655-cmis/APCS-minju2655-cmis
9adf22f9faf2885bda296e003f7dedb7e12f0518
[ "MIT" ]
null
null
null
27.25
85
0.406537
3,665
public class MergeSort{ public static void main(String[] args){ int[] array = getArray(5, true); print(array); int[] sorted = sort(array); print(sorted); } public static int[] sort(int[] array){ //BASE CASE if(array.length <= 1){ return array; } //SPLIT STEP int half = array.length / 2; int[] front = new int[half]; int[] back = new int[array.length - half]; for(int i = 0; i < array.length; i++){ if(i < half){ front[i] = array[i]; }else{ back[i - half] = array[i]; } } //MERGESORT STEP front = sort(front); back = sort(back); int fi = 0; int bi = 0; //MERGE STEP for(int i = 0; i < array.length; i++){ if((bi >= back.length) || (fi < front.length && front[fi] < back[bi])){ array[i] = front[fi]; fi++; }else{ array[i] = back[bi]; bi++; } } return array; } public static int[] getArray(int w, boolean random){ int[] array = new int[w]; int ct = 0; for(int i = 0; i < w; i++){ if(random) array[i] = (int)(Math.random() * 20000) - 10000; else array[i] = ct++; } return array; } public static void print(int[] array){ String out = "{"; for(int i = 0; i < array.length; i++){ out += array[i]; if( i != array.length -1) out+=", "; } out+= "}\n"; System.out.println(out); } }
3e08ab150778f152a9b03b3bf647df55db7ee7db
3,740
java
Java
example/sequence-split-merge/src/test/java/com/jstorm/example/unittests/window/WindowTestAbstractRankingBolt.java
chenqixu/jstorm
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
[ "Apache-2.0" ]
4,124
2015-01-03T15:58:17.000Z
2022-03-31T11:06:25.000Z
example/sequence-split-merge/src/test/java/com/jstorm/example/unittests/window/WindowTestAbstractRankingBolt.java
chenqixu/jstorm
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
[ "Apache-2.0" ]
596
2015-01-05T14:11:02.000Z
2021-08-05T20:44:39.000Z
example/sequence-split-merge/src/test/java/com/jstorm/example/unittests/window/WindowTestAbstractRankingBolt.java
chenqixu/jstorm
5d6cde22dbca7df3d6e6830bf94f98a6639ab559
[ "Apache-2.0" ]
2,064
2015-01-04T10:54:02.000Z
2022-03-29T06:55:43.000Z
35.283019
118
0.703476
3,666
/** * 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.jstorm.example.unittests.window; import backtype.storm.Config; import backtype.storm.topology.BasicOutputCollector; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.topology.base.BaseBasicBolt; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Tuple; import backtype.storm.tuple.Values; import backtype.storm.utils.TupleUtils; import org.apache.storm.starter.tools.Rankings; import org.slf4j.Logger; import java.util.HashMap; import java.util.Map; /** * @author binyang.dby on 2016/7/11. */ public abstract class WindowTestAbstractRankingBolt extends BaseBasicBolt { private static final long serialVersionUID = 4931640198501530202L; private static final int DEFAULT_EMIT_FREQUENCY_IN_SECONDS = 2; private static final int DEFAULT_COUNT = 10; private final int emitFrequencyInSeconds; private final int count; private final Rankings rankings; public WindowTestAbstractRankingBolt() { this(DEFAULT_COUNT, DEFAULT_EMIT_FREQUENCY_IN_SECONDS); } public WindowTestAbstractRankingBolt(int topN) { this(topN, DEFAULT_EMIT_FREQUENCY_IN_SECONDS); } public WindowTestAbstractRankingBolt(int topN, int emitFrequencyInSeconds) { if (topN < 1) { throw new IllegalArgumentException("topN must be >= 1 (you requested " + topN + ")"); } if (emitFrequencyInSeconds < 1) { throw new IllegalArgumentException( "The emit frequency must be >= 1 seconds (you requested " + emitFrequencyInSeconds + " seconds)"); } count = topN; this.emitFrequencyInSeconds = emitFrequencyInSeconds; rankings = new Rankings(count); } protected Rankings getRankings() { return rankings; } /** * This method functions as a template method (design pattern). */ @Override public final void execute(Tuple tuple, BasicOutputCollector collector) { if (TupleUtils.isTick(tuple)) { getLogger().debug("Received tick tuple, triggering emit of current rankings"); emitRankings(collector); } else { updateRankingsWithTuple(tuple); } } abstract void updateRankingsWithTuple(Tuple tuple); private void emitRankings(BasicOutputCollector collector) { collector.emit(new Values(rankings.copy())); getLogger().info("AbstractRankerBolt Rankings: " + rankings); } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("rankings")); } @Override public Map<String, Object> getComponentConfiguration() { Map<String, Object> conf = new HashMap<String, Object>(); conf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, emitFrequencyInSeconds); return conf; } abstract Logger getLogger(); }
3e08ab88e681d23ec32a1b385214ae5a9836d67c
3,560
java
Java
src/test/java/com/oroarmor/neural_network/numberID/NumberIDJCuda.java
OroArmor/NeuralNetwork
248af29caa660fc42be750f0ad57247e8c3a6f64
[ "MIT" ]
null
null
null
src/test/java/com/oroarmor/neural_network/numberID/NumberIDJCuda.java
OroArmor/NeuralNetwork
248af29caa660fc42be750f0ad57247e8c3a6f64
[ "MIT" ]
null
null
null
src/test/java/com/oroarmor/neural_network/numberID/NumberIDJCuda.java
OroArmor/NeuralNetwork
248af29caa660fc42be750f0ad57247e8c3a6f64
[ "MIT" ]
null
null
null
38.695652
110
0.694382
3,667
/* * MIT License * * Copyright (c) 2021 OroArmor * * 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 com.oroarmor.neural_network.numberID; import com.oroarmor.neural_network.matrix.CPUMatrix; import com.oroarmor.neural_network.matrix.jcuda.JCudaMatrix; import com.oroarmor.neural_network.matrix.jcuda.kernels.MatrixKernel; import com.oroarmor.neural_network.util.Dim3; import com.oroarmor.neural_network.util.JCudaHelper; import com.oroarmor.neural_network.util.JCudaKernel; import jcuda.Pointer; public class NumberIDJCuda { private static JCudaKernel testKernel; private static JCudaMatrix matrix; private static JCudaMatrix matrix2; private static CPUMatrix cpuMatrix; private static CPUMatrix cpuMatrix2; public static void main(String[] args) { JCudaHelper.InitJCuda(true); MatrixKernel.rebuildAllKernels(); testKernel = new JCudaKernel("test2"); testKernel.loadKernel("matrixKernels/test2.cu"); JCudaMatrix.randomMatrix(10, 10, null, 0, 10); initializeMatrices(); for (int i = 1; i < 100000; i *= 10) testImprovement(i); } private static void testImprovement(int ops) { long millis = System.currentTimeMillis(); for (int i = 0; i < ops; i++) { cpuMatrix.multiplyMatrix(cpuMatrix2); } long cpuTime = (System.currentTimeMillis() - millis); System.out.println("CPU: " + cpuTime); millis = System.currentTimeMillis(); for (int i = 0; i < ops; i++) { matrix.multiplyMatrix(matrix2); } long gpuTime = (System.currentTimeMillis() - millis); System.out.println("GPU: " + gpuTime); System.out.printf("Improvement at %d ops: %.2f%%\n", ops, (double) 100 * cpuTime / gpuTime); } private static void initializeMatrices() { int dims = 1 << 6; matrix = new JCudaMatrix(dims, dims).keep(); matrix2 = new JCudaMatrix(dims, dims).keep(); Dim3 blockSize = new Dim3(1024); Dim3 gridSize = new Dim3((int) Math.ceil(matrix.getCols() * matrix.getRows() / (double) blockSize.x)); Pointer params = Pointer.to(matrix.getSizePointer(), matrix.getMatrixPointer()); testKernel.runKernel(params, gridSize, blockSize); params = Pointer.to(matrix2.getSizePointer(), matrix2.getMatrixPointer()); testKernel.runKernel(params, gridSize, blockSize); cpuMatrix = matrix.toCPUMatrix(); cpuMatrix2 = matrix2.toCPUMatrix(); } }
3e08aca06325c7f8eb059d764a951391a9a6f27d
2,341
java
Java
hazelcast/src/main/java/com/hazelcast/client/impl/protocol/task/management/RunGcMessageTask.java
santhoshkumarbs/hazelcast
7728c89f48ef76e5bedde0ede4184abf9287efcd
[ "Apache-2.0" ]
null
null
null
hazelcast/src/main/java/com/hazelcast/client/impl/protocol/task/management/RunGcMessageTask.java
santhoshkumarbs/hazelcast
7728c89f48ef76e5bedde0ede4184abf9287efcd
[ "Apache-2.0" ]
null
null
null
hazelcast/src/main/java/com/hazelcast/client/impl/protocol/task/management/RunGcMessageTask.java
santhoshkumarbs/hazelcast
7728c89f48ef76e5bedde0ede4184abf9287efcd
[ "Apache-2.0" ]
null
null
null
30.012821
92
0.73601
3,668
/* * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.client.impl.protocol.task.management; import com.hazelcast.client.impl.protocol.ClientMessage; import com.hazelcast.client.impl.protocol.codec.MCRunGcCodec; import com.hazelcast.client.impl.protocol.codec.MCRunGcCodec.RequestParameters; import com.hazelcast.client.impl.protocol.task.AbstractCallableMessageTask; import com.hazelcast.instance.impl.Node; import com.hazelcast.internal.management.ManagementCenterService; import com.hazelcast.internal.nio.Connection; import java.security.Permission; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; public class RunGcMessageTask extends AbstractCallableMessageTask<RequestParameters> { public RunGcMessageTask(ClientMessage clientMessage, Node node, Connection connection) { super(clientMessage, node, connection); } @SuppressFBWarnings("DM_GC") @Override protected Object call() throws Exception { System.gc(); return null; } @Override protected RequestParameters decodeClientMessage(ClientMessage clientMessage) { return MCRunGcCodec.decodeRequest(clientMessage); } @Override protected ClientMessage encodeResponse(Object response) { return MCRunGcCodec.encodeResponse(); } @Override public String getServiceName() { return ManagementCenterService.SERVICE_NAME; } @Override public Permission getRequiredPermission() { return null; } @Override public String getDistributedObjectName() { return null; } @Override public String getMethodName() { return "runGc"; } @Override public Object[] getParameters() { return new Object[0]; } }
3e08adaba6bb6bd0e1b8686480ef758dfcf43a28
2,243
java
Java
febs-common/src/main/java/cc/mrbird/febs/common/configure/FebsLettuceRedisConfigure.java
bossjim/frontend
6790af091c1d052fe6b274cdb0f3a018d18ac039
[ "Apache-2.0" ]
2
2021-09-05T08:05:34.000Z
2022-01-26T02:31:44.000Z
febs-common/src/main/java/cc/mrbird/febs/common/configure/FebsLettuceRedisConfigure.java
bossjim/frontend
6790af091c1d052fe6b274cdb0f3a018d18ac039
[ "Apache-2.0" ]
null
null
null
febs-common/src/main/java/cc/mrbird/febs/common/configure/FebsLettuceRedisConfigure.java
bossjim/frontend
6790af091c1d052fe6b274cdb0f3a018d18ac039
[ "Apache-2.0" ]
1
2019-12-04T12:17:24.000Z
2019-12-04T12:17:24.000Z
40.053571
122
0.781097
3,669
package cc.mrbird.febs.common.configure; import cc.mrbird.febs.common.service.RedisService; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * Lettuce Redis配置 * * @author MrBird */ public class FebsLettuceRedisConfigure { @Bean @ConditionalOnClass(RedisOperations.class) public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(factory); Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(mapper); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); // key采用 String的序列化方式 template.setKeySerializer(stringRedisSerializer); // hash的 key也采用 String的序列化方式 template.setHashKeySerializer(stringRedisSerializer); // value序列化方式采用 jackson template.setValueSerializer(jackson2JsonRedisSerializer); // hash的 value序列化方式采用 jackson template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } @Bean @ConditionalOnBean(name = "redisTemplate") public RedisService redisService() { return new RedisService(); } }
3e08adb961d5e201ed2223791fa035f89623dfc5
3,030
java
Java
Source/SmartProductBrowser/app/src/main/java/ch/ost/wing/smartproducts/smartproductbrowser/dataaccess/local/ProductRepository.java
KretschiHSR/HSR-SmartProductsApp
54841b8002c7d597c0c8d84aea20332efce1b5dd
[ "MIT" ]
null
null
null
Source/SmartProductBrowser/app/src/main/java/ch/ost/wing/smartproducts/smartproductbrowser/dataaccess/local/ProductRepository.java
KretschiHSR/HSR-SmartProductsApp
54841b8002c7d597c0c8d84aea20332efce1b5dd
[ "MIT" ]
null
null
null
Source/SmartProductBrowser/app/src/main/java/ch/ost/wing/smartproducts/smartproductbrowser/dataaccess/local/ProductRepository.java
KretschiHSR/HSR-SmartProductsApp
54841b8002c7d597c0c8d84aea20332efce1b5dd
[ "MIT" ]
1
2020-09-11T06:56:54.000Z
2020-09-11T06:56:54.000Z
29.705882
87
0.650495
3,670
package ch.ost.wing.smartproducts.smartproductbrowser.dataaccess.local; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.util.Iterator; import java.util.UUID; import javax.inject.Inject; import ch.ost.wing.smartproducts.smartproductbrowser.dataaccess.local.entities.Product; import ch.ost.wing.smartproducts.smartproductbrowser.util.ImageUtil; public class ProductRepository implements IProductRepository { private final AppDatabase _db; private final IFileSystem _fileSystem; @Inject public ProductRepository(AppDatabase db, IFileSystem fileSystem){ this._db = db; this._fileSystem = fileSystem; } @Override public Iterable<Product> getAll() { return this._db.products().getAll(); } @Override public boolean exists(UUID productId) { Iterable<Product> products = this._db.products().getById(productId); return products.iterator().hasNext(); } @Override public Product get(UUID productId) { Iterable<Product> products = this._db.products().getById(productId); Iterator<Product> it = products.iterator(); if(it.hasNext()){ return it.next(); } return null; } @Override public void update(Product product) { if(product == null){ return; } if(this.exists(product.getId())){ this._db.products().update(product); } else { this._db.products().insert(product); } } @Override public boolean delete(UUID productId) { if(!this.exists(productId)){ return false; } this._db.products().delete(Product.getDeletable(productId)); return !this.exists(productId); } private static final String IMAGES_FOLDER = "ProductImages"; private static final String IMAGE_FILE_EXTENSION = ".png"; @Override public boolean hasImage(UUID productId) { try { String filename = this.toFilename(productId, IMAGE_FILE_EXTENSION); return this._fileSystem.exists(IMAGES_FOLDER, filename); } catch (Throwable ex){ ex.printStackTrace(); return false; } } @Override public Bitmap getImageOf(UUID productId) { String filename = this.toFilename(productId, IMAGE_FILE_EXTENSION); byte[] content = this._fileSystem.load(IMAGES_FOLDER, filename); return BitmapFactory.decodeByteArray(content,0,content.length); } @Override public void storeImageOf(UUID productId, Bitmap image) { try { String filename = this.toFilename(productId, IMAGE_FILE_EXTENSION); byte[] content = ImageUtil.toByteArray(image); this._fileSystem.store(IMAGES_FOLDER, filename, content); } catch (Throwable ex){ ex.printStackTrace(); } } private String toFilename(UUID id, String fileExtension){ return id.toString() + fileExtension; } }
3e08ae56968ee6807a00d028a2dffb6d6635cbec
1,158
java
Java
locatr/src/main/java/com/example/locatr/LocatrActivity.java
jhwsx/AndroidProgramming
25849a700e4e3483e5833c06d729c4b963646315
[ "MIT" ]
null
null
null
locatr/src/main/java/com/example/locatr/LocatrActivity.java
jhwsx/AndroidProgramming
25849a700e4e3483e5833c06d729c4b963646315
[ "MIT" ]
null
null
null
locatr/src/main/java/com/example/locatr/LocatrActivity.java
jhwsx/AndroidProgramming
25849a700e4e3483e5833c06d729c4b963646315
[ "MIT" ]
null
null
null
31.297297
83
0.643351
3,671
package com.example.locatr; import android.app.Dialog; import android.content.DialogInterface; import android.support.v4.app.Fragment; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; public class LocatrActivity extends SingleFragmentActivity { private static final int REQUEST_ERROR = 0; @Override protected Fragment createFragment() { return LocatrFragment.newInstance(); } @Override protected void onResume() { super.onResume(); // 检查是否有可用的Googleplay服务 int errorCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (errorCode != ConnectionResult.SUCCESS) { Dialog errorDialog = GooglePlayServicesUtil .getErrorDialog(errorCode, this, REQUEST_ERROR, new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // Leave if services are unavailable finish(); } }); errorDialog.show(); } } }
3e08af17b07624af7b92160cf6491ce3413b9483
2,688
java
Java
src/main/java/com/GeneratorJson.java
Amikh/java_library
40bd2c8622ab9ae39d03b05e32dc2f6ca6eca38a
[ "Apache-2.0" ]
null
null
null
src/main/java/com/GeneratorJson.java
Amikh/java_library
40bd2c8622ab9ae39d03b05e32dc2f6ca6eca38a
[ "Apache-2.0" ]
2
2020-11-02T15:55:10.000Z
2021-05-17T10:53:05.000Z
src/main/java/com/GeneratorJson.java
Amikh/java_library
40bd2c8622ab9ae39d03b05e32dc2f6ca6eca38a
[ "Apache-2.0" ]
null
null
null
33.185185
91
0.575521
3,672
package com; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import javax.json.Json; import javax.json.stream.JsonGenerator; import lombok.extern.log4j.Log4j; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser; @Log4j public class GeneratorJson { public void isCreateJSON(){ FileWriter writer = null; JSONParser parser = new JSONParser(); Object simpleObj = null; try { String p = "C:/TEMP/"; isCheckIfFolderPresent(p); writer = new FileWriter(p+"test.json"); } catch (IOException e) { e.printStackTrace(); } // JsonGenerator to create JSONObject and store it to file location mentioned above JsonGenerator generator = Json.createGenerator(writer); generator .writeStartObject().writeStartArray("Company") .writeStartObject() .write("name", "AM") .write("address", "NYC") .writeStartObject("support") .write("JAVA", "text") .write("Node", "JS") .writeStartArray("products") .write("AA").write("BB").write("CC") .writeEnd() .writeEnd() .writeEnd() .writeEnd().writeEnd(); generator.close(); try { simpleObj = parser.parse(new FileReader("C:/TEMP/test.json")); } catch (IOException | ParseException e) { e.printStackTrace(); } assert simpleObj != null; System.out.println( crucifyPrettyJSONUtility(simpleObj.toString())); } // JSON Utility public static String crucifyPrettyJSONUtility(String simpleJSON) { JsonObject json = JsonParser.parseString(simpleJSON).getAsJsonObject(); Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); return prettyGson.toJson(json); } //Function for check if folder is present and make if is not. public void isCheckIfFolderPresent(String path){ System.out.println("Path for check "+ path); File f = new File(path); if (f.exists() && f.isDirectory()) { log.info("Folder is present"); }else{ log.info("Folder don't present, start create folder in path :" + path); f.mkdirs(); } } }
3e08b01cac1f450ae940e5fa6d27a6b900d84a34
5,447
java
Java
Samples/MaxstARSample/src/main/java/com/maxst/ar/sample/wearable/WearableDeviceRenderer.java
m-wrona/android-ar
ba6863efa4bc188379445882fdd16766886cd3cc
[ "MIT" ]
null
null
null
Samples/MaxstARSample/src/main/java/com/maxst/ar/sample/wearable/WearableDeviceRenderer.java
m-wrona/android-ar
ba6863efa4bc188379445882fdd16766886cd3cc
[ "MIT" ]
null
null
null
Samples/MaxstARSample/src/main/java/com/maxst/ar/sample/wearable/WearableDeviceRenderer.java
m-wrona/android-ar
ba6863efa4bc188379445882fdd16766886cd3cc
[ "MIT" ]
null
null
null
37.826389
134
0.760969
3,673
/* * Copyright 2017 Maxst, Inc. All Rights Reserved. */ package com.maxst.ar.sample.wearable; import android.app.Activity; import android.graphics.Bitmap; import android.opengl.GLES20; import android.opengl.GLSurfaceView.Renderer; import com.maxst.ar.CameraDevice; import com.maxst.ar.MaxstAR; import com.maxst.ar.MaxstARUtil; import com.maxst.ar.Trackable; import com.maxst.ar.TrackerManager; import com.maxst.ar.TrackingResult; import com.maxst.ar.TrackingState; import com.maxst.ar.WearableCalibration; import com.maxst.ar.sample.arobject.TexturedCubeRenderer; import com.maxst.ar.wearable.WearableDeviceController; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; class WearableDeviceRenderer implements Renderer { public static final String TAG = WearableDeviceRenderer.class.getSimpleName(); private TexturedCubeRenderer texturedCubeRenderer; private int surfaceWidth; private int surfaceHeight; private final Activity activity; private float[] leftEyeProjectionMatrix; private float[] rightEyeProjectionMatrix; private float[] rightEyeViewport; private float[] leftEyeViewport; private WearableDeviceController wearableDeviceController; WearableDeviceRenderer(Activity activity, WearableDeviceController wearableDeviceController) { this.activity = activity; this.wearableDeviceController = wearableDeviceController; } @Override public void onSurfaceCreated(GL10 unused, EGLConfig config) { GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); Bitmap bitmap = MaxstARUtil.getBitmapFromAsset("MaxstAR_Cube.png", activity.getAssets()); texturedCubeRenderer = new TexturedCubeRenderer(); texturedCubeRenderer.setTextureBitmap(bitmap); } @Override public void onSurfaceChanged(GL10 unused, int width, int height) { surfaceWidth = width; surfaceHeight = height; MaxstAR.onSurfaceChanged(surfaceWidth, surfaceHeight); WearableCalibration.getInstance().setSurfaceSize(surfaceWidth, surfaceHeight); leftEyeProjectionMatrix = WearableCalibration.getInstance().getProjectionMatrix(WearableCalibration.EyeType.EYE_LEFT.getValue()); rightEyeProjectionMatrix = WearableCalibration.getInstance().getProjectionMatrix(WearableCalibration.EyeType.EYE_RIGHT.getValue()); leftEyeViewport = WearableCalibration.getInstance().getViewport(WearableCalibration.EyeType.EYE_LEFT); rightEyeViewport = WearableCalibration.getInstance().getViewport(WearableCalibration.EyeType.EYE_RIGHT); } @Override public void onDrawFrame(GL10 unused) { GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); GLES20.glViewport(0, 0, surfaceWidth, surfaceHeight); TrackingState state = TrackerManager.getInstance().updateTrackingState(); renderFrame(state); } private void renderFrame(TrackingState state) { if (wearableDeviceController.isSupportedWearableDevice()) { GLES20.glViewport((int) leftEyeViewport[0], (int) leftEyeViewport[1], (int) leftEyeViewport[2], (int) leftEyeViewport[3]); GLES20.glEnable(GLES20.GL_DEPTH_TEST); TrackingResult trackingResult = state.getTrackingResult(); for (int i = 0; i < trackingResult.getCount(); i++) { Trackable trackable = trackingResult.getTrackable(i); texturedCubeRenderer.setProjectionMatrix(leftEyeProjectionMatrix); texturedCubeRenderer.setTransform(trackable.getPoseMatrix()); texturedCubeRenderer.setTranslate(0, 0, -0.005f); texturedCubeRenderer.setScale(0.26f, 0.18f, 0.01f); texturedCubeRenderer.draw(); } GLES20.glViewport((int) rightEyeViewport[0], (int) rightEyeViewport[1], (int) rightEyeViewport[2], (int) rightEyeViewport[3]); GLES20.glEnable(GLES20.GL_DEPTH_TEST); trackingResult = state.getTrackingResult(); for (int i = 0; i < trackingResult.getCount(); i++) { Trackable trackable = trackingResult.getTrackable(i); texturedCubeRenderer.setProjectionMatrix(rightEyeProjectionMatrix); texturedCubeRenderer.setTransform(trackable.getPoseMatrix()); texturedCubeRenderer.setTranslate(0, 0, -0.005f); texturedCubeRenderer.setScale(0.26f, 0.18f, 0.01f); texturedCubeRenderer.draw(); } } else { TrackingResult trackingResult = state.getTrackingResult(); float[] projectionMatrix = CameraDevice.getInstance().getProjectionMatrix(); GLES20.glViewport(0, 0, surfaceWidth / 2, surfaceHeight); GLES20.glEnable(GLES20.GL_DEPTH_TEST); for (int i = 0; i < trackingResult.getCount(); i++) { Trackable trackable = trackingResult.getTrackable(i); texturedCubeRenderer.setProjectionMatrix(projectionMatrix); texturedCubeRenderer.setTransform(trackable.getPoseMatrix()); texturedCubeRenderer.setTranslate(0, 0, -0.005f); texturedCubeRenderer.setScale(0.26f, 0.18f, 0.01f); texturedCubeRenderer.draw(); } GLES20.glViewport(surfaceWidth / 2, 0, surfaceWidth / 2, surfaceHeight); GLES20.glEnable(GLES20.GL_DEPTH_TEST); for (int i = 0; i < trackingResult.getCount(); i++) { Trackable trackable = trackingResult.getTrackable(i); texturedCubeRenderer.setProjectionMatrix(projectionMatrix); texturedCubeRenderer.setTransform(trackable.getPoseMatrix()); texturedCubeRenderer.setTranslate(0, 0, -0.005f); texturedCubeRenderer.setScale(0.26f, 0.18f, 0.01f); texturedCubeRenderer.draw(); } } } }
3e08b08ebe91182bf2e8c0ee0f38c15eb4154efb
2,032
java
Java
projwiz-core/src/main/java/com/dwarfeng/projwiz/core/model/obv/FileObverser.java
DwArFeng/ProjWizard
ed6003ae92e6490fea94b5a2765b5e4492a11d88
[ "Apache-2.0" ]
null
null
null
projwiz-core/src/main/java/com/dwarfeng/projwiz/core/model/obv/FileObverser.java
DwArFeng/ProjWizard
ed6003ae92e6490fea94b5a2765b5e4492a11d88
[ "Apache-2.0" ]
null
null
null
projwiz-core/src/main/java/com/dwarfeng/projwiz/core/model/obv/FileObverser.java
DwArFeng/ProjWizard
ed6003ae92e6490fea94b5a2765b5e4492a11d88
[ "Apache-2.0" ]
null
null
null
18.814815
80
0.563976
3,674
package com.dwarfeng.projwiz.core.model.obv; import com.dwarfeng.dutil.basic.prog.Obverser; import com.dwarfeng.projwiz.core.model.struct.FileProcessor; public interface FileObverser extends Obverser { /** * 通知访问时间发生改变。 * * @param oldValue * 旧的访问时间。 * @param newValue * 新的访问时间。 */ public void fireAccessTimeChanged(long oldValue, long newValue); /** * 通知指定的文件的指定标签所在的输入流被关闭。 * * @param label * 指定的标签。 */ public void fireInputClosed(String label); /** * 通知指定的文件的指定标签所在的输入流被打开。 * * @param label * 指定的标签。 */ public void fireInputOpened(String label); /** * 通知指定的标签被添加。 * * @param label * 指定的标签。 */ public void fireLabelAdded(String label); /** * 通知指定的标签被移除。 * * @param label * 指定的标签。 */ public void fireLabelRemoved(String label); /** * 通知文件的长度发生改变。 * * @param oldValue * 旧的长度。 * @param newValue * 新的长度。 */ public void fireLengthChanged(long oldValue, long newValue); /** * 通知编辑时间发生改变。 * * @param oldValue * 旧的编辑时间。 * @param newValue * 新的编辑时间。 */ public void fireModifyTimeChanged(long oldValue, long newValue); /** * 通知文件的占用大小发生了改变。 * * @param oldValue * 旧的占用大小。 * @param newValue * 新的占用大小。 */ public void fireOccupiedSizeChanged(long oldValue, long newValue); /** * 通知是定的文件的指定标签所在的输出流被关闭。 * * @param label * 指定的标签。 */ public void fireOutputClosed(String label); /** * 通知指定的文件的指定标签所在的输出流被打开。 * * @param label * 指定的标签。 */ public void fireOutputOpened(String label); /** * 通知文件的处理器类发生了改变。 * * @param oldValue * 旧的处理器类。 * @param newValue * 新的处理器类。 */ public void fireProcessorClassChanged(Class<? extends FileProcessor> oldValue, Class<? extends FileProcessor> newValue); }
3e08b0984d27440d161a4c59b3b15a7e9eba23bc
3,257
java
Java
felsenstein_gui/BufferedCanvas.java
birc-aeh/coalescent_dk
d5c99c75edf98e8e5131a96b444f6bdc04ebd107
[ "MIT" ]
null
null
null
felsenstein_gui/BufferedCanvas.java
birc-aeh/coalescent_dk
d5c99c75edf98e8e5131a96b444f6bdc04ebd107
[ "MIT" ]
null
null
null
felsenstein_gui/BufferedCanvas.java
birc-aeh/coalescent_dk
d5c99c75edf98e8e5131a96b444f6bdc04ebd107
[ "MIT" ]
null
null
null
20.878205
79
0.583666
3,675
import java.awt.*; /** * Canvas keeping an off-screen copy of its contents to be * able to respond to paint events. * * @author Anders Mikkelsen */ public class BufferedCanvas extends Canvas { /** * Dimension * */ protected int width, height; /** * Buffer image */ protected Image ib; /** * Graphics for buffer image */ protected Graphics ig; /** * Construct new buffered canvas * * @param width the desired width of the new canvas * @param height the desired height of the new canvas */ public BufferedCanvas(int width, int height) { this.width = width; this.height = height; setSize(width,height); } /** * Create buffer image when connecting to native code * */ public void addNotify() { super.addNotify(); ib = createImage(width,height); ig = ib.getGraphics(); } /** * Redraw canvas from buffer image * * @param g graphics for this canvas */ public void paint(Graphics g) { super.paint(g); if (ib != null) g.drawImage(ib,0,0,this); } /** * Set pen color * * @param g graphics for this canvas * @param c new pen color */ protected void setRenderColor(Graphics g, Color c) { g.setColor(c); ig.setColor(c); } /** * Draw a circle on canvas and buffer image * * @param g graphics for this canvas * @param x x-coordinate of center * @param y y-coordinate of center * @param diameter diameter of circle */ protected void renderCircle(Graphics g, int x, int y, int diameter) { x -= diameter/2; y -= diameter/2; g.drawOval(x,y,diameter,diameter); ig.drawOval(x,y,diameter,diameter); } /** * Draw a filled circle * * @param g graphics for this canvas * @param x x-coordinate of center * @param y y-coordinate of center * @param diameter diameter */ protected void renderFilledCircle(Graphics g, int x, int y, int diameter) { x -= diameter/2; y -= diameter/2; g.fillOval(x,y,diameter,diameter); ig.fillOval(x,y,diameter,diameter); } /** * Draw a filled rectangle * * @param g graphics for this canvas * @param x1 top left x-coordinate * @param y1 top left y-coordinate * @param x2 bottom right x-coordinate * @param y2 bottom right y-coordinate */ protected void renderFilledRect(Graphics g, int x1, int y1, int x2, int y2) { g.fillRect(x1,y1,x2,y2); ig.fillRect(x1,y1,x2,y2); } /** * Draw a line * * @param g graphics for this canvas * @param x1 top left x-coordinate * @param y1 top left y-coordinate * @param x2 bottom right x-coordinate * @param y2 bottom right y-coordinate */ protected void renderLine(Graphics g, int x1, int y1, int x2, int y2) { g.drawLine(x1,y1,x2,y2); ig.drawLine(x1,y1,x2,y2); } /** * Erase to background color * */ protected void clearToBack() { Graphics g = getGraphics(); setRenderColor(g,getBackground()); renderFilledRect(g,0,0,width,height); } }
3e08b16f3909c67bd02073585637ccdceac02c31
866
java
Java
src/com/yu/demo/utils/DataSouceUtils.java
Thinker-ypp/CustomerManageSystem
c7935c38c0b4e6f1666ec3ba181d6fcbac312fc9
[ "Apache-2.0" ]
1
2019-06-14T02:02:21.000Z
2019-06-14T02:02:21.000Z
src/com/yu/demo/utils/DataSouceUtils.java
Thinker-ypp/CustomerManageSystem
c7935c38c0b4e6f1666ec3ba181d6fcbac312fc9
[ "Apache-2.0" ]
null
null
null
src/com/yu/demo/utils/DataSouceUtils.java
Thinker-ypp/CustomerManageSystem
c7935c38c0b4e6f1666ec3ba181d6fcbac312fc9
[ "Apache-2.0" ]
null
null
null
21.65
70
0.657044
3,676
package com.yu.demo.utils; import com.mchange.v2.c3p0.ComboPooledDataSource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; /** * 数据库工具类 * * @version v0.0.1 * @author: yupanpan * @since: 2018-02-27 9:08 */ public class DataSouceUtils { private static ComboPooledDataSource comboPooledDataSource = null; static { //会自动寻找数据库,节点就是mysql数据库(默认的也是mysql) comboPooledDataSource = new ComboPooledDataSource(); } /*获取数据库*/ public static DataSource getDataSource(){ return comboPooledDataSource; } /*获取连接初始化数据库*/ public static Connection getConnection(){ try { return comboPooledDataSource.getConnection(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException("数据库初始化失败!!!"); } } }
3e08b18d5583ecef3053ae1bebc313267d9edcb6
5,210
java
Java
src/main/java/rsb/plugin/ScriptPanel.java
GigiaJ/RSB
4707d229f9c214132268c04b027e8e553496c3e4
[ "BSD-3-Clause" ]
11
2020-03-24T13:06:14.000Z
2021-11-18T20:38:51.000Z
src/main/java/rsb/plugin/ScriptPanel.java
GigiaJ/RSB
4707d229f9c214132268c04b027e8e553496c3e4
[ "BSD-3-Clause" ]
45
2020-03-22T22:56:23.000Z
2022-01-20T18:35:04.000Z
src/main/java/rsb/plugin/ScriptPanel.java
GigiaJ/RSB
4707d229f9c214132268c04b027e8e553496c3e4
[ "BSD-3-Clause" ]
14
2020-04-07T03:43:58.000Z
2022-01-20T02:26:11.000Z
35.931034
182
0.718426
3,677
package rsb.plugin; import rsb.botLauncher.RuneLite; import rsb.gui.AccountManager; import rsb.gui.BotToolBar; import rsb.gui.ScriptSelector; import rsb.internal.ScriptHandler; import rsb.script.Script; import rsb.script.ScriptManifest; import java.awt.event.*; import java.util.Map; import javax.swing.*; import javax.swing.GroupLayout; public class ScriptPanel extends JPanel { private RuneLite bot; private JScrollPane scrollPane1; private JTable table1; private JComboBox comboBoxAccounts; private JButton buttonStart; private JButton buttonPause; private JButton buttonStop; public ScriptPanel(RuneLite bot) { this.bot = bot; initComponents(); } /** * @author GigiaJ * @description Sets the action to occur when the pause button is pressed. * * @param e */ private void buttonPauseActionPerformed(ActionEvent e) { ScriptHandler sh = bot.getScriptHandler(); Map<Integer, Script> running = sh.getRunningScripts(); if (running.size() > 0) { int id = running.keySet().iterator().next(); sh.pauseScript(id); //Swaps the displayed text if (buttonPause.getText().equals("Pause")) { buttonPause.setText("Play"); } else { buttonPause.setText("Pause"); } } } /** * @author GigiaJ * @description Sets the action to occur when the stop button is pressed. * * @param e */ private void buttonStopActionPerformed(ActionEvent e) { //Sets the value back to Pause if (buttonPause.getText().equals("Play")) { buttonPause.setText("Pause"); } ScriptHandler sh = bot.getScriptHandler(); Map<Integer, Script> running = sh.getRunningScripts(); if (running.size() > 0) { int id = running.keySet().iterator().next(); Script s = running.get(id); //ScriptManifest prop = s.getClass().getAnnotation(ScriptManifest.class); //int result = JOptionPane.showConfirmDialog(this, "Would you like to stop the script " + prop.name() + "?", "Script", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); //if (result == JOptionPane.OK_OPTION) { sh.stopScript(id); //} } } private void initComponents() { ScriptSelector scriptSelector = new ScriptSelector(bot); scrollPane1 = new JScrollPane(); table1 = scriptSelector.getTable(0, 70, 30, 70); comboBoxAccounts = scriptSelector.getAccounts(); buttonStart = scriptSelector.getSubmit(); //Make a search area scriptSelector.getSearch(); scriptSelector.load(); buttonPause = new JButton(); buttonStop = new JButton(); //======== this ======== setBorder (new javax. swing. border. CompoundBorder( new javax .swing .border .TitledBorder (new javax. swing. border. EmptyBorder( 0 , 0, 0, 0) , "", javax. swing. border. TitledBorder. CENTER, javax. swing. border. TitledBorder. BOTTOM , new java .awt .Font ("D\u0069alog" ,java .awt .Font .BOLD ,12 ), java. awt. Color. red) , getBorder( )) ); addPropertyChangeListener (new java. beans. PropertyChangeListener( ){ @Override public void propertyChange (java .beans .PropertyChangeEvent e ) {if ("\u0062order" .equals (e .getPropertyName () )) throw new RuntimeException( ); }} ); //======== scrollPane1 ======== { scrollPane1.setViewportView(table1); } //---- buttonPause ---- buttonPause.setText("Pause"); buttonPause.addActionListener(e -> buttonPauseActionPerformed(e)); //---- buttonStop ---- buttonStop.setText("Stop"); buttonStop.addActionListener(e -> buttonStopActionPerformed(e)); GroupLayout layout = new GroupLayout(this); setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup() .addComponent(scrollPane1, GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup() .addGroup(layout.createSequentialGroup() .addGap(47, 47, 47) .addComponent(comboBoxAccounts, GroupLayout.PREFERRED_SIZE, 157, GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(buttonStart, GroupLayout.PREFERRED_SIZE, 101, GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(buttonPause, GroupLayout.PREFERRED_SIZE, 106, GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(73, 73, 73) .addComponent(buttonStop, GroupLayout.PREFERRED_SIZE, 95, GroupLayout.PREFERRED_SIZE))) .addContainerGap(30, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup() .addGroup(layout.createSequentialGroup() .addComponent(scrollPane1, GroupLayout.PREFERRED_SIZE, 293, GroupLayout.PREFERRED_SIZE) .addGap(28, 28, 28) .addComponent(comboBoxAccounts, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGap(57, 57, 57) .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(buttonStart, GroupLayout.PREFERRED_SIZE, 33, GroupLayout.PREFERRED_SIZE) .addComponent(buttonPause, GroupLayout.PREFERRED_SIZE, 33, GroupLayout.PREFERRED_SIZE)) .addGap(28, 28, 28) .addComponent(buttonStop, GroupLayout.PREFERRED_SIZE, 36, GroupLayout.PREFERRED_SIZE) .addGap(0, 60, Short.MAX_VALUE)) ); } }
3e08b2a85e156ae9b2d9b31f43677ac9ef747699
10,960
java
Java
src/main/java/com/yworks/yshrink/util/Util.java
Hassan-Elseoudy/yGuard
800d8849885e8f9c3b9203cbbc1af41c2a8e4106
[ "MIT" ]
216
2019-11-12T10:05:31.000Z
2022-03-28T21:32:20.000Z
src/main/java/com/yworks/yshrink/util/Util.java
Hassan-Elseoudy/yGuard
800d8849885e8f9c3b9203cbbc1af41c2a8e4106
[ "MIT" ]
82
2019-11-18T12:41:58.000Z
2022-03-28T10:37:07.000Z
src/main/java/com/yworks/yshrink/util/Util.java
Hassan-Elseoudy/yGuard
800d8849885e8f9c3b9203cbbc1af41c2a8e4106
[ "MIT" ]
41
2019-11-13T15:02:46.000Z
2022-03-23T09:23:37.000Z
28.842105
111
0.510401
3,678
package com.yworks.yshrink.util; import org.objectweb.asm.Type; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * The type Util. * * @author Michael Schroeder, yWorks GmbH http://www.yworks.com */ public class Util { /** * To java class string. * * @param className the class name * @return the string */ public static final String toJavaClass( String className ) { if ( className.endsWith( ".class" ) ) { className = className.substring( 0, className.length() - 6 ); } return className.replace( '/', '.' ); } /** * To internal class string. * * @param className the class name * @return the string */ public static final String toInternalClass( String className ) { if ( className.endsWith( ".class" ) ) { className = className.substring( 0, className.length() - 6 ); } return className.replace( '.', '/' ); } private static final String toNativeType( String type, int arraydim ) { StringBuffer nat = new StringBuffer( 30 ); for ( int i = 0; i < arraydim; i++ ) { nat.append( '[' ); } if ( "byte".equals( type ) ) { nat.append( 'B' ); } else if ( "char".equals( type ) ) { nat.append( 'C' ); } else if ( "double".equals( type ) ) { nat.append( 'D' ); } else if ( "float".equals( type ) ) { nat.append( 'F' ); } else if ( "int".equals( type ) ) { nat.append( 'I' ); } else if ( "long".equals( type ) ) { nat.append( 'J' ); } else if ( "short".equals( type ) ) { nat.append( 'S' ); } else if ( "boolean".equals( type ) ) { nat.append( 'Z' ); } else if ( "void".equals( type ) ) { nat.append( 'V' ); } else { //Lclassname; nat.append( 'L' ); nat.append( type.replace( '.', '/' ) ); nat.append( ';' ); } return nat.toString(); } /** * Verbose to native type string. * * @param type the type * @return the string */ public static final String verboseToNativeType( String type ) { if ( type == "" ) return null; Pattern p = Pattern.compile( "\\s*\\[\\s*\\]\\s*" ); Matcher m = p.matcher( type ); int arrayDim = 0; while ( m.find() ) { arrayDim++; } return toNativeType( type.substring( 0, type.length()-(arrayDim*2)), arrayDim ); } /** * extracts the class name or primitve identifier from any type descriptor. * e.g. [[Ltest/ugly/JJ {@literal ->} test/ugly/JJ * * @param desc the desc * @return the extracted class name or primitive identifier. */ public static final String getTypeNameFromDescriptor( final String desc ) { String r = desc; final int i = desc.lastIndexOf( '[' ); if ( i != -1 ) { final char type = desc.charAt( i + 1 ); if ( type != 'L' ) { r = String.valueOf( type ); } else { r = desc.substring( i + 2, desc.length() - 1 ); } } else { if ( desc.endsWith(";") ) { r = desc.substring( 1, desc.length() - 1 ); } } return r; } /** * To java type string. * * @param type the type * @return the string */ public static String toJavaType( String type ) { StringBuffer nat = new StringBuffer( 30 ); int arraydim = 0; while ( type.charAt( arraydim ) == '[' ) arraydim++; type = type.substring( arraydim ); switch ( type.charAt( 0 ) ) { default: throw new IllegalArgumentException( "unknown native type:" + type ); case 'B': nat.append( "byte" ); break; case 'C': nat.append( "char" ); break; case 'D': nat.append( "double" ); break; case 'F': nat.append( "float" ); break; case 'I': nat.append( "int" ); break; case 'J': nat.append( "long" ); break; case 'S': nat.append( "short" ); break; case 'Z': nat.append( "boolean" ); break; case 'V': nat.append( "void" ); break; case 'L': String className = type.substring( 1, type.length() - 1 ); if ( className.indexOf( '<' ) >= 0 ) { String parameters = type.substring( className.indexOf( '<' ) + 2, className.lastIndexOf( '>' ) - 1 ); className = className.substring( 0, className.indexOf( '<' ) ); nat.append( className.replace( '/', '.' ) ); nat.append( '<' ); nat.append( toJavaParameters( parameters ) ); nat.append( '>' ); } else { nat.append( className.replace( '/', '.' ) ); } break; } for ( int i = 0; i < arraydim; i++ ) { nat.append( "[]" ); } return nat.toString(); } /** * To java parameters string. * * @param parameters the parameters * @return the string */ public static String toJavaParameters( String parameters ) { StringBuffer nat = new StringBuffer( 30 ); switch ( parameters.charAt( 0 ) ) { default: throw new IllegalArgumentException( "unknown native type:" + parameters.charAt( 0 ) ); case '+': nat.append( "? extends " ).append( toJavaParameters( parameters.substring( 1 ) ) ); break; case '-': nat.append( "? super " ).append( toJavaParameters( parameters.substring( 1 ) ) ); break; case '*': nat.append( "*" ); if ( parameters.length() > 1 ) { nat.append( ", " ).append( toJavaParameters( parameters.substring( 1 ) ) ); } break; case 'B': nat.append( "byte" ); break; case 'C': nat.append( "char" ); break; case 'D': nat.append( "double" ); break; case 'F': nat.append( "float" ); break; case 'I': nat.append( "int" ); break; case 'J': nat.append( "long" ); break; case 'S': nat.append( "short" ); break; case 'Z': nat.append( "boolean" ); break; case 'V': nat.append( "void" ); break; case 'L': int len = parameters.indexOf( '<' ); if ( len >= 0 ) { len = Math.min( len, parameters.indexOf( ';' ) ); } break; case 'T': int index = parameters.indexOf( ';' ); nat.append( parameters.substring( 1, index ) ); if ( parameters.length() > index ) { nat.append( ", " ); nat.append( parameters.substring( index ) ); } break; } return nat.toString(); } /** * Gets argument string. * * @param arguments the arguments * @return the argument string */ public static final String getArgumentString( Type[] arguments ) { StringBuilder buf = new StringBuilder(); for ( int i = 0; i < arguments.length - 1; i++ ) { buf.append( Util.toJavaType( arguments[ i ].getDescriptor() ) ).append( "," ); } if ( arguments.length > 0 ) { buf.append( Util.toJavaType( arguments[ arguments.length - 1 ].getDescriptor() ) ); } return buf.toString(); } /** * To native method string [ ]. * * @param javaMethod the java method * @return the string [ ] */ public static final String[] toNativeMethod( String javaMethod ) { StringTokenizer tokenizer = new StringTokenizer( javaMethod, "(,[]) ", true ); String tmp = tokenizer.nextToken(); ; while ( tmp.trim().length() == 0 ) { tmp = tokenizer.nextToken(); } String returnType = tmp; tmp = tokenizer.nextToken(); int retarraydim = 0; while ( tmp.equals( "[" ) ) { tmp = tokenizer.nextToken(); if ( !tmp.equals( "]" ) ) throw new IllegalArgumentException( "']' expected but found " + tmp ); retarraydim++; tmp = tokenizer.nextToken(); } if ( tmp.trim().length() != 0 ) { throw new IllegalArgumentException( "space expected but found " + tmp ); } tmp = tokenizer.nextToken(); while ( tmp.trim().length() == 0 ) { tmp = tokenizer.nextToken(); } String name = tmp; StringBuffer nativeMethod = new StringBuffer( 30 ); nativeMethod.append( '(' ); tmp = tokenizer.nextToken(); while ( tmp.trim().length() == 0 ) { tmp = tokenizer.nextToken(); } if ( !tmp.equals( "(" ) ) throw new IllegalArgumentException( "'(' expected but found " + tmp ); tmp = tokenizer.nextToken(); while ( !tmp.equals( ")" ) ) { while ( tmp.trim().length() == 0 ) { tmp = tokenizer.nextToken(); } String type = tmp; tmp = tokenizer.nextToken(); while ( tmp.trim().length() == 0 ) { tmp = tokenizer.nextToken(); } int arraydim = 0; while ( tmp.equals( "[" ) ) { tmp = tokenizer.nextToken(); if ( !tmp.equals( "]" ) ) throw new IllegalArgumentException( "']' expected but found " + tmp ); arraydim++; tmp = tokenizer.nextToken(); } while ( tmp.trim().length() == 0 ) { tmp = tokenizer.nextToken(); } nativeMethod.append( toNativeType( type, arraydim ) ); if ( tmp.equals( "," ) ) { tmp = tokenizer.nextToken(); while ( tmp.trim().length() == 0 ) { tmp = tokenizer.nextToken(); } continue; } } nativeMethod.append( ')' ); nativeMethod.append( toNativeType( returnType, retarraydim ) ); String[] result = new String[]{ name, nativeMethod.toString() }; return result; } /** * Encode a byte[] as a Base64 (see RFC1521, Section 5.2) String. */ private static final char[] base64 = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; private static final char pad = '='; /** * To base 64 string. * * @param b the b * @return the string */ public static String toBase64( byte[] b ) { StringBuffer sb = new StringBuffer(); for ( int ptr = 0; ptr < b.length; ptr += 3 ) { sb.append( base64[ ( b[ ptr ] >> 2 ) & 0x3F ] ); if ( ptr + 1 < b.length ) { sb.append( base64[ ( ( b[ ptr ] << 4 ) & 0x30 ) | ( ( b[ ptr + 1 ] >> 4 ) & 0x0F ) ] ); if ( ptr + 2 < b.length ) { sb.append( base64[ ( ( b[ ptr + 1 ] << 2 ) & 0x3C ) | ( ( b[ ptr + 2 ] >> 6 ) & 0x03 ) ] ); sb.append( base64[ b[ ptr + 2 ] & 0x3F ] ); } else { sb.append( base64[ ( b[ ptr + 1 ] << 2 ) & 0x3C ] ); sb.append( pad ); } } else { sb.append( base64[ ( ( b[ ptr ] << 4 ) & 0x30 ) ] ); sb.append( pad ); sb.append( pad ); } } return sb.toString(); } }
3e08b2cbba903f78ad1075f26ecbf7a69fa61208
2,247
java
Java
src/tests/junit/org/apache/tools/ant/types/FlexIntegerTest.java
Overruler/ant
66b5f3f06ba641ffd22428b8da4f8b14ff45db53
[ "Apache-2.0" ]
1
2022-01-25T03:48:11.000Z
2022-01-25T03:48:11.000Z
src/tests/junit/org/apache/tools/ant/types/FlexIntegerTest.java
changgengli/ant
f1930b0061d661e4b0a4072caacb19d35a61f370
[ "Apache-2.0" ]
null
null
null
src/tests/junit/org/apache/tools/ant/types/FlexIntegerTest.java
changgengli/ant
f1930b0061d661e4b0a4072caacb19d35a61f370
[ "Apache-2.0" ]
null
null
null
29.96
81
0.699154
3,679
/* * 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.tools.ant.types; import org.apache.tools.ant.BuildFileRule; import org.apache.tools.ant.Project; import org.apache.tools.ant.BuildException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import static org.junit.Assert.assertEquals; public class FlexIntegerTest { @Rule public BuildFileRule buildRule = new BuildFileRule(); @Before public void setUp() { buildRule.configureProject("src/etc/testcases/types/flexinteger.xml"); } @Test public void testFlexInteger() { buildRule.executeTarget("test"); assertEquals(buildRule.getProject().getProperty("flexint.value1"), "10"); assertEquals(buildRule.getProject().getProperty("flexint.value2"), "8"); } // This class acts as a custom Ant task also // and uses these variables/methods in that mode private Project taskProject; String propName; private FlexInteger value; public void setPropName(String propName) { this.propName = propName; } public void setValue(FlexInteger value) { this.value = value; } public void setProject(Project project) { taskProject = project; } public void execute() { if (propName == null || value == null) { throw new BuildException("name and value required"); } taskProject.setNewProperty(propName, value.toString()); } }
3e08b51820b722fedf7f74616eb6c4fc0d98af42
2,177
java
Java
backend_java_case/JavaFrame/CamelFrame/src/main/java/chapter3/transforming/OrderToCsvBeanTest.java
JUSTLOVELE/MobileDevStudy
ddcfd67d9ad66dd710fcbb355406bab3679ebaf7
[ "MIT" ]
1
2021-09-26T04:31:52.000Z
2021-09-26T04:31:52.000Z
backend_java_case/JavaFrame/CamelFrame/src/main/java/chapter3/transforming/OrderToCsvBeanTest.java
JUSTLOVELE/MobileDevStudy
ddcfd67d9ad66dd710fcbb355406bab3679ebaf7
[ "MIT" ]
null
null
null
backend_java_case/JavaFrame/CamelFrame/src/main/java/chapter3/transforming/OrderToCsvBeanTest.java
JUSTLOVELE/MobileDevStudy
ddcfd67d9ad66dd710fcbb355406bab3679ebaf7
[ "MIT" ]
1
2020-06-28T01:04:38.000Z
2020-06-28T01:04:38.000Z
37.534483
84
0.675701
3,680
/** * 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 chapter3.transforming; import java.io.File; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; /** * @version $Revision$ */ public class OrderToCsvBeanTest extends CamelTestSupport { @Test public void testOrderToCsvBean() throws Exception { // this is the inhouse format we want to transform to CSV String inhouse = "0000005555000001144120091209 2319@1108"; template.sendBodyAndHeader("direct:start", inhouse, "Date", "20091209"); File file = new File("D:\\logs\\inbox\\message2.csv"); assertTrue("File should exist", file.exists()); // compare the expected file content String body = context.getTypeConverter().convertTo(String.class, file); assertEquals("000000555,20091209,000001144,2319,1108", body); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start") // format inhouse to csv using a bean .bean(new OrderToCsvBean()) // and save it to a file .to("file:D:\\logs\\outbox?fileName=report-${header.Date}.csv"); } }; } }
3e08b5865071d62eab931c1064e194f94797c3e9
48,212
java
Java
proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/UpdateBackendBucketRequest.java
googleapis/java-compute
28bd65d278b162538195e71b7dbb3d83d909514c
[ "Apache-2.0" ]
19
2020-01-28T12:32:27.000Z
2022-02-12T07:48:33.000Z
proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/UpdateBackendBucketRequest.java
googleapis/java-compute
28bd65d278b162538195e71b7dbb3d83d909514c
[ "Apache-2.0" ]
458
2019-11-04T22:32:18.000Z
2022-03-30T00:03:12.000Z
proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/UpdateBackendBucketRequest.java
googleapis/java-compute
28bd65d278b162538195e71b7dbb3d83d909514c
[ "Apache-2.0" ]
23
2019-10-31T21:05:28.000Z
2021-08-24T16:35:45.000Z
35.476085
672
0.672032
3,681
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/compute/v1/compute.proto package com.google.cloud.compute.v1; /** * * * <pre> * A request message for BackendBuckets.Update. See the method description for details. * </pre> * * Protobuf type {@code google.cloud.compute.v1.UpdateBackendBucketRequest} */ public final class UpdateBackendBucketRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.compute.v1.UpdateBackendBucketRequest) UpdateBackendBucketRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateBackendBucketRequest.newBuilder() to construct. private UpdateBackendBucketRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateBackendBucketRequest() { backendBucket_ = ""; project_ = ""; requestId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateBackendBucketRequest(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private UpdateBackendBucketRequest( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 296879706: { java.lang.String s = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; requestId_ = s; break; } case 733712298: { java.lang.String s = input.readStringRequireUtf8(); backendBucket_ = s; break; } case 1820481738: { java.lang.String s = input.readStringRequireUtf8(); project_ = s; break; } case -1248905022: { com.google.cloud.compute.v1.BackendBucket.Builder subBuilder = null; if (backendBucketResource_ != null) { subBuilder = backendBucketResource_.toBuilder(); } backendBucketResource_ = input.readMessage( com.google.cloud.compute.v1.BackendBucket.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(backendBucketResource_); backendBucketResource_ = subBuilder.buildPartial(); } break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_UpdateBackendBucketRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_UpdateBackendBucketRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.UpdateBackendBucketRequest.class, com.google.cloud.compute.v1.UpdateBackendBucketRequest.Builder.class); } private int bitField0_; public static final int BACKEND_BUCKET_FIELD_NUMBER = 91714037; private volatile java.lang.Object backendBucket_; /** * * * <pre> * Name of the BackendBucket resource to update. * </pre> * * <code>string backend_bucket = 91714037 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The backendBucket. */ @java.lang.Override public java.lang.String getBackendBucket() { java.lang.Object ref = backendBucket_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); backendBucket_ = s; return s; } } /** * * * <pre> * Name of the BackendBucket resource to update. * </pre> * * <code>string backend_bucket = 91714037 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for backendBucket. */ @java.lang.Override public com.google.protobuf.ByteString getBackendBucketBytes() { java.lang.Object ref = backendBucket_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); backendBucket_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int BACKEND_BUCKET_RESOURCE_FIELD_NUMBER = 380757784; private com.google.cloud.compute.v1.BackendBucket backendBucketResource_; /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.BackendBucket backend_bucket_resource = 380757784 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the backendBucketResource field is set. */ @java.lang.Override public boolean hasBackendBucketResource() { return backendBucketResource_ != null; } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.BackendBucket backend_bucket_resource = 380757784 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The backendBucketResource. */ @java.lang.Override public com.google.cloud.compute.v1.BackendBucket getBackendBucketResource() { return backendBucketResource_ == null ? com.google.cloud.compute.v1.BackendBucket.getDefaultInstance() : backendBucketResource_; } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.BackendBucket backend_bucket_resource = 380757784 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.compute.v1.BackendBucketOrBuilder getBackendBucketResourceOrBuilder() { return getBackendBucketResource(); } public static final int PROJECT_FIELD_NUMBER = 227560217; private volatile java.lang.Object project_; /** * * * <pre> * Project ID for this request. * </pre> * * <code> * string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"]; * </code> * * @return The project. */ @java.lang.Override public java.lang.String getProject() { java.lang.Object ref = project_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); project_ = s; return s; } } /** * * * <pre> * Project ID for this request. * </pre> * * <code> * string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"]; * </code> * * @return The bytes for project. */ @java.lang.Override public com.google.protobuf.ByteString getProjectBytes() { java.lang.Object ref = project_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); project_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int REQUEST_ID_FIELD_NUMBER = 37109963; private volatile java.lang.Object requestId_; /** * * * <pre> * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). * </pre> * * <code>optional string request_id = 37109963;</code> * * @return Whether the requestId field is set. */ @java.lang.Override public boolean hasRequestId() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). * </pre> * * <code>optional string request_id = 37109963;</code> * * @return The requestId. */ @java.lang.Override public java.lang.String getRequestId() { java.lang.Object ref = requestId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestId_ = s; return s; } } /** * * * <pre> * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). * </pre> * * <code>optional string request_id = 37109963;</code> * * @return The bytes for requestId. */ @java.lang.Override public com.google.protobuf.ByteString getRequestIdBytes() { java.lang.Object ref = requestId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); requestId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 37109963, requestId_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(backendBucket_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 91714037, backendBucket_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 227560217, project_); } if (backendBucketResource_ != null) { output.writeMessage(380757784, getBackendBucketResource()); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(37109963, requestId_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(backendBucket_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(91714037, backendBucket_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(227560217, project_); } if (backendBucketResource_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 380757784, getBackendBucketResource()); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.compute.v1.UpdateBackendBucketRequest)) { return super.equals(obj); } com.google.cloud.compute.v1.UpdateBackendBucketRequest other = (com.google.cloud.compute.v1.UpdateBackendBucketRequest) obj; if (!getBackendBucket().equals(other.getBackendBucket())) return false; if (hasBackendBucketResource() != other.hasBackendBucketResource()) return false; if (hasBackendBucketResource()) { if (!getBackendBucketResource().equals(other.getBackendBucketResource())) return false; } if (!getProject().equals(other.getProject())) return false; if (hasRequestId() != other.hasRequestId()) return false; if (hasRequestId()) { if (!getRequestId().equals(other.getRequestId())) return false; } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + BACKEND_BUCKET_FIELD_NUMBER; hash = (53 * hash) + getBackendBucket().hashCode(); if (hasBackendBucketResource()) { hash = (37 * hash) + BACKEND_BUCKET_RESOURCE_FIELD_NUMBER; hash = (53 * hash) + getBackendBucketResource().hashCode(); } hash = (37 * hash) + PROJECT_FIELD_NUMBER; hash = (53 * hash) + getProject().hashCode(); if (hasRequestId()) { hash = (37 * hash) + REQUEST_ID_FIELD_NUMBER; hash = (53 * hash) + getRequestId().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.compute.v1.UpdateBackendBucketRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.UpdateBackendBucketRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.UpdateBackendBucketRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.UpdateBackendBucketRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.UpdateBackendBucketRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.UpdateBackendBucketRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.UpdateBackendBucketRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.UpdateBackendBucketRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.compute.v1.UpdateBackendBucketRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.UpdateBackendBucketRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.compute.v1.UpdateBackendBucketRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.UpdateBackendBucketRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.compute.v1.UpdateBackendBucketRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * A request message for BackendBuckets.Update. See the method description for details. * </pre> * * Protobuf type {@code google.cloud.compute.v1.UpdateBackendBucketRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.UpdateBackendBucketRequest) com.google.cloud.compute.v1.UpdateBackendBucketRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_UpdateBackendBucketRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_UpdateBackendBucketRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.UpdateBackendBucketRequest.class, com.google.cloud.compute.v1.UpdateBackendBucketRequest.Builder.class); } // Construct using com.google.cloud.compute.v1.UpdateBackendBucketRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); backendBucket_ = ""; if (backendBucketResourceBuilder_ == null) { backendBucketResource_ = null; } else { backendBucketResource_ = null; backendBucketResourceBuilder_ = null; } project_ = ""; requestId_ = ""; bitField0_ = (bitField0_ & ~0x00000001); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_UpdateBackendBucketRequest_descriptor; } @java.lang.Override public com.google.cloud.compute.v1.UpdateBackendBucketRequest getDefaultInstanceForType() { return com.google.cloud.compute.v1.UpdateBackendBucketRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.compute.v1.UpdateBackendBucketRequest build() { com.google.cloud.compute.v1.UpdateBackendBucketRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.compute.v1.UpdateBackendBucketRequest buildPartial() { com.google.cloud.compute.v1.UpdateBackendBucketRequest result = new com.google.cloud.compute.v1.UpdateBackendBucketRequest(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; result.backendBucket_ = backendBucket_; if (backendBucketResourceBuilder_ == null) { result.backendBucketResource_ = backendBucketResource_; } else { result.backendBucketResource_ = backendBucketResourceBuilder_.build(); } result.project_ = project_; if (((from_bitField0_ & 0x00000001) != 0)) { to_bitField0_ |= 0x00000001; } result.requestId_ = requestId_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.compute.v1.UpdateBackendBucketRequest) { return mergeFrom((com.google.cloud.compute.v1.UpdateBackendBucketRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.compute.v1.UpdateBackendBucketRequest other) { if (other == com.google.cloud.compute.v1.UpdateBackendBucketRequest.getDefaultInstance()) return this; if (!other.getBackendBucket().isEmpty()) { backendBucket_ = other.backendBucket_; onChanged(); } if (other.hasBackendBucketResource()) { mergeBackendBucketResource(other.getBackendBucketResource()); } if (!other.getProject().isEmpty()) { project_ = other.project_; onChanged(); } if (other.hasRequestId()) { bitField0_ |= 0x00000001; requestId_ = other.requestId_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.compute.v1.UpdateBackendBucketRequest parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.compute.v1.UpdateBackendBucketRequest) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object backendBucket_ = ""; /** * * * <pre> * Name of the BackendBucket resource to update. * </pre> * * <code>string backend_bucket = 91714037 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The backendBucket. */ public java.lang.String getBackendBucket() { java.lang.Object ref = backendBucket_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); backendBucket_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Name of the BackendBucket resource to update. * </pre> * * <code>string backend_bucket = 91714037 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for backendBucket. */ public com.google.protobuf.ByteString getBackendBucketBytes() { java.lang.Object ref = backendBucket_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); backendBucket_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Name of the BackendBucket resource to update. * </pre> * * <code>string backend_bucket = 91714037 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The backendBucket to set. * @return This builder for chaining. */ public Builder setBackendBucket(java.lang.String value) { if (value == null) { throw new NullPointerException(); } backendBucket_ = value; onChanged(); return this; } /** * * * <pre> * Name of the BackendBucket resource to update. * </pre> * * <code>string backend_bucket = 91714037 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearBackendBucket() { backendBucket_ = getDefaultInstance().getBackendBucket(); onChanged(); return this; } /** * * * <pre> * Name of the BackendBucket resource to update. * </pre> * * <code>string backend_bucket = 91714037 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for backendBucket to set. * @return This builder for chaining. */ public Builder setBackendBucketBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); backendBucket_ = value; onChanged(); return this; } private com.google.cloud.compute.v1.BackendBucket backendBucketResource_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.compute.v1.BackendBucket, com.google.cloud.compute.v1.BackendBucket.Builder, com.google.cloud.compute.v1.BackendBucketOrBuilder> backendBucketResourceBuilder_; /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.BackendBucket backend_bucket_resource = 380757784 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the backendBucketResource field is set. */ public boolean hasBackendBucketResource() { return backendBucketResourceBuilder_ != null || backendBucketResource_ != null; } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.BackendBucket backend_bucket_resource = 380757784 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The backendBucketResource. */ public com.google.cloud.compute.v1.BackendBucket getBackendBucketResource() { if (backendBucketResourceBuilder_ == null) { return backendBucketResource_ == null ? com.google.cloud.compute.v1.BackendBucket.getDefaultInstance() : backendBucketResource_; } else { return backendBucketResourceBuilder_.getMessage(); } } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.BackendBucket backend_bucket_resource = 380757784 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setBackendBucketResource(com.google.cloud.compute.v1.BackendBucket value) { if (backendBucketResourceBuilder_ == null) { if (value == null) { throw new NullPointerException(); } backendBucketResource_ = value; onChanged(); } else { backendBucketResourceBuilder_.setMessage(value); } return this; } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.BackendBucket backend_bucket_resource = 380757784 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setBackendBucketResource( com.google.cloud.compute.v1.BackendBucket.Builder builderForValue) { if (backendBucketResourceBuilder_ == null) { backendBucketResource_ = builderForValue.build(); onChanged(); } else { backendBucketResourceBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.BackendBucket backend_bucket_resource = 380757784 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeBackendBucketResource(com.google.cloud.compute.v1.BackendBucket value) { if (backendBucketResourceBuilder_ == null) { if (backendBucketResource_ != null) { backendBucketResource_ = com.google.cloud.compute.v1.BackendBucket.newBuilder(backendBucketResource_) .mergeFrom(value) .buildPartial(); } else { backendBucketResource_ = value; } onChanged(); } else { backendBucketResourceBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.BackendBucket backend_bucket_resource = 380757784 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearBackendBucketResource() { if (backendBucketResourceBuilder_ == null) { backendBucketResource_ = null; onChanged(); } else { backendBucketResource_ = null; backendBucketResourceBuilder_ = null; } return this; } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.BackendBucket backend_bucket_resource = 380757784 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.compute.v1.BackendBucket.Builder getBackendBucketResourceBuilder() { onChanged(); return getBackendBucketResourceFieldBuilder().getBuilder(); } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.BackendBucket backend_bucket_resource = 380757784 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.compute.v1.BackendBucketOrBuilder getBackendBucketResourceOrBuilder() { if (backendBucketResourceBuilder_ != null) { return backendBucketResourceBuilder_.getMessageOrBuilder(); } else { return backendBucketResource_ == null ? com.google.cloud.compute.v1.BackendBucket.getDefaultInstance() : backendBucketResource_; } } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.BackendBucket backend_bucket_resource = 380757784 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.compute.v1.BackendBucket, com.google.cloud.compute.v1.BackendBucket.Builder, com.google.cloud.compute.v1.BackendBucketOrBuilder> getBackendBucketResourceFieldBuilder() { if (backendBucketResourceBuilder_ == null) { backendBucketResourceBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.compute.v1.BackendBucket, com.google.cloud.compute.v1.BackendBucket.Builder, com.google.cloud.compute.v1.BackendBucketOrBuilder>( getBackendBucketResource(), getParentForChildren(), isClean()); backendBucketResource_ = null; } return backendBucketResourceBuilder_; } private java.lang.Object project_ = ""; /** * * * <pre> * Project ID for this request. * </pre> * * <code> * string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"]; * </code> * * @return The project. */ public java.lang.String getProject() { java.lang.Object ref = project_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); project_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Project ID for this request. * </pre> * * <code> * string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"]; * </code> * * @return The bytes for project. */ public com.google.protobuf.ByteString getProjectBytes() { java.lang.Object ref = project_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); project_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Project ID for this request. * </pre> * * <code> * string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"]; * </code> * * @param value The project to set. * @return This builder for chaining. */ public Builder setProject(java.lang.String value) { if (value == null) { throw new NullPointerException(); } project_ = value; onChanged(); return this; } /** * * * <pre> * Project ID for this request. * </pre> * * <code> * string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"]; * </code> * * @return This builder for chaining. */ public Builder clearProject() { project_ = getDefaultInstance().getProject(); onChanged(); return this; } /** * * * <pre> * Project ID for this request. * </pre> * * <code> * string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"]; * </code> * * @param value The bytes for project to set. * @return This builder for chaining. */ public Builder setProjectBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); project_ = value; onChanged(); return this; } private java.lang.Object requestId_ = ""; /** * * * <pre> * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). * </pre> * * <code>optional string request_id = 37109963;</code> * * @return Whether the requestId field is set. */ public boolean hasRequestId() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). * </pre> * * <code>optional string request_id = 37109963;</code> * * @return The requestId. */ public java.lang.String getRequestId() { java.lang.Object ref = requestId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). * </pre> * * <code>optional string request_id = 37109963;</code> * * @return The bytes for requestId. */ public com.google.protobuf.ByteString getRequestIdBytes() { java.lang.Object ref = requestId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); requestId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). * </pre> * * <code>optional string request_id = 37109963;</code> * * @param value The requestId to set. * @return This builder for chaining. */ public Builder setRequestId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; requestId_ = value; onChanged(); return this; } /** * * * <pre> * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). * </pre> * * <code>optional string request_id = 37109963;</code> * * @return This builder for chaining. */ public Builder clearRequestId() { bitField0_ = (bitField0_ & ~0x00000001); requestId_ = getDefaultInstance().getRequestId(); onChanged(); return this; } /** * * * <pre> * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). * </pre> * * <code>optional string request_id = 37109963;</code> * * @param value The bytes for requestId to set. * @return This builder for chaining. */ public Builder setRequestIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); bitField0_ |= 0x00000001; requestId_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.UpdateBackendBucketRequest) } // @@protoc_insertion_point(class_scope:google.cloud.compute.v1.UpdateBackendBucketRequest) private static final com.google.cloud.compute.v1.UpdateBackendBucketRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.compute.v1.UpdateBackendBucketRequest(); } public static com.google.cloud.compute.v1.UpdateBackendBucketRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateBackendBucketRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateBackendBucketRequest>() { @java.lang.Override public UpdateBackendBucketRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new UpdateBackendBucketRequest(input, extensionRegistry); } }; public static com.google.protobuf.Parser<UpdateBackendBucketRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateBackendBucketRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.compute.v1.UpdateBackendBucketRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
3e08b6d88a9a4f58cd38844de939b4ead17cc891
34,640
java
Java
eidas-client-webapp/src/test/java/ee/ria/eidas/client/webapp/EidasClientApplicationTest.java
e-gov/eIDAS-Client
46f34ea99ee63e82b1de2eb85732698cd0f9bf7a
[ "MIT" ]
5
2018-11-14T16:06:50.000Z
2021-05-18T12:09:50.000Z
eidas-client-webapp/src/test/java/ee/ria/eidas/client/webapp/EidasClientApplicationTest.java
e-gov/eIDAS-Client
46f34ea99ee63e82b1de2eb85732698cd0f9bf7a
[ "MIT" ]
6
2018-01-25T10:25:59.000Z
2022-03-08T21:12:46.000Z
eidas-client-webapp/src/test/java/ee/ria/eidas/client/webapp/EidasClientApplicationTest.java
e-gov/eIDAS-Client
46f34ea99ee63e82b1de2eb85732698cd0f9bf7a
[ "MIT" ]
9
2018-06-21T11:53:14.000Z
2021-05-06T10:04:50.000Z
50.643275
696
0.667841
3,682
package ee.ria.eidas.client.webapp; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.WireMock; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import com.sun.org.apache.xerces.internal.dom.DOMInputImpl; import ee.ria.eidas.client.AuthInitiationService; import ee.ria.eidas.client.AuthResponseService; import ee.ria.eidas.client.authnrequest.AssuranceLevel; import ee.ria.eidas.client.authnrequest.EidasAttribute; import ee.ria.eidas.client.config.EidasClientProperties; import ee.ria.eidas.client.fixtures.ResponseBuilder; import ee.ria.eidas.client.metadata.IDPMetadataResolver; import ee.ria.eidas.client.metadata.SPMetadataGenerator; import ee.ria.eidas.client.session.RequestSessionService; import ee.ria.eidas.client.session.UnencodedRequestSession; import ee.ria.eidas.client.util.OpenSAMLUtils; import ee.ria.eidas.client.utils.XmlUtils; import ee.ria.eidas.client.webapp.status.CredentialsHealthIndicator; import io.restassured.RestAssured; import io.restassured.config.XmlConfig; import io.restassured.http.Method; import io.restassured.response.ResponseBodyExtractionOptions; import io.restassured.response.ValidatableResponse; import lombok.extern.slf4j.Slf4j; import org.joda.time.DateTime; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mockito; import org.opensaml.saml.saml2.core.AttributeStatement; import org.opensaml.saml.saml2.core.Response; import org.opensaml.saml.saml2.core.impl.AttributeStatementBuilder; import org.opensaml.saml.saml2.metadata.EntityDescriptor; import org.opensaml.security.credential.Credential; import org.opensaml.security.x509.BasicX509Credential; import org.opensaml.xmlsec.signature.support.SignatureValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.context.ApplicationEventPublisher; import org.w3c.dom.ls.LSInput; import org.w3c.dom.ls.LSResourceResolver; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static io.restassured.RestAssured.given; import static io.restassured.internal.matcher.xml.XmlXsdMatcher.matchesXsdInClasspath; import static java.util.Arrays.asList; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.not; import static org.hamcrest.core.IsEqual.equalTo; @Slf4j public abstract class EidasClientApplicationTest { @Autowired EidasClientProperties eidasClientProperties; @SpyBean EidasClientProperties.HsmProperties hsmProperties; @SpyBean CredentialsHealthIndicator credentialsHealthIndicator; @SpyBean @Qualifier("metadataSigningCredential") BasicX509Credential metadataSigningCredential; @SpyBean @Qualifier("authnReqSigningCredential") BasicX509Credential authnReqSigningCredential; @SpyBean @Qualifier("responseAssertionDecryptionCredential") BasicX509Credential responseAssertionDecryptionCredential; @Autowired SPMetadataGenerator spMetadataGenerator; @Autowired AuthResponseService authResponseService; @Autowired RequestSessionService requestSessionService; @Autowired IDPMetadataResolver idpMetadataResolver; @Autowired Credential eidasNodeSigningCredential; @Autowired ApplicationEventPublisher applicationEventPublisher; private final static WireMockServer wireMockServer = new WireMockServer(WireMockConfiguration.wireMockConfig().port(7771)); @LocalServerPort int port; @BeforeClass public static void initExternalDependencies() throws InterruptedException { wireMockServer.start(); wireMockServer.stubFor(WireMock.get(urlEqualTo("/EidasNode/ConnectorResponderMetadata")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/xml") .withBody(XmlUtils.readFileBody("samples/response/idp-metadata-ok.xml")) )); for(int i = 0 ; i <= 5 && !wireMockServer.isRunning(); i++) { log.info("Mock eIDAS-Node service not up. Waiting..."); Thread.sleep(1000); } } @AfterClass public static void teardown() throws Exception { wireMockServer.stop(); } @Test public void returnUrl_shouldSucceed_whenValidSAMLResponseWithNaturalPersonMinimalAttributeSet() { ResponseBuilder responseBuilder = new ResponseBuilder(eidasNodeSigningCredential, responseAssertionDecryptionCredential); saveNewRequestSession(ResponseBuilder.DEFAULT_IN_RESPONSE_TO, new DateTime(), AssuranceLevel.LOW, AuthInitiationService.DEFAULT_REQUESTED_ATTRIBUTE_SET); given() .port(port) .contentType("application/x-www-form-urlencoded") .formParam("RelayState", "some-state") .formParam("SAMLResponse", Base64.getEncoder().encodeToString(OpenSAMLUtils.getXmlString(responseBuilder .buildResponse("http://localhost:7771/EidasNode/ConnectorResponderMetadata")).getBytes(StandardCharsets.UTF_8))) .when() .post("/returnUrl") .then() .statusCode(200) .body("levelOfAssurance", equalTo("http://eidas.europa.eu/LoA/low")) .body("attributes.PersonIdentifier", equalTo("CA/CA/12345")) .body("attributes.FamilyName", equalTo("Ωνάσης")) .body("attributes.FirstName", equalTo("Αλέξανδρος")) .body("attributesTransliterated.FamilyName", equalTo("Onassis")) .body("attributesTransliterated.FirstName", equalTo("Alexander")); } @Before public void removeDefaultRequestIdFromSessionStore() { requestSessionService.getAndRemoveRequestSession(ResponseBuilder.DEFAULT_IN_RESPONSE_TO); } @Test public void metadataMatchesSchema() throws Exception { given() .port(port).config(RestAssured.config().xmlConfig(XmlConfig.xmlConfig().disableLoadingOfExternalDtd())) .when() .get("/metadata") .then() .statusCode(200) // schema/saml-schema-metadata-2.0.xsd is located in opensaml-saml-api-3.4.5.jar .body(matchesXsdInClasspath("schema/saml-schema-metadata-2.0.xsd").using(new ClasspathResourceResolver())); } @Test public void metadataIsSignedWithKeyConfiguredInKeystore() throws Exception { ResponseBodyExtractionOptions body = given() .port(port) .when() .get("/metadata") .then() .statusCode(200) .extract().body(); EntityDescriptor signableObj = XmlUtils.unmarshallElement(body.asString()); SignatureValidator.validate(signableObj.getSignature(), metadataSigningCredential); } @Test public void httpPostBinding_shouldPass_whenAllAllowedParamsPresent() { given() .port(port) .queryParam("Country", "EE") .queryParam("LoA", "LOW") .queryParam("RelayState", "test") .queryParam("Attributes", "BirthName PlaceOfBirth CurrentAddress Gender LegalPersonIdentifier LegalName LegalAddress VATRegistration TaxReference LEI EORI SEED SIC") .when() .get("/login") .then() .statusCode(200) .body("html.body.form.@action", equalTo("http://localhost:8080/EidasNode/ServiceProvider")) .body("html.body.form.div.input[0].@value", equalTo("test")) .body("html.body.form.div.input[1].@value", not(empty())) .body("html.body.form.div.input[2].@value", equalTo("EE")); } @Test public void httpPostBinding_shouldFail_whenAttributesContainsSingleValidAttribute() { given() .port(port) .queryParam("Country", "EE") .queryParam("LoA", "LOW") .queryParam("RelayState", "test") .queryParam("Attributes", "LegalPersonIdentifier") .when() .get("/login") .then() .statusCode(200) .body("html.body.form.@action", equalTo("http://localhost:8080/EidasNode/ServiceProvider")) .body("html.body.form.div.input[0].@value", equalTo("test")) .body("html.body.form.div.input[1].@value", not(empty())) .body("html.body.form.div.input[2].@value", equalTo("EE")); } @Test public void httpPostBinding_shouldFail_whenAttributesContainsInvalidAttribute() { given() .port(port) .queryParam("Country", "EE") .queryParam("LoA", "LOW") .queryParam("RelayState", "test") .queryParam("Attributes", "LegalPersonIdentifier XXXX LegalName") .when() .get("/login") .then() .statusCode(400) .body("error", equalTo("Bad Request")) .body("message", equalTo("Found one or more invalid Attributes value(s). Valid values are: " + Arrays.stream(EidasAttribute.values()).map(EidasAttribute::getFriendlyName).collect(Collectors.toList()))); } @Test public void httpPostBinding_shouldFail_whenAttributesContainsNotAllowedAttribute() { given() .port(port) .queryParam("Country", "EE") .queryParam("LoA", "LOW") .queryParam("RelayState", "test") .queryParam("Attributes", "LegalPersonIdentifier LegalName D-2012-17-EUIdentifier") .when() .get("/login") .then() .statusCode(400) .body("error", equalTo("Bad Request")) .body("message", equalTo("Attributes value 'D-2012-17-EUIdentifier' is not allowed. Allowed values are: " + eidasClientProperties.getAllowedEidasAttributes().stream().map(EidasAttribute::getFriendlyName).collect(Collectors.toList()))); } @Test public void httpPostBinding_shouldFail_whenLoAContainsInvalidValue() { given() .port(port) .queryParam("Country", "EE") .queryParam("LoA", "ABCdef") .when() .get("/login") .then() .statusCode(400) .body("error", equalTo("Bad Request")) .body("message", equalTo("Invalid value for parameter LoA")); } @Test public void httpPostBinding_shouldPass_whenOnlyCountryParamPresent() { given() .port(port) .queryParam("Country", "EE") .when() .get("/login") .then() .statusCode(200) .body("html.body.form.@action", equalTo("http://localhost:8080/EidasNode/ServiceProvider")) .body("html.body.form.div.input[0].@value", not(empty())) .body("html.body.form.div.input[1].@value", equalTo("EE")); } @Test public void httpPostBinding_shouldFail_whenCountryRequestParamInvalid() { given() .port(port) .queryParam("Country", "NEVERLAND") .queryParam("RelayState", "test") .when() .get("/login") .then() .statusCode(400) .body("error", equalTo("Bad Request")) .body("message", equalTo("Invalid country! Valid countries:[EE, CA]")); } @Test public void httpPostBinding_shouldFail_whenRelayStateRequestParamInvalid() { given() .port(port) .queryParam("Country", "EE") .queryParam("RelayState", "ä") .when() .get("/login") .then() .statusCode(400) .body("error", equalTo("Bad Request")) .body("message", equalTo("Invalid RelayState! Must match the following regexp: ^[a-zA-Z0-9-_]{0,80}$")); } @Test public void httpPostBinding_shouldFail_whenMissingMandatoryParameter() { given() .port(port) .when() .get("/login") .then() .statusCode(400) .body("error", equalTo("Bad Request")) .body("message", equalTo("Required request parameter 'Country' for method parameter type String is not present")); } @Test public void returnUrl_shouldSucceed_whenValidSAMLResponseWithAllAttributesPresent() { ResponseBuilder responseBuilder = new ResponseBuilder(eidasNodeSigningCredential, responseAssertionDecryptionCredential); saveNewRequestSession(ResponseBuilder.DEFAULT_IN_RESPONSE_TO, new DateTime(), AssuranceLevel.LOW, AuthInitiationService.DEFAULT_REQUESTED_ATTRIBUTE_SET); AttributeStatement attributeStatement = new AttributeStatementBuilder().buildObject(); attributeStatement.getAttributes().add(responseBuilder.buildAttribute("FirstName", "http://eidas.europa.eu/attributes/naturalperson/CurrentGivenName", "urn:oasis:names:tc:SAML:2.0:attrname-format:uri", "eidas-natural:CurrentGivenNameType", "Alexander", "Αλέξανδρος")); attributeStatement.getAttributes().add(responseBuilder.buildAttribute("FamilyName", "http://eidas.europa.eu/attributes/naturalperson/CurrentFamilyName", "urn:oasis:names:tc:SAML:2.0:attrname-format:uri", "eidas-natural:CurrentFamilyNameType", "Onassis", "Ωνάσης")); attributeStatement.getAttributes().add(responseBuilder.buildAttribute("PersonIdentifier", "http://eidas.europa.eu/attributes/naturalperson/PersonIdentifier", "urn:oasis:names:tc:SAML:2.0:attrname-format:uri", "eidas-natural:PersonIdentifierType", "CA/CA/12345")); attributeStatement.getAttributes().add(responseBuilder.buildAttribute("DateOfBirth", "http://eidas.europa.eu/attributes/naturalperson/DateOfBirth", "urn:oasis:names:tc:SAML:2.0:attrname-format:uri", "eidas-natural:DateOfBirthType", "1965-01-01")); attributeStatement.getAttributes().add(responseBuilder.buildAttribute("UnknownMsSpecificAttribute", "http://eidas.europa.eu/attributes/ms/specific/Unknown", "urn:oasis:names:tc:SAML:2.0:attrname-format:uri", "eidas-natural:Custom", "Unspecified")); Response response = responseBuilder.buildResponse("http://localhost:7771/EidasNode/ConnectorResponderMetadata", Collections.singletonMap(ResponseBuilder.InputType.ATTRIBUTE_STATEMENT, Optional.of(attributeStatement))); given() .port(port) .contentType("application/x-www-form-urlencoded") .formParam("RelayState", "some-state") .formParam("SAMLResponse", Base64.getEncoder().encodeToString(OpenSAMLUtils.getXmlString(response).getBytes(StandardCharsets.UTF_8))) .when() .post("/returnUrl") .then() .statusCode(200) .body("levelOfAssurance", equalTo("http://eidas.europa.eu/LoA/low")) .body("attributes.PersonIdentifier", equalTo("CA/CA/12345")) .body("attributes.FamilyName", equalTo("Ωνάσης")) .body("attributes.FirstName", equalTo("Αλέξανδρος")) .body("attributes.FirstName", equalTo("Αλέξανδρος")) .body("attributes.UnknownMsSpecificAttribute", equalTo("Unspecified")) .body("attributesTransliterated.FamilyName", equalTo("Onassis")) .body("attributesTransliterated.FirstName", equalTo("Alexander")); } @Test public void returnUrl_shouldFail_whenAuthenticationFails() { ResponseBuilder responseBuilder = new ResponseBuilder(eidasNodeSigningCredential, responseAssertionDecryptionCredential); Response response = responseBuilder.buildResponse("http://localhost:7771/EidasNode/ConnectorResponderMetadata", Collections.singletonMap(ResponseBuilder.InputType.STATUS, Optional.of(responseBuilder.buildAuthnFailedStatus()))); given() .port(port) .contentType("application/x-www-form-urlencoded") .formParam("SAMLResponse", Base64.getEncoder().encodeToString(OpenSAMLUtils.getXmlString(response).getBytes(StandardCharsets.UTF_8))) .when() .post("/returnUrl") .then() .statusCode(401) .body("error", equalTo("Unauthorized")) .body("message", equalTo("Authentication failed.")); } @Test public void returnUrl_shouldFail_whenInvalidSchema() { given() .port(port) .contentType("application/x-www-form-urlencoded") .formParam("SAMLResponse", Base64.getEncoder().encodeToString("<saml2p:Response xmlns:saml2p=\"urn:oasis:names:tc:SAML:2.0:protocol\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\" xmlns:eidas=\"http://eidas.europa.eu/attributes/naturalperson\" xmlns:saml2=\"urn:oasis:names:tc:SAML:2.0:assertion\" Consent=\"urn:oasis:names:tc:SAML:2.0:consent:obtained\" Destination=\"https://eidastest.eesti.ee/SP/ReturnPage\" ID=\"_3mEzdFJfrtUjn2m2AiVlzcPWQMzUbKbSeBy361IbOJ5bgQsy.luTRPBp5amP1KG\" InResponseTo=\"_dfe8paUm3yG_u4-fdnCtUoM.mQjQnD874VyioAEB71q8waJkIQLBjOP5HdfGLwP\" IssueInstant=\"2018-03-22T12:03:26.306Z\" Version=\"2.0\"></saml2p:Response>".getBytes(StandardCharsets.UTF_8))) .when() .post("/returnUrl") .then() .statusCode(400) .body("error", equalTo("Bad Request")) .body("message", equalTo("Invalid SAMLResponse. Error handling message: Message is not schema-valid.")); } @Test public void returnUrl_shouldFail_whenNoUserConsentGiven() { ResponseBuilder responseBuilder = new ResponseBuilder(eidasNodeSigningCredential, responseAssertionDecryptionCredential); Response response = responseBuilder.buildResponse("http://localhost:8080/EidasNode/ConnectorResponderMetadata", Collections.singletonMap(ResponseBuilder.InputType.STATUS, Optional.of(responseBuilder.buildRequesterRequestDeniedStatus()))); given() .port(port) .contentType("application/x-www-form-urlencoded") .formParam("SAMLResponse", Base64.getEncoder().encodeToString(OpenSAMLUtils.getXmlString(response).getBytes(StandardCharsets.UTF_8))) .when() .post("/returnUrl") .then() .statusCode(401) .body("error", equalTo("Unauthorized")) .body("message", equalTo("No user consent received. User denied access.")); } @Test public void returnUrl_shouldFail_whenInternalError() { ResponseBuilder responseBuilder = new ResponseBuilder(eidasNodeSigningCredential, responseAssertionDecryptionCredential); saveNewRequestSession(ResponseBuilder.DEFAULT_IN_RESPONSE_TO, new DateTime(), AssuranceLevel.LOW, AuthInitiationService.DEFAULT_REQUESTED_ATTRIBUTE_SET); Mockito.when(responseAssertionDecryptionCredential.getPrivateKey()).thenThrow(new RuntimeException("Ooops! An internal error occurred!")); given() .port(port) .contentType("application/x-www-form-urlencoded") .formParam("relayState", "some-state") .formParam("SAMLResponse", Base64.getEncoder().encodeToString(OpenSAMLUtils.getXmlString(responseBuilder.buildResponse("http://localhost:7771/EidasNode/ConnectorResponderMetadata")).getBytes(StandardCharsets.UTF_8))) .when() .post("/returnUrl") .then() .statusCode(500) .body("error", equalTo("Internal Server Error")) .body("message", equalTo("Something went wrong internally. Please consult server logs for further details.")); } @Test public void returnUrl_shouldFail_whenSAMLResponseParamMissing() { ResponseBuilder responseBuilder = new ResponseBuilder(eidasNodeSigningCredential, responseAssertionDecryptionCredential); saveNewRequestSession(ResponseBuilder.DEFAULT_IN_RESPONSE_TO, new DateTime(), AssuranceLevel.LOW, AuthInitiationService.DEFAULT_REQUESTED_ATTRIBUTE_SET); given() .port(port) .contentType("application/x-www-form-urlencoded") .formParam("relayState", "some-state") .formParam("notSAMLResponse", Base64.getEncoder().encodeToString(OpenSAMLUtils.getXmlString(responseBuilder.buildResponse("http://localhost:7771/EidasNode/ConnectorResponderMetadata")).getBytes(StandardCharsets.UTF_8))) .when() .post("/returnUrl") .then() .statusCode(400) .body("error", equalTo("Bad Request")) .body("message", equalTo("Required request parameter 'SAMLResponse' for method parameter type String is not present")); } @Test public void returnUrl_shouldFail_whenSAMLResponseParamEmpty() { saveNewRequestSession(ResponseBuilder.DEFAULT_IN_RESPONSE_TO, new DateTime(), AssuranceLevel.LOW, AuthInitiationService.DEFAULT_REQUESTED_ATTRIBUTE_SET); given() .port(port) .contentType("application/x-www-form-urlencoded") .formParam("relayState", "some-state") .formParam("SAMLResponse", "") .when() .post("/returnUrl") .then() .statusCode(400) .body("error", equalTo("Bad Request")) .body("message", equalTo("Required request parameter 'SAMLResponse' for method parameter type String is not present")); } @Test public void returnUrl_shouldFail_whenSAMLResponseIsNotSigned() { ResponseBuilder responseBuilder = new ResponseBuilder(eidasNodeSigningCredential, responseAssertionDecryptionCredential); Response response = responseBuilder.buildResponse("http://localhost:7771/EidasNode/ConnectorResponderMetadata"); response.setSignature(null); given() .port(port) .contentType("application/x-www-form-urlencoded") .formParam("SAMLResponse", Base64.getEncoder().encodeToString(OpenSAMLUtils.getXmlString(response).getBytes(StandardCharsets.UTF_8))) .when() .post("/returnUrl") .then() .statusCode(400) .body("error", equalTo("Bad Request")) .body("message", equalTo("Invalid SAMLResponse. Response not signed.")); } @Test public void returnUrl_shouldFail_whenSAMLResponseSignatureDoesNotVerify() { ResponseBuilder responseBuilder = new ResponseBuilder(eidasNodeSigningCredential, responseAssertionDecryptionCredential); Response response = responseBuilder.buildResponse("http://localhost:7771/EidasNode/ConnectorResponderMetadata"); response.setInResponseTo("new-inResponseTo-to-invalidate-signature"); given() .port(port) .contentType("application/x-www-form-urlencoded") .formParam("SAMLResponse", Base64.getEncoder().encodeToString(OpenSAMLUtils.getXmlString(response).getBytes(StandardCharsets.UTF_8))) .when() .post("/returnUrl") .then() .statusCode(400) .body("error", equalTo("Bad Request")) .body("message", equalTo("Invalid SAMLResponse. Invalid response signature.")); } @Test public void returnUrl_shouldFail_whenNoRequestSessionPresent() { ResponseBuilder responseBuilder = new ResponseBuilder(eidasNodeSigningCredential, responseAssertionDecryptionCredential); Response response = responseBuilder.buildResponse("http://localhost:7771/EidasNode/ConnectorResponderMetadata"); given() .port(port) .contentType("application/x-www-form-urlencoded") .formParam("SAMLResponse", Base64.getEncoder().encodeToString(OpenSAMLUtils.getXmlString(response).getBytes(StandardCharsets.UTF_8))) .when() .post("/returnUrl") .then() .statusCode(400) .body("error", equalTo("Bad Request")) .body("message", equalTo("Invalid SAMLResponse. No corresponding SAML request session found for the given response!")); } @Test public void returnUrl_shouldFail_whenRequestSessionHasExpired() { ResponseBuilder responseBuilder = new ResponseBuilder(eidasNodeSigningCredential, responseAssertionDecryptionCredential); DateTime issueInstant = new DateTime().minusSeconds(eidasClientProperties.getResponseMessageLifetime()).minusSeconds(eidasClientProperties.getAcceptedClockSkew()).minusSeconds(1); saveNewRequestSession(responseBuilder.DEFAULT_IN_RESPONSE_TO, issueInstant, AssuranceLevel.LOW, AuthInitiationService.DEFAULT_REQUESTED_ATTRIBUTE_SET); Response response = responseBuilder.buildResponse("http://localhost:7771/EidasNode/ConnectorResponderMetadata"); given() .port(port) .contentType("application/x-www-form-urlencoded") .formParam("SAMLResponse", Base64.getEncoder().encodeToString(OpenSAMLUtils.getXmlString(response).getBytes(StandardCharsets.UTF_8))) .when() .post("/returnUrl") .then() .statusCode(400) .body("error", equalTo("Bad Request")) .body("message", equalTo(String.format("Invalid SAMLResponse. Request session with ID %s has expired!", responseBuilder.DEFAULT_IN_RESPONSE_TO))); } @Test public void returnUrl_shouldFail_whenResponseIssueInstantHasExpired() { ResponseBuilder responseBuilder = new ResponseBuilder(eidasNodeSigningCredential, responseAssertionDecryptionCredential); saveNewRequestSession(ResponseBuilder.DEFAULT_IN_RESPONSE_TO, new DateTime(), AssuranceLevel.LOW, AuthInitiationService.DEFAULT_REQUESTED_ATTRIBUTE_SET); DateTime pastTime = new DateTime().minusSeconds(eidasClientProperties.getResponseMessageLifetime()).minusSeconds(eidasClientProperties.getAcceptedClockSkew()).minusSeconds(1); Response response = responseBuilder.buildResponse("http://localhost:7771/EidasNode/ConnectorResponderMetadata", Collections.singletonMap(ResponseBuilder.InputType.ISSUE_INSTANT, Optional.of(pastTime))); given() .port(port) .contentType("application/x-www-form-urlencoded") .formParam("SAMLResponse", Base64.getEncoder().encodeToString(OpenSAMLUtils.getXmlString(response).getBytes(StandardCharsets.UTF_8))) .when() .post("/returnUrl") .then() .statusCode(400) .body("error", equalTo("Bad Request")) .body("message", equalTo("Invalid SAMLResponse. Error handling message: Message was rejected due to issue instant expiration")); } @Test public void returnUrl_shouldFail_whenResponseIssueInstantIsInTheFuture() { ResponseBuilder responseBuilder = new ResponseBuilder(eidasNodeSigningCredential, responseAssertionDecryptionCredential); saveNewRequestSession(ResponseBuilder.DEFAULT_IN_RESPONSE_TO, new DateTime(), AssuranceLevel.LOW, AuthInitiationService.DEFAULT_REQUESTED_ATTRIBUTE_SET); DateTime futureTime = new DateTime().plusSeconds(1).plusSeconds(eidasClientProperties.getResponseMessageLifetime()).plusSeconds(eidasClientProperties.getAcceptedClockSkew()); Response response = responseBuilder.buildResponse("http://localhost:7771/EidasNode/ConnectorResponderMetadata", Collections.singletonMap(ResponseBuilder.InputType.ISSUE_INSTANT, Optional.of(futureTime))); given() .port(port) .contentType("application/x-www-form-urlencoded") .formParam("SAMLResponse", Base64.getEncoder().encodeToString(OpenSAMLUtils.getXmlString(response).getBytes(StandardCharsets.UTF_8))) .when() .post("/returnUrl") .then() .statusCode(400) .body("error", equalTo("Bad Request")) .body("message", equalTo("Invalid SAMLResponse. Error handling message: Message was rejected because it was issued in the future")); } @Test public void returnUrl_shouldFail_whenResponseInResponseToIsInvalid() { ResponseBuilder responseBuilder = new ResponseBuilder(eidasNodeSigningCredential, responseAssertionDecryptionCredential); saveNewRequestSession(ResponseBuilder.DEFAULT_IN_RESPONSE_TO, new DateTime(), AssuranceLevel.LOW, AuthInitiationService.DEFAULT_REQUESTED_ATTRIBUTE_SET); Response response = responseBuilder.buildResponse("http://localhost:7771/EidasNode/ConnectorResponderMetadata", Collections.singletonMap(ResponseBuilder.InputType.IN_RESPONSE_TO, Optional.of("invalid-inResponseTo"))); given() .port(port) .contentType("application/x-www-form-urlencoded") .formParam("SAMLResponse", Base64.getEncoder().encodeToString(OpenSAMLUtils.getXmlString(response).getBytes(StandardCharsets.UTF_8))) .when() .post("/returnUrl") .then() .statusCode(400) .body("error", equalTo("Bad Request")) .body("message", equalTo("Invalid SAMLResponse. No corresponding SAML request session found for the given response!")); } @Test public void returnUrl_shouldFail_whenAssertionInResponseToIsInvalid() { ResponseBuilder responseBuilder = new ResponseBuilder(eidasNodeSigningCredential, responseAssertionDecryptionCredential); saveNewRequestSession(ResponseBuilder.DEFAULT_IN_RESPONSE_TO, new DateTime(), AssuranceLevel.LOW, AuthInitiationService.DEFAULT_REQUESTED_ATTRIBUTE_SET); Response response = responseBuilder.buildResponse("http://localhost:7771/EidasNode/ConnectorResponderMetadata", Collections.singletonMap(ResponseBuilder.InputType.ASSERTION_IN_RESPONSE_TO, Optional.of("invalid-inResponseTo"))); given() .port(port) .contentType("application/x-www-form-urlencoded") .formParam("SAMLResponse", Base64.getEncoder().encodeToString(OpenSAMLUtils.getXmlString(response).getBytes(StandardCharsets.UTF_8))) .when() .post("/returnUrl") .then() .statusCode(400) .body("error", equalTo("Bad Request")) .body("message", equalTo("Invalid SAMLResponse. No corresponding SAML request session found for the given response assertion!")); } @Test public void url_shouldFailWithHttp405WhenInvalidMethod() { Method[] methods = { Method.OPTIONS, Method.DELETE, Method.PUT, Method.PATCH, Method.HEAD, Method.TRACE}; veriftMethodsNotAllowed("/metadata", methods); veriftMethodsNotAllowed("/returnUrl", methods); veriftMethodsNotAllowed("/login", methods); veriftMethodsNotAllowed("/heartbeat", methods); } private void veriftMethodsNotAllowed(String path, Method... methods) { for (Method method: methods) { ValidatableResponse response = given() .port(port) .when() .request(method, path) .then() .statusCode(405); // No response body expected with TRACE and HEAD if (!asList(Method.TRACE, Method.HEAD).contains(method)) { response.body("error", equalTo("Method Not Allowed")); response.body("message", equalTo("Request method '" + method.name() + "' not supported")); } } } protected void saveNewRequestSession(String requestID, DateTime issueInstant, AssuranceLevel loa, List<EidasAttribute> requestedAttributes) { UnencodedRequestSession requestSession = new UnencodedRequestSession(requestID, issueInstant, loa, requestedAttributes); requestSessionService.saveRequestSession(requestID, requestSession); } public static class ClasspathResourceResolver implements LSResourceResolver { @Override public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) { String resourceName = getResourceName(systemId); InputStream resource = ClassLoader.getSystemResourceAsStream(resourceName); if (resource == null) { throw new RuntimeException("Resource not found or error reading resource: " + resourceName); } return new DOMInputImpl(publicId, systemId, baseURI, resource, null); } private static String getResourceName(String systemId) { if (systemId.equals("http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core-schema.xsd")) { return "schema/xmldsig-core-schema.xsd"; // Located in opensaml-xmlsec-api-3.4.5.jar } else if (systemId.equals("http://www.w3.org/TR/xmlenc-core/xenc-schema.xsd")) { return "schema/xenc-schema.xsd"; // Located in opensaml-xmlsec-api-3.4.5.jar } else if (systemId.equals("http://docs.oasis-open.org/security/saml/v2.0/saml-schema-assertion-2.0.xsd")) { return "schema/saml-schema-assertion-2.0.xsd"; // Located in opensaml-saml-api-3.4.5.jar } else if (systemId.equals("http://www.w3.org/2001/xml.xsd")) { return "schema/xml.xsd"; // Local } else if (systemId.contains("://")) { throw new RuntimeException("External resource must be made available locally: " + systemId); } return systemId; } } }
3e08b80a9fa1ba1778dae1bc32774088b133cdea
11,582
java
Java
java/dagger/internal/codegen/ComponentHjarProcessingStep.java
jeppeman/dagger
d735348d3f6cd191d218d8b6910c63eef91542bc
[ "Apache-2.0" ]
1
2019-02-13T16:35:31.000Z
2019-02-13T16:35:31.000Z
java/dagger/internal/codegen/ComponentHjarProcessingStep.java
gauravk95/dagger
d735348d3f6cd191d218d8b6910c63eef91542bc
[ "Apache-2.0" ]
null
null
null
java/dagger/internal/codegen/ComponentHjarProcessingStep.java
gauravk95/dagger
d735348d3f6cd191d218d8b6910c63eef91542bc
[ "Apache-2.0" ]
null
null
null
41.963768
100
0.741323
3,683
/* * Copyright (C) 2017 The Dagger Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dagger.internal.codegen; import static com.google.auto.common.MoreElements.isAnnotationPresent; import static com.google.common.base.CaseFormat.LOWER_CAMEL; import static com.google.common.base.CaseFormat.UPPER_CAMEL; import static com.google.common.base.Preconditions.checkArgument; import static com.squareup.javapoet.MethodSpec.constructorBuilder; import static dagger.internal.codegen.ComponentGenerator.componentName; import static dagger.internal.codegen.ComponentProcessingStep.getElementsFromAnnotations; import static dagger.internal.codegen.TypeSpecs.addSupertype; import static javax.lang.model.element.Modifier.ABSTRACT; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; import static javax.lang.model.util.ElementFilter.methodsIn; import com.google.auto.common.BasicAnnotationProcessor.ProcessingStep; import com.google.auto.common.MoreElements; import com.google.auto.common.MoreTypes; import com.google.common.collect.ImmutableSet; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import dagger.BindsInstance; import dagger.Component; import dagger.internal.codegen.ComponentDescriptor.Factory; import dagger.internal.codegen.ComponentValidator.ComponentValidationReport; import dagger.producers.ProductionComponent; import java.lang.annotation.Annotation; import java.util.Optional; import java.util.Set; import java.util.stream.Stream; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.inject.Inject; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; /** * A processing step that emits the API of a generated component, without any actual implementation. * * <p>When compiling a header jar (hjar), Bazel needs to run annotation processors that generate * API, like Dagger, to see what code they might output. Full {@link BindingGraph} analysis is * costly and unnecessary from the perspective of the header compiler; it's sole goal is to pass * along a slimmed down version of what will be the jar for a particular compilation, whether or not * that compilation succeeds. If it does not, the compilation pipeline will fail, even if header * compilation succeeded. * * <p>The components emitted by this processing step include all of the API elements exposed by the * normal step. Method bodies are omitted as Turbine ignores them entirely. */ final class ComponentHjarProcessingStep implements ProcessingStep { private final Elements elements; private final SourceVersion sourceVersion; private final Types types; private final Filer filer; private final Messager messager; private final ComponentValidator componentValidator; private final ComponentDescriptor.Factory componentDescriptorFactory; @Inject ComponentHjarProcessingStep( Elements elements, SourceVersion sourceVersion, Types types, Filer filer, Messager messager, ComponentValidator componentValidator, Factory componentDescriptorFactory) { this.elements = elements; this.sourceVersion = sourceVersion; this.types = types; this.filer = filer; this.messager = messager; this.componentValidator = componentValidator; this.componentDescriptorFactory = componentDescriptorFactory; } @Override public Set<Class<? extends Annotation>> annotations() { return ImmutableSet.of(Component.class, ProductionComponent.class); } @Override public ImmutableSet<Element> process( SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation) { ImmutableSet.Builder<Element> rejectedElements = ImmutableSet.builder(); ImmutableSet<Element> componentElements = getElementsFromAnnotations( elementsByAnnotation, Component.class, ProductionComponent.class); for (Element element : componentElements) { TypeElement componentTypeElement = MoreElements.asType(element); try { // TODO(ronshapiro): component validation might not be necessary. We should measure it and // figure out if it's worth seeing if removing it will still work. We could potentially // add a new catch clause for any exception that's not TypeNotPresentException and ignore // the component entirely in that case. ComponentValidationReport validationReport = componentValidator.validate(componentTypeElement, ImmutableSet.of(), ImmutableSet.of()); validationReport.report().printMessagesTo(messager); if (validationReport.report().isClean()) { new EmptyComponentGenerator(filer, elements, sourceVersion) .generate(componentDescriptorFactory.forComponent(componentTypeElement), messager); } } catch (TypeNotPresentException e) { rejectedElements.add(componentTypeElement); } } return rejectedElements.build(); } private final class EmptyComponentGenerator extends SourceFileGenerator<ComponentDescriptor> { EmptyComponentGenerator(Filer filer, Elements elements, SourceVersion sourceVersion) { super(filer, elements, sourceVersion); } @Override ClassName nameGeneratedType(ComponentDescriptor input) { return componentName(input.componentDefinitionType()); } @Override Optional<? extends Element> getElementForErrorReporting(ComponentDescriptor input) { return Optional.of(input.componentDefinitionType()); } @Override Optional<TypeSpec.Builder> write( ClassName generatedTypeName, ComponentDescriptor componentDescriptor) { TypeSpec.Builder generatedComponent = TypeSpec.classBuilder(generatedTypeName) .addModifiers(PUBLIC, FINAL) .addMethod(privateConstructor()); TypeElement componentElement = componentDescriptor.componentDefinitionType(); addSupertype(generatedComponent, componentElement); TypeName builderMethodReturnType; if (componentDescriptor.builderSpec().isPresent()) { builderMethodReturnType = ClassName.get(componentDescriptor.builderSpec().get().builderDefinitionType()); } else { TypeSpec.Builder builder = TypeSpec.classBuilder("Builder") .addModifiers(PUBLIC, STATIC, FINAL) .addMethod(privateConstructor()); ClassName builderClassName = generatedTypeName.nestedClass("Builder"); builderMethodReturnType = builderClassName; componentRequirements(componentDescriptor) .map(requirement -> builderInstanceMethod(requirement.typeElement(), builderClassName)) .forEach(builder::addMethod); builder.addMethod(builderBuildMethod(componentDescriptor)); generatedComponent.addType(builder.build()); } generatedComponent.addMethod(staticBuilderMethod(builderMethodReturnType)); if (componentRequirements(componentDescriptor) .noneMatch(requirement -> requirement.requiresAPassedInstance(elements, types)) && !hasBindsInstanceMethods(componentDescriptor)) { generatedComponent.addMethod(createMethod(componentDescriptor)); } DeclaredType componentType = MoreTypes.asDeclared(componentElement.asType()); // TODO(ronshapiro): unify with ComponentModelBuilder Set<MethodSignature> methodSignatures = Sets.newHashSetWithExpectedSize(componentDescriptor.componentMethods().size()); componentDescriptor .componentMethods() .stream() .filter( method -> { return methodSignatures.add( MethodSignature.forComponentMethod(method, componentType, types)); }) .forEach( method -> generatedComponent.addMethod( emptyComponentMethod(componentElement, method.methodElement()))); return Optional.of(generatedComponent); } } private MethodSpec emptyComponentMethod(TypeElement typeElement, ExecutableElement baseMethod) { return MethodSpec.overriding(baseMethod, MoreTypes.asDeclared(typeElement.asType()), types) .build(); } private MethodSpec privateConstructor() { return constructorBuilder().addModifiers(PRIVATE).build(); } /** * Returns the {@link ComponentRequirement}s for a component that does not have a {@link * ComponentDescriptor#builderSpec()}. */ private Stream<ComponentRequirement> componentRequirements(ComponentDescriptor component) { checkArgument(component.kind().isTopLevel()); return Stream.concat( component.dependencies().stream(), component .transitiveModules() .stream() .filter(module -> !module.moduleElement().getModifiers().contains(ABSTRACT)) .map(module -> ComponentRequirement.forModule(module.moduleElement().asType()))); } private boolean hasBindsInstanceMethods(ComponentDescriptor componentDescriptor) { return componentDescriptor.builderSpec().isPresent() && methodsIn( elements.getAllMembers( componentDescriptor.builderSpec().get().builderDefinitionType())) .stream() .anyMatch(method -> isAnnotationPresent(method, BindsInstance.class)); } private MethodSpec builderInstanceMethod( TypeElement componentRequirement, ClassName builderClass) { String simpleName = UPPER_CAMEL.to(LOWER_CAMEL, componentRequirement.getSimpleName().toString()); return MethodSpec.methodBuilder(simpleName) .addModifiers(PUBLIC) .addParameter(ClassName.get(componentRequirement), simpleName) .returns(builderClass) .build(); } private MethodSpec builderBuildMethod(ComponentDescriptor component) { return MethodSpec.methodBuilder("build") .addModifiers(PUBLIC) .returns(ClassName.get(component.componentDefinitionType())) .build(); } private MethodSpec staticBuilderMethod(TypeName builderMethodReturnType) { return MethodSpec.methodBuilder("builder") .addModifiers(PUBLIC, STATIC) .returns(builderMethodReturnType) .build(); } private MethodSpec createMethod(ComponentDescriptor componentDescriptor) { return MethodSpec.methodBuilder("create") .addModifiers(PUBLIC, STATIC) .returns(ClassName.get(componentDescriptor.componentDefinitionType())) .build(); } }
3e08b81e55eb25318066be22166a66a9f48ad761
612
java
Java
src/app/java/pages/web/herokuapp/DragAndDropPage.java
sksingh329/automationCoders
b3c91a709834f36245d21b7ec9cb7b5803a2ccfa
[ "Apache-2.0" ]
2
2020-05-31T12:17:34.000Z
2020-07-12T00:55:35.000Z
src/app/java/pages/web/herokuapp/DragAndDropPage.java
sksingh329/automationCoders
b3c91a709834f36245d21b7ec9cb7b5803a2ccfa
[ "Apache-2.0" ]
6
2020-06-06T20:31:15.000Z
2022-01-04T16:45:55.000Z
src/app/java/pages/web/herokuapp/DragAndDropPage.java
sksingh329/automationCoders
b3c91a709834f36245d21b7ec9cb7b5803a2ccfa
[ "Apache-2.0" ]
null
null
null
29.142857
94
0.72549
3,684
package pages.web.herokuapp; import core.web.selenium.BaseWebPage; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class DragAndDropPage extends BaseWebPage { private final By divColumnA = By.id("column-a"); private final By divColumnB = By.id("column-b"); private final WebDriver pageDriver; public DragAndDropPage(WebDriver driver){ this.pageDriver = driver; } public void performDragAndDrop(){ dragAndDrop(getWebElement(pageDriver,divColumnA),getWebElement(pageDriver,divColumnB), pageDriver,true,"DragAndDrop"); } }
3e08b85a125d3d83c661d335270fd0330d531e15
2,498
java
Java
src/main/java/net/teamfruit/eewbot/dispatcher/EEWDispatcher.java
BreadIsPan/EEW-BOT-24
04fa3685187a9550b1e0b269ada9eb878277fd25
[ "MIT" ]
null
null
null
src/main/java/net/teamfruit/eewbot/dispatcher/EEWDispatcher.java
BreadIsPan/EEW-BOT-24
04fa3685187a9550b1e0b269ada9eb878277fd25
[ "MIT" ]
null
null
null
src/main/java/net/teamfruit/eewbot/dispatcher/EEWDispatcher.java
BreadIsPan/EEW-BOT-24
04fa3685187a9550b1e0b269ada9eb878277fd25
[ "MIT" ]
null
null
null
35.183099
123
0.709367
3,685
package net.teamfruit.eewbot.dispatcher; import java.io.IOException; import java.io.InputStreamReader; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.lang3.time.FastDateFormat; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import net.teamfruit.eewbot.EEWBot; import net.teamfruit.eewbot.Log; import net.teamfruit.eewbot.event.EEWEvent; import net.teamfruit.eewbot.node.EEW; public class EEWDispatcher implements Runnable { public static final EEWDispatcher INSTANCE = new EEWDispatcher(); public static final String REMOTE = "http://www.kmoni.bosai.go.jp/new/webservice/hypo/eew/"; public static final FastDateFormat FORMAT = FastDateFormat.getInstance("yyyyMMddHHmmss"); private final Map<Long, EEW> prev = new HashMap<>(); private EEWDispatcher() { } @Override public void run() { try { final Date date = new Date(System.currentTimeMillis()+NTPDispatcher.INSTANCE.getOffset()-TimeUnit.SECONDS.toMillis(1)); final String url = REMOTE+FORMAT.format(date)+".json"; final EEW res = get(url); if (res!=null&&res.isEEW()) { final EEW last = this.prev.get(res.getReportId()); if (last==null||last.getReportNum()<res.getReportNum()) { final EEWEvent event = new EEWEvent(EEWBot.instance.getClient(), res, res.isInitial() ? null : last); if (res.isInitial()||res.isFinal()) { final byte[] monitor = MonitorDispatcher.get(); event.setMonitor(monitor); } EEWBot.instance.getClient().getDispatcher().dispatch(event); this.prev.put(res.getReportId(), res); } } else this.prev.clear(); } catch (final Exception e) { Log.logger.error(ExceptionUtils.getStackTrace(e)); } } public static EEW get(final String url) throws IOException { Log.logger.debug("Remote: "+url); final HttpGet get = new HttpGet(url); try (CloseableHttpResponse response = EEWBot.instance.getHttpClient().execute(get)) { if (response.getStatusLine().getStatusCode()==HttpStatus.SC_OK) try (InputStreamReader is = new InputStreamReader(response.getEntity().getContent())) { final EEW res = EEWBot.GSON.fromJson(is, EEW.class); Log.logger.debug(res.toString()); return res; } return null; } } }
3e08b8d8778de73b557c22ac735631f7c244cc41
14,861
java
Java
src/main/java/io/mycat/server/executors/MultiNodeQueryHandler.java
renhua91/Mycat-Server
b64e929cb82feab439060bf7df1dea975026b774
[ "Apache-2.0" ]
1
2016-03-11T06:32:32.000Z
2016-03-11T06:32:32.000Z
src/main/java/io/mycat/server/executors/MultiNodeQueryHandler.java
renhua91/Mycat-Server
b64e929cb82feab439060bf7df1dea975026b774
[ "Apache-2.0" ]
null
null
null
src/main/java/io/mycat/server/executors/MultiNodeQueryHandler.java
renhua91/Mycat-Server
b64e929cb82feab439060bf7df1dea975026b774
[ "Apache-2.0" ]
null
null
null
28.469349
89
0.672027
3,686
/* * Copyright (c) 2013, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software;Designed and Developed mainly by many Chinese * opensource volunteers. you can redistribute it and/or modify it under the * terms of the GNU General Public License version 2 only, as published by the * Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Any questions about this component can be directed to it's project Web address * https://code.google.com/p/opencloudb/. * */ package io.mycat.server.executors; import io.mycat.MycatServer; import io.mycat.backend.BackendConnection; import io.mycat.backend.PhysicalDBNode; import io.mycat.backend.nio.MySQLBackendConnection; import io.mycat.cache.LayerCachePool; import io.mycat.net.BufferArray; import io.mycat.net.NetSystem; import io.mycat.route.RouteResultset; import io.mycat.route.RouteResultsetNode; import io.mycat.server.MySQLFrontConnection; import io.mycat.server.NonBlockingSession; import io.mycat.server.config.node.MycatConfig; import io.mycat.server.packet.FieldPacket; import io.mycat.server.packet.OkPacket; import io.mycat.server.packet.ResultSetHeaderPacket; import io.mycat.server.packet.RowDataPacket; import io.mycat.server.packet.util.LoadDataUtil; import io.mycat.server.parser.ServerParse; import io.mycat.sqlengine.mpp.ColMeta; import io.mycat.sqlengine.mpp.DataMergeService; import io.mycat.sqlengine.mpp.MergeCol; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; import java.util.concurrent.locks.ReentrantLock; /** * @author mycat */ public class MultiNodeQueryHandler extends MultiNodeHandler implements LoadDataResponseHandler { public static final Logger LOGGER = LoggerFactory .getLogger(MultiNodeQueryHandler.class); private final RouteResultset rrs; private final NonBlockingSession session; // private final CommitNodeHandler icHandler; private final DataMergeService dataMergeSvr; private final boolean autocommit; private String priamaryKeyTable = null; private int primaryKeyIndex = -1; private int fieldCount = 0; private final ReentrantLock lock; private long affectedRows; private long insertId; private volatile boolean fieldsReturned; private int okCount; private final boolean isCallProcedure; public MultiNodeQueryHandler(int sqlType, RouteResultset rrs, boolean autocommit, NonBlockingSession session) { super(session); if (rrs.getNodes() == null) { throw new IllegalArgumentException("routeNode is null!"); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("execute mutinode query " + rrs.getStatement()); } this.rrs = rrs; if (ServerParse.SELECT == sqlType && rrs.needMerge()) { dataMergeSvr = new DataMergeService(this, rrs); } else { dataMergeSvr = null; } isCallProcedure = rrs.isCallStatement(); this.autocommit = session.getSource().isAutocommit(); this.session = session; this.lock = new ReentrantLock(); // this.icHandler = new CommitNodeHandler(session); if (dataMergeSvr != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("has data merge logic "); } } } protected void reset(int initCount) { super.reset(initCount); this.okCount = initCount; } public NonBlockingSession getSession() { return session; } public void execute() throws Exception { final ReentrantLock lock = this.lock; lock.lock(); try { this.reset(rrs.getNodes().length); this.fieldsReturned = false; this.affectedRows = 0L; this.insertId = 0L; } finally { lock.unlock(); } MycatConfig conf = MycatServer.getInstance().getConfig(); for (final RouteResultsetNode node : rrs.getNodes()) { final BackendConnection conn = session.getTarget(node); if (session.tryExistsCon(conn, node)) { _execute(conn, node); } else { // create new connection PhysicalDBNode dn = conf.getDataNodes().get(node.getName()); dn.getConnection(dn.getDatabase(), autocommit, node, this, node); } } } private void _execute(BackendConnection conn, RouteResultsetNode node) { if (clearIfSessionClosed(session)) { return; } conn.setResponseHandler(this); try { conn.execute(node, session.getSource(), autocommit); } catch (IOException e) { connectionError(e, conn); } } @Override public void connectionAcquired(final BackendConnection conn) { final RouteResultsetNode node = (RouteResultsetNode) conn .getAttachment(); session.bindConnection(node, conn); _execute(conn, node); } private boolean decrementOkCountBy(int finished) { lock.lock(); try { return --okCount == 0; } finally { lock.unlock(); } } @Override public void okResponse(byte[] data, BackendConnection conn) { boolean executeResponse = conn.syncAndExcute(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("received ok response ,executeResponse:" + executeResponse + " from " + conn); } if (executeResponse) { if (clearIfSessionClosed(session)) { return; } else if (canClose(conn, false)) { return; } MySQLFrontConnection source = session.getSource(); OkPacket ok = new OkPacket(); ok.read(data); lock.lock(); try { // 判断是否是全局表,如果是,执行行数不做累加,以最后一次执行的为准。 if (!rrs.isGlobalTable()) { affectedRows += ok.affectedRows; } else { affectedRows = ok.affectedRows; } if (ok.insertId > 0) { insertId = (insertId == 0) ? ok.insertId : Math.min( insertId, ok.insertId); } } finally { lock.unlock(); } // 对于存储过程,其比较特殊,查询结果返回EndRow报文以后,还会再返回一个OK报文,才算结束 boolean isEndPacket = isCallProcedure ? decrementOkCountBy(1) : decrementCountBy(1); if (isEndPacket) { if (this.autocommit) {// clear all connections session.releaseConnections(false); } if (this.isFail() || session.closed()) { tryErrorFinished(true); return; } lock.lock(); try { if (rrs.isLoadData()) { byte lastPackId = source.getLoadDataInfileHandler() .getLastPackId(); ok.packetId = ++lastPackId;// OK_PACKET ok.message = ("Records: " + affectedRows + " Deleted: 0 Skipped: 0 Warnings: 0") .getBytes();// 此处信息只是为了控制台给人看的 source.getLoadDataInfileHandler().clear(); } else { ok.packetId = ++packetId;// OK_PACKET } ok.affectedRows = affectedRows; ok.serverStatus = source.isAutocommit() ? 2 : 1; if (insertId > 0) { ok.insertId = insertId; source.setLastInsertId(insertId); } ok.write(source); } catch (Exception e) { handleDataProcessException(e); } finally { lock.unlock(); } } } } @Override public void rowEofResponse(final byte[] eof, BackendConnection conn) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("on row end reseponse " + conn); } if (errorRepsponsed.get()) { conn.close(this.error); return; } final MySQLFrontConnection source = session.getSource(); if (!isCallProcedure) { if (clearIfSessionClosed(session)) { return; } else if (canClose(conn, false)) { return; } } if (decrementCountBy(1)) { if (!this.isCallProcedure) { if (this.autocommit) {// clear all connections session.releaseConnections(false); } if (this.isFail() || session.closed()) { tryErrorFinished(true); return; } } if (dataMergeSvr != null) { try { dataMergeSvr.outputMergeResult(session, eof); } catch (Exception e) { handleDataProcessException(e); } } else { try { lock.lock(); eof[3] = ++packetId; if (LOGGER.isDebugEnabled()) { LOGGER.debug("last packet id:" + packetId); } source.write(eof); } finally { lock.unlock(); } } } } public void outputMergeResult(final MySQLFrontConnection source, final byte[] eof) { try { lock.lock(); BufferArray bufferArray = NetSystem.getInstance().getBufferPool() .allocateArray(); final DataMergeService dataMergeService = this.dataMergeSvr; final RouteResultset rrs = dataMergeService.getRrs(); // 处理limit语句 int start = rrs.getLimitStart(); int end = start + rrs.getLimitSize(); /* * modify by [email protected]#2015/11/2 优化为通过索引获取,避免无效循环 * Collection<RowDataPacket> results = dataMergeSvr.getResults(eof); * Iterator<RowDataPacket> itor = results.iterator(); if * (LOGGER.isDebugEnabled()) { * LOGGER.debug("output merge result ,total data " + results.size() * + " start :" + start + " end :" + end + " package id start:" + * packetId); } int i = 0; while (itor.hasNext()) { RowDataPacket * row = itor.next(); if (i < start) { i++; continue; } else if (i * == end) { break; } i++; row.packetId = ++packetId; buffer = * row.write(buffer, source, true); } */ // 对于不需要排序的语句,返回的数据只有rrs.getLimitSize() List<RowDataPacket> results = dataMergeSvr.getResults(eof); if (rrs.getOrderByCols() == null) { end = results.size(); start = 0; } for (int i = start; i < end; i++) { RowDataPacket row = results.get(i); row.packetId = ++packetId; row.write(bufferArray); } eof[3] = ++packetId; bufferArray.write(eof); source.write(bufferArray); if (LOGGER.isDebugEnabled()) { LOGGER.debug("last packet id:" + packetId); } } catch (Exception e) { handleDataProcessException(e); } finally { lock.unlock(); dataMergeSvr.clear(); } } @Override public void fieldEofResponse(byte[] header, List<byte[]> fields, byte[] eof, BackendConnection conn) { MySQLFrontConnection source = null; if (fieldsReturned) { return; } lock.lock(); try { if (fieldsReturned) { return; } fieldsReturned = true; boolean needMerg = (dataMergeSvr != null) && dataMergeSvr.getRrs().needMerge(); Set<String> shouldRemoveAvgField = new HashSet<>(); Set<String> shouldRenameAvgField = new HashSet<>(); if (needMerg) { Map<String, Integer> mergeColsMap = dataMergeSvr.getRrs() .getMergeCols(); if (mergeColsMap != null) { for (Map.Entry<String, Integer> entry : mergeColsMap .entrySet()) { String key = entry.getKey(); int mergeType = entry.getValue(); if (MergeCol.MERGE_AVG == mergeType && mergeColsMap.containsKey(key + "SUM")) { shouldRemoveAvgField.add((key + "COUNT") .toUpperCase()); shouldRenameAvgField.add((key + "SUM") .toUpperCase()); } } } } source = session.getSource(); BufferArray bufferArray = NetSystem.getInstance().getBufferPool() .allocateArray(); fieldCount = fields.size(); if (shouldRemoveAvgField.size() > 0) { ResultSetHeaderPacket packet = new ResultSetHeaderPacket(); packet.packetId = ++packetId; packet.fieldCount = fieldCount - shouldRemoveAvgField.size(); packet.write(bufferArray); } else { header[3] = ++packetId; bufferArray.write(header); } String primaryKey = null; if (rrs.hasPrimaryKeyToCache()) { String[] items = rrs.getPrimaryKeyItems(); priamaryKeyTable = items[0]; primaryKey = items[1]; } Map<String, ColMeta> columToIndx = new HashMap<String, ColMeta>( fieldCount); for (int i = 0, len = fieldCount; i < len; ++i) { boolean shouldSkip = false; byte[] field = fields.get(i); if (needMerg) { FieldPacket fieldPkg = new FieldPacket(); fieldPkg.read(field); String fieldName = new String(fieldPkg.name).toUpperCase(); if (columToIndx != null && !columToIndx.containsKey(fieldName)) { if (shouldRemoveAvgField.contains(fieldName)) { shouldSkip = true; } if (shouldRenameAvgField.contains(fieldName)) { String newFieldName = fieldName.substring(0, fieldName.length() - 3); fieldPkg.name = newFieldName.getBytes(); fieldPkg.packetId = ++packetId; shouldSkip = true; fieldPkg.write(bufferArray); } columToIndx.put(fieldName, new ColMeta(i, fieldPkg.type)); } } else if (primaryKey != null && primaryKeyIndex == -1) { // find primary key index FieldPacket fieldPkg = new FieldPacket(); fieldPkg.read(field); String fieldName = new String(fieldPkg.name); if (primaryKey.equalsIgnoreCase(fieldName)) { primaryKeyIndex = i; fieldCount = fields.size(); } } if (!shouldSkip) { field[3] = ++packetId; bufferArray.write(field); } } eof[3] = ++packetId; bufferArray.write(eof); source.write(bufferArray); if (dataMergeSvr != null) { dataMergeSvr.onRowMetaData(columToIndx, fieldCount); } } catch (Exception e) { handleDataProcessException(e); } finally { lock.unlock(); } } public void handleDataProcessException(Exception e) { if (!errorRepsponsed.get()) { this.error = e.toString(); LOGGER.warn("caught exception ", e); setFail(e.toString()); this.tryErrorFinished(true); } } @Override public void rowResponse(final byte[] row, final BackendConnection conn) { if (errorRepsponsed.get()) { conn.close(error); return; } lock.lock(); try { if (dataMergeSvr != null) { final String dnName = ((RouteResultsetNode) conn .getAttachment()).getName(); dataMergeSvr.onNewRecord(dnName, row); } else { if (primaryKeyIndex != -1) {// cache // primaryKey-> // dataNode RowDataPacket rowDataPkg = new RowDataPacket(fieldCount); rowDataPkg.read(row); String primaryKey = new String( rowDataPkg.fieldValues.get(primaryKeyIndex)); LayerCachePool pool = MycatServer.getInstance() .getRouterservice().getTableId2DataNodeCache(); String dataNode = ((RouteResultsetNode) conn .getAttachment()).getName(); pool.putIfAbsent(priamaryKeyTable, primaryKey, dataNode); } row[3] = ++packetId; session.getSource().write(row); } } catch (Exception e) { handleDataProcessException(e); } finally { lock.unlock(); } } @Override public void clearResources() { if (dataMergeSvr != null) { dataMergeSvr.clear(); } } @Override public void requestDataResponse(byte[] data, BackendConnection conn) { LoadDataUtil.requestFileDataResponse(data, (MySQLBackendConnection) conn); } }
3e08b8e737138d28f73c8edf78af69fb76431fdc
5,074
java
Java
bb-email/src/test/java/com/cognifide/qa/bb/email/EmailTest.java
cogbobcat/bobcat
b38faa94af322dbd08f28455a4e1de45f015694b
[ "Apache-2.0" ]
102
2016-08-08T16:40:18.000Z
2020-12-10T15:22:20.000Z
bb-email/src/test/java/com/cognifide/qa/bb/email/EmailTest.java
cogbobcat/bobcat
b38faa94af322dbd08f28455a4e1de45f015694b
[ "Apache-2.0" ]
302
2016-08-04T07:54:47.000Z
2021-01-22T17:34:56.000Z
bb-email/src/test/java/com/cognifide/qa/bb/email/EmailTest.java
cogbobcat/bobcat
b38faa94af322dbd08f28455a4e1de45f015694b
[ "Apache-2.0" ]
48
2016-08-08T10:19:30.000Z
2020-10-06T07:36:31.000Z
25.497487
92
0.717777
3,687
/*- * #%L * Bobcat * %% * Copyright (C) 2016 Cognifide 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. * #L% */ package com.cognifide.qa.bb.email; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import com.cognifide.qa.bb.email.helpers.EmailDataGenerator; import com.cognifide.qa.bb.module.PropertiesLoaderModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; @RunWith(Parameterized.class) public class EmailTest { private final String propertiesFileName; @Inject private EmailClient client; @Inject private EmailSender sender; @Inject private EmailDataGenerator dataGenerator; @Inject private MailServer mailServer; public EmailTest(String propertiesFileName) { this.propertiesFileName = propertiesFileName; } @Parameters public static Collection<Object[]> parameters() { return Arrays.asList(new Object[][]{ {"email.imap.properties"}, {"email.imaps.properties"}, {"email.pop3s.properties"}, }); } @Before public void setUpClass() { Injector injector = Guice.createInjector(new PropertiesLoaderModule(propertiesFileName), new EmailModule()); injector.injectMembers(this); mailServer.start(); } @After public void tearDown() { mailServer.stop(); } @Test public void canReceiveLatestEmails() { int emailsNumber = 5; List<EmailData> sentEmails = dataGenerator.generateEmailData(emailsNumber); sentEmails.forEach(sender::sendEmail); client.connect(); List<EmailData> receivedEmails = client.getLatest(emailsNumber); client.removeLastEmails(emailsNumber); client.close(); Assert.assertEquals("email data objects should be equal", sentEmails, receivedEmails); } @Test public void canReceiveMailBySubject() { String subject = "test"; EmailData sentEmail = dataGenerator.generateEmailData(subject); sender.sendEmail(sentEmail); int emailsNumber = 5; List<EmailData> sentEmails = dataGenerator.generateEmailData(emailsNumber); sentEmails.forEach(sender::sendEmail); client.connect(); List<EmailData> receivedEmail = client.getLatest(subject); client.close(); Assert.assertTrue(receivedEmail.contains(sentEmail)); boolean topicMatches = receivedEmail.stream() .map(EmailData::getSubject) .allMatch(subject::equals); Assert.assertTrue(topicMatches); } @Test public void canRemoveAllMailsWithSubject() { String subject = "test"; EmailData subjectMail = dataGenerator.generateEmailData(subject); sender.sendEmail(subjectMail); int emailsNumber = 5; List<EmailData> sentEmails = dataGenerator.generateEmailData(emailsNumber); sentEmails.forEach(sender::sendEmail); client.connect(); client.removeAllEmails(subject); //reconnect to apply delete of messages client.close(); client.connect(); List<EmailData> latest = client.getLatest(emailsNumber + 1); client.close(); Assert.assertFalse(latest.contains(subjectMail)); Assert.assertTrue(latest.containsAll(sentEmails)); } @Test public void canRemoveLastEmails() { int emailsNumber = 5; int emailsToDelete = 2; List<EmailData> sentEmails = dataGenerator.generateEmailData(emailsNumber); sentEmails.forEach(sender::sendEmail); client.connect(); client.removeLastEmails(emailsToDelete); //reconnect to apply delete of messages client.close(); client.connect(); List<EmailData> latest = client.getLatest(emailsNumber); client.close(); List<EmailData> limitedList = sentEmails.stream() .limit(emailsNumber - (long) emailsToDelete) .collect(Collectors.toList()); Assert.assertEquals(latest, limitedList); } @Test public void canRemoveAllEmails() { int emailsNumber = 5; List<EmailData> sentEmails = dataGenerator.generateEmailData(emailsNumber); sentEmails.forEach(sender::sendEmail); client.connect(); client.removeAllEmails(); //reconnect to apply delete of messages client.close(); client.connect(); List<EmailData> latest = client.getLatest(emailsNumber); client.close(); Assert.assertTrue(latest.isEmpty()); } }
3e08b9fa8bb567011aec26c46ebf71f6468dc374
3,020
java
Java
activiti-core/activiti-engine/src/test/java/org/activiti/engine/impl/runtime/ProcessInstanceBuilderImplTest.java
kesa-Wu/Activiti
e724423de92d09d855a9fe2ccef5788558a59481
[ "Apache-2.0" ]
1
2020-05-05T09:33:08.000Z
2020-05-05T09:33:08.000Z
activiti-core/activiti-engine/src/test/java/org/activiti/engine/impl/runtime/ProcessInstanceBuilderImplTest.java
kesa-Wu/Activiti
e724423de92d09d855a9fe2ccef5788558a59481
[ "Apache-2.0" ]
null
null
null
activiti-core/activiti-engine/src/test/java/org/activiti/engine/impl/runtime/ProcessInstanceBuilderImplTest.java
kesa-Wu/Activiti
e724423de92d09d855a9fe2ccef5788558a59481
[ "Apache-2.0" ]
null
null
null
32.12766
105
0.74106
3,688
/* * Copyright 2020 Alfresco, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.engine.impl.runtime; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.MockitoAnnotations.initMocks; import org.activiti.engine.impl.RuntimeServiceImpl; import org.activiti.engine.runtime.ProcessInstance; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; public class ProcessInstanceBuilderImplTest { @InjectMocks private ProcessInstanceBuilderImpl processInstanceBuilder; @Mock private RuntimeServiceImpl runtimeService; @Before public void setUp() throws Exception { initMocks(this); } @Test public void hasProcessDefinitionIdOrKey_shouldReturnTrue_WhenProcessDefinitionIdIsSet() { //given processInstanceBuilder.processDefinitionId("procDefId"); //when boolean hasProcessDefinitionIdOrKey = processInstanceBuilder.hasProcessDefinitionIdOrKey(); //then assertThat(hasProcessDefinitionIdOrKey).isTrue(); } @Test public void hasProcessDefinitionIdOrKey_shouldReturnTrue_WhenProcessDefinitionKeyIsSet() { //given processInstanceBuilder.processDefinitionKey("procDefKey"); //when boolean hasProcessDefinitionIdOrKey = processInstanceBuilder.hasProcessDefinitionIdOrKey(); //then assertThat(hasProcessDefinitionIdOrKey).isTrue(); } @Test public void hasProcessDefinitionIdOrKey_shouldReturnFalse_WhenNoneOfProcessDefinitionIdOrKeyIsSet() { //given processInstanceBuilder.processDefinitionId(null); processInstanceBuilder.processDefinitionKey(null); //when boolean hasProcessDefinitionIdOrKey = processInstanceBuilder.hasProcessDefinitionIdOrKey(); //then assertThat(hasProcessDefinitionIdOrKey).isFalse(); } @Test public void create_shouldDelegateCreationToRuntimeService() { //given ProcessInstance processInstance = mock( ProcessInstance.class); given(runtimeService.createProcessInstance(processInstanceBuilder)).willReturn(processInstance); //when ProcessInstance createdProcess = processInstanceBuilder.create(); //then assertThat(createdProcess).isEqualTo(processInstance); } }
3e08b9fe56313e2bba97f86a675ecf11a7dae342
20,835
java
Java
android/termux-shared/src/main/java/com/termux/shared/termux/TermuxUtils.java
simbadMarino/dCloud
cebf4a7a0f7aaa11bf39e73ed2552183193f0690
[ "Apache-2.0" ]
11
2021-08-13T07:24:09.000Z
2022-03-05T00:45:46.000Z
android/termux-shared/src/main/java/com/termux/shared/termux/TermuxUtils.java
simbadMarino/dCloud
cebf4a7a0f7aaa11bf39e73ed2552183193f0690
[ "Apache-2.0" ]
6
2021-08-18T02:42:37.000Z
2022-03-30T20:45:01.000Z
android/termux-shared/src/main/java/com/termux/shared/termux/TermuxUtils.java
simbadMarino/dCloud
cebf4a7a0f7aaa11bf39e73ed2552183193f0690
[ "Apache-2.0" ]
1
2021-08-13T09:25:03.000Z
2021-08-13T09:25:03.000Z
49.255319
217
0.710151
3,689
package com.termux.shared.termux; import android.annotation.SuppressLint; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ResolveInfo; import android.os.Build; import androidx.annotation.NonNull; import com.google.common.base.Joiner; import com.termux.shared.R; import com.termux.shared.logger.Logger; import com.termux.shared.markdown.MarkdownUtils; import com.termux.shared.models.ExecutionCommand; import com.termux.shared.packages.PackageUtils; import com.termux.shared.shell.TermuxTask; import org.apache.commons.io.IOUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TermuxUtils { private static final String LOG_TAG = "TermuxUtils"; /** * Get the {@link Context} for {@link TermuxConstants#TERMUX_PACKAGE_NAME} package. * * @param context The {@link Context} to use to get the {@link Context} of the package. * @return Returns the {@link Context}. This will {@code null} if an exception is raised. */ public static Context getTermuxPackageContext(@NonNull Context context) { return PackageUtils.getContextForPackage(context, TermuxConstants.TERMUX_PACKAGE_NAME); } /** * Get the {@link Context} for {@link TermuxConstants#TERMUX_API_PACKAGE_NAME} package. * * @param context The {@link Context} to use to get the {@link Context} of the package. * @return Returns the {@link Context}. This will {@code null} if an exception is raised. */ public static Context getTermuxAPIPackageContext(@NonNull Context context) { return PackageUtils.getContextForPackage(context, TermuxConstants.TERMUX_API_PACKAGE_NAME); } /** * Get the {@link Context} for {@link TermuxConstants#TERMUX_BOOT_PACKAGE_NAME} package. * * @param context The {@link Context} to use to get the {@link Context} of the package. * @return Returns the {@link Context}. This will {@code null} if an exception is raised. */ public static Context getTermuxBootPackageContext(@NonNull Context context) { return PackageUtils.getContextForPackage(context, TermuxConstants.TERMUX_BOOT_PACKAGE_NAME); } /** * Get the {@link Context} for {@link TermuxConstants#TERMUX_FLOAT_PACKAGE_NAME} package. * * @param context The {@link Context} to use to get the {@link Context} of the package. * @return Returns the {@link Context}. This will {@code null} if an exception is raised. */ public static Context getTermuxFloatPackageContext(@NonNull Context context) { return PackageUtils.getContextForPackage(context, TermuxConstants.TERMUX_FLOAT_PACKAGE_NAME); } /** * Get the {@link Context} for {@link TermuxConstants#TERMUX_STYLING_PACKAGE_NAME} package. * * @param context The {@link Context} to use to get the {@link Context} of the package. * @return Returns the {@link Context}. This will {@code null} if an exception is raised. */ public static Context getTermuxStylingPackageContext(@NonNull Context context) { return PackageUtils.getContextForPackage(context, TermuxConstants.TERMUX_STYLING_PACKAGE_NAME); } /** * Get the {@link Context} for {@link TermuxConstants#TERMUX_TASKER_PACKAGE_NAME} package. * * @param context The {@link Context} to use to get the {@link Context} of the package. * @return Returns the {@link Context}. This will {@code null} if an exception is raised. */ public static Context getTermuxTaskerPackageContext(@NonNull Context context) { return PackageUtils.getContextForPackage(context, TermuxConstants.TERMUX_TASKER_PACKAGE_NAME); } /** * Get the {@link Context} for {@link TermuxConstants#TERMUX_WIDGET_PACKAGE_NAME} package. * * @param context The {@link Context} to use to get the {@link Context} of the package. * @return Returns the {@link Context}. This will {@code null} if an exception is raised. */ public static Context getTermuxWidgetPackageContext(@NonNull Context context) { return PackageUtils.getContextForPackage(context, TermuxConstants.TERMUX_WIDGET_PACKAGE_NAME); } /** * Send the {@link TermuxConstants#BROADCAST_TERMUX_OPENED} broadcast to notify apps that Termux * app has been opened. * * @param context The Context to send the broadcast. */ public static void sendTermuxOpenedBroadcast(@NonNull Context context) { if (context == null) return; Intent broadcast = new Intent(TermuxConstants.BROADCAST_TERMUX_OPENED); List<ResolveInfo> matches = context.getPackageManager().queryBroadcastReceivers(broadcast, 0); // send broadcast to registered Termux receivers // this technique is needed to work around broadcast changes that Oreo introduced for (ResolveInfo info : matches) { Intent explicitBroadcast = new Intent(broadcast); ComponentName cname = new ComponentName(info.activityInfo.applicationInfo.packageName, info.activityInfo.name); explicitBroadcast.setComponent(cname); context.sendBroadcast(explicitBroadcast); } } /** * Get a markdown {@link String} for the app info. If the {@code context} passed is different * from the {@link TermuxConstants#TERMUX_PACKAGE_NAME} package context, then this function * must have been called by a different package like a plugin, so we return info for both packages * if {@code returnTermuxPackageInfoToo} is {@code true}. * * @param currentPackageContext The context of current package. * @param returnTermuxPackageInfoToo If set to {@code true}, then will return info of the * {@link TermuxConstants#TERMUX_PACKAGE_NAME} package as well if its different from current package. * @return Returns the markdown {@link String}. */ public static String getAppInfoMarkdownString(@NonNull final Context currentPackageContext, final boolean returnTermuxPackageInfoToo) { if (currentPackageContext == null) return "null"; StringBuilder markdownString = new StringBuilder(); Context termuxPackageContext = getTermuxPackageContext(currentPackageContext); String termuxPackageName = null; String termuxAppName = null; if (termuxPackageContext != null) { termuxPackageName = PackageUtils.getPackageNameForPackage(termuxPackageContext); termuxAppName = PackageUtils.getAppNameForPackage(termuxPackageContext); } String currentPackageName = PackageUtils.getPackageNameForPackage(currentPackageContext); String currentAppName = PackageUtils.getAppNameForPackage(currentPackageContext); boolean isTermuxPackage = (termuxPackageName != null && termuxPackageName.equals(currentPackageName)); if (returnTermuxPackageInfoToo && !isTermuxPackage) markdownString.append("## ").append(currentAppName).append(" App Info (Current)\n"); else markdownString.append("## ").append(currentAppName).append(" App Info\n"); markdownString.append(getAppInfoMarkdownStringInner(currentPackageContext)); if (returnTermuxPackageInfoToo && !isTermuxPackage) { markdownString.append("\n\n## ").append(termuxAppName).append(" App Info\n"); markdownString.append(getAppInfoMarkdownStringInner(termuxPackageContext)); } markdownString.append("\n##\n"); return markdownString.toString(); } /** * Get a markdown {@link String} for the app info for the package associated with the {@code context}. * * @param context The context for operations for the package. * @return Returns the markdown {@link String}. */ public static String getAppInfoMarkdownStringInner(@NonNull final Context context) { StringBuilder markdownString = new StringBuilder(); appendPropertyToMarkdown(markdownString,"APP_NAME", PackageUtils.getAppNameForPackage(context)); appendPropertyToMarkdown(markdownString,"PACKAGE_NAME", PackageUtils.getPackageNameForPackage(context)); appendPropertyToMarkdown(markdownString,"VERSION_NAME", PackageUtils.getVersionNameForPackage(context)); appendPropertyToMarkdown(markdownString,"VERSION_CODE", PackageUtils.getVersionCodeForPackage(context)); appendPropertyToMarkdown(markdownString,"TARGET_SDK", PackageUtils.getTargetSDKForPackage(context)); appendPropertyToMarkdown(markdownString,"IS_DEBUG_BUILD", PackageUtils.isAppForPackageADebugBuild(context)); return markdownString.toString(); } /** * Get a markdown {@link String} for the device info. * * @param context The context for operations. * @return Returns the markdown {@link String}. */ public static String getDeviceInfoMarkdownString(@NonNull final Context context) { if (context == null) return "null"; // Some properties cannot be read with {@link System#getProperty(String)} but can be read // directly by running getprop command Properties systemProperties = getSystemProperties(); StringBuilder markdownString = new StringBuilder(); markdownString.append("## Device Info"); markdownString.append("\n\n### Software\n"); appendPropertyToMarkdown(markdownString,"OS_VERSION", getSystemPropertyWithAndroidAPI("os.version")); appendPropertyToMarkdown(markdownString, "SDK_INT", Build.VERSION.SDK_INT); // If its a release version if ("REL".equals(Build.VERSION.CODENAME)) appendPropertyToMarkdown(markdownString, "RELEASE", Build.VERSION.RELEASE); else appendPropertyToMarkdown(markdownString, "CODENAME", Build.VERSION.CODENAME); appendPropertyToMarkdown(markdownString, "ID", Build.ID); appendPropertyToMarkdown(markdownString, "DISPLAY", Build.DISPLAY); appendPropertyToMarkdown(markdownString, "INCREMENTAL", Build.VERSION.INCREMENTAL); appendPropertyToMarkdownIfSet(markdownString, "SECURITY_PATCH", systemProperties.getProperty("ro.build.version.security_patch")); appendPropertyToMarkdownIfSet(markdownString, "IS_DEBUGGABLE", systemProperties.getProperty("ro.debuggable")); appendPropertyToMarkdownIfSet(markdownString, "IS_EMULATOR", systemProperties.getProperty("ro.boot.qemu")); appendPropertyToMarkdownIfSet(markdownString, "IS_TREBLE_ENABLED", systemProperties.getProperty("ro.treble.enabled")); appendPropertyToMarkdown(markdownString, "TYPE", Build.TYPE); appendPropertyToMarkdown(markdownString, "TAGS", Build.TAGS); markdownString.append("\n\n### Hardware\n"); appendPropertyToMarkdown(markdownString, "MANUFACTURER", Build.MANUFACTURER); appendPropertyToMarkdown(markdownString, "BRAND", Build.BRAND); appendPropertyToMarkdown(markdownString, "MODEL", Build.MODEL); appendPropertyToMarkdown(markdownString, "PRODUCT", Build.PRODUCT); appendPropertyToMarkdown(markdownString, "BOARD", Build.BOARD); appendPropertyToMarkdown(markdownString, "HARDWARE", Build.HARDWARE); appendPropertyToMarkdown(markdownString, "DEVICE", Build.DEVICE); appendPropertyToMarkdown(markdownString, "SUPPORTED_ABIS", Joiner.on(", ").skipNulls().join(Build.SUPPORTED_ABIS)); markdownString.append("\n##\n"); return markdownString.toString(); } /** * Get a markdown {@link String} for reporting an issue. * * @param context The context for operations. * @return Returns the markdown {@link String}. */ public static String getReportIssueMarkdownString(@NonNull final Context context) { if (context == null) return "null"; StringBuilder markdownString = new StringBuilder(); markdownString.append("## Where To Report An Issue"); markdownString.append("\n\n").append(context.getString(R.string.msg_report_issue)).append("\n"); markdownString.append("\n\n### Email\n"); markdownString.append("\n").append(MarkdownUtils.getLinkMarkdownString(TermuxConstants.TERMUX_SUPPORT_EMAIL_URL, TermuxConstants.TERMUX_SUPPORT_EMAIL_MAILTO_URL)).append(" "); markdownString.append("\n\n### Reddit\n"); markdownString.append("\n").append(MarkdownUtils.getLinkMarkdownString(TermuxConstants.TERMUX_REDDIT_SUBREDDIT, TermuxConstants.TERMUX_REDDIT_SUBREDDIT_URL)).append(" "); markdownString.append("\n\n### Github Issues for Termux apps\n"); markdownString.append("\n").append(MarkdownUtils.getLinkMarkdownString(TermuxConstants.TERMUX_APP_NAME, TermuxConstants.TERMUX_GITHUB_ISSUES_REPO_URL)).append(" "); markdownString.append("\n").append(MarkdownUtils.getLinkMarkdownString(TermuxConstants.TERMUX_API_APP_NAME, TermuxConstants.TERMUX_API_GITHUB_ISSUES_REPO_URL)).append(" "); markdownString.append("\n").append(MarkdownUtils.getLinkMarkdownString(TermuxConstants.TERMUX_BOOT_APP_NAME, TermuxConstants.TERMUX_BOOT_GITHUB_ISSUES_REPO_URL)).append(" "); markdownString.append("\n").append(MarkdownUtils.getLinkMarkdownString(TermuxConstants.TERMUX_FLOAT_APP_NAME, TermuxConstants.TERMUX_FLOAT_GITHUB_ISSUES_REPO_URL)).append(" "); markdownString.append("\n").append(MarkdownUtils.getLinkMarkdownString(TermuxConstants.TERMUX_STYLING_APP_NAME, TermuxConstants.TERMUX_STYLING_GITHUB_ISSUES_REPO_URL)).append(" "); markdownString.append("\n").append(MarkdownUtils.getLinkMarkdownString(TermuxConstants.TERMUX_TASKER_APP_NAME, TermuxConstants.TERMUX_TASKER_GITHUB_ISSUES_REPO_URL)).append(" "); markdownString.append("\n").append(MarkdownUtils.getLinkMarkdownString(TermuxConstants.TERMUX_WIDGET_APP_NAME, TermuxConstants.TERMUX_WIDGET_GITHUB_ISSUES_REPO_URL)).append(" "); markdownString.append("\n\n### Github Issues for Termux packages\n"); markdownString.append("\n").append(MarkdownUtils.getLinkMarkdownString(TermuxConstants.TERMUX_PACKAGES_GITHUB_REPO_NAME, TermuxConstants.TERMUX_PACKAGES_GITHUB_ISSUES_REPO_URL)).append(" "); markdownString.append("\n").append(MarkdownUtils.getLinkMarkdownString(TermuxConstants.TERMUX_GAME_PACKAGES_GITHUB_REPO_NAME, TermuxConstants.TERMUX_GAME_PACKAGES_GITHUB_ISSUES_REPO_URL)).append(" "); markdownString.append("\n").append(MarkdownUtils.getLinkMarkdownString(TermuxConstants.TERMUX_SCIENCE_PACKAGES_GITHUB_REPO_NAME, TermuxConstants.TERMUX_SCIENCE_PACKAGES_GITHUB_ISSUES_REPO_URL)).append(" "); markdownString.append("\n").append(MarkdownUtils.getLinkMarkdownString(TermuxConstants.TERMUX_ROOT_PACKAGES_GITHUB_REPO_NAME, TermuxConstants.TERMUX_ROOT_PACKAGES_GITHUB_ISSUES_REPO_URL)).append(" "); markdownString.append("\n").append(MarkdownUtils.getLinkMarkdownString(TermuxConstants.TERMUX_UNSTABLE_PACKAGES_GITHUB_REPO_NAME, TermuxConstants.TERMUX_UNSTABLE_PACKAGES_GITHUB_ISSUES_REPO_URL)).append(" "); markdownString.append("\n").append(MarkdownUtils.getLinkMarkdownString(TermuxConstants.TERMUX_X11_PACKAGES_GITHUB_REPO_NAME, TermuxConstants.TERMUX_X11_PACKAGES_GITHUB_ISSUES_REPO_URL)).append(" "); markdownString.append("\n##\n"); return markdownString.toString(); } /** * Get a markdown {@link String} for APT info of the app. * * This will take a few seconds to run due to running {@code apt update} command. * * @param context The context for operations. * @return Returns the markdown {@link String}. */ public static String geAPTInfoMarkdownString(@NonNull final Context context) { String aptInfoScript = null; InputStream inputStream = context.getResources().openRawResource(com.termux.shared.R.raw.apt_info_script); try { aptInfoScript = IOUtils.toString(inputStream, Charset.defaultCharset()); } catch (IOException e) { Logger.logError(LOG_TAG, "Failed to get APT info script: " + e.getMessage()); return null; } IOUtils.closeQuietly(inputStream); if (aptInfoScript == null || aptInfoScript.isEmpty()) { Logger.logError(LOG_TAG, "The APT info script is null or empty"); return null; } aptInfoScript = aptInfoScript.replaceAll(Pattern.quote("@TERMUX_PREFIX@"), TermuxConstants.TERMUX_PREFIX_DIR_PATH); ExecutionCommand executionCommand = new ExecutionCommand(1, TermuxConstants.TERMUX_BIN_PREFIX_DIR_PATH + "/bash", null, aptInfoScript, null, true, false); TermuxTask termuxTask = TermuxTask.execute(context, executionCommand, null, true); if (termuxTask == null || !executionCommand.isSuccessful() || executionCommand.exitCode != 0) { Logger.logError(LOG_TAG, executionCommand.toString()); return null; } if (executionCommand.stderr != null && !executionCommand.stderr.isEmpty()) Logger.logError(LOG_TAG, executionCommand.toString()); StringBuilder markdownString = new StringBuilder(); markdownString.append("## ").append(TermuxConstants.TERMUX_APP_NAME).append(" APT Info\n\n"); markdownString.append(executionCommand.stdout); return markdownString.toString(); } public static Properties getSystemProperties() { Properties systemProperties = new Properties(); // getprop commands returns values in the format `[key]: [value]` // Regex matches string starting with a literal `[`, // followed by one or more characters that do not match a closing square bracket as the key, // followed by a literal `]: [`, // followed by one or more characters as the value, // followed by string ending with literal `]` // multiline values will be ignored Pattern propertiesPattern = Pattern.compile("^\\[([^]]+)]: \\[(.+)]$"); try { Process process = new ProcessBuilder() .command("/system/bin/getprop") .redirectErrorStream(true) .start(); InputStream inputStream = process.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line, key, value; while ((line = bufferedReader.readLine()) != null) { Matcher matcher = propertiesPattern.matcher(line); if (matcher.matches()) { key = matcher.group(1); value = matcher.group(2); if (key != null && value != null && !key.isEmpty() && !value.isEmpty()) systemProperties.put(key, value); } } bufferedReader.close(); process.destroy(); } catch (IOException e) { Logger.logStackTraceWithMessage("Failed to get run \"/system/bin/getprop\" to get system properties.", e); } //for (String key : systemProperties.stringPropertyNames()) { // Logger.logVerbose(key + ": " + systemProperties.get(key)); //} return systemProperties; } private static String getSystemPropertyWithAndroidAPI(@NonNull String property) { try { return System.getProperty(property); } catch (Exception e) { Logger.logVerbose("Failed to get system property \"" + property + "\":" + e.getMessage()); return null; } } private static void appendPropertyToMarkdownIfSet(StringBuilder markdownString, String label, Object value) { if (value == null) return; if (value instanceof String && (((String) value).isEmpty()) || "REL".equals(value)) return; markdownString.append("\n").append(getPropertyMarkdown(label, value)); } private static void appendPropertyToMarkdown(StringBuilder markdownString, String label, Object value) { markdownString.append("\n").append(getPropertyMarkdown(label, value)); } private static String getPropertyMarkdown(String label, Object value) { return MarkdownUtils.getSingleLineMarkdownStringEntry(label, value, "-"); } public static String getCurrentTimeStamp() { @SuppressLint("SimpleDateFormat") final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); df.setTimeZone(TimeZone.getTimeZone("UTC")); return df.format(new Date()); } }
3e08ba0fd128ba74ea339cabd1333a77af587e70
6,837
java
Java
projects/batfish/src/main/java/org/batfish/representation/cumulus/BgpNeighbor.java
batfish/batfish
3a8792fbe249d531ea69d9522bdefe6b396f6229
[ "Apache-2.0" ]
763
2017-02-21T20:35:50.000Z
2022-03-29T09:27:14.000Z
projects/batfish/src/main/java/org/batfish/representation/cumulus/BgpNeighbor.java
batfish/batfish
3a8792fbe249d531ea69d9522bdefe6b396f6229
[ "Apache-2.0" ]
7,675
2017-01-18T08:04:59.000Z
2022-03-31T21:29:36.000Z
projects/batfish/src/main/java/org/batfish/representation/cumulus/BgpNeighbor.java
batfish/batfish
3a8792fbe249d531ea69d9522bdefe6b396f6229
[ "Apache-2.0" ]
194
2017-05-03T14:58:10.000Z
2022-03-30T20:56:44.000Z
28.970339
100
0.690654
3,690
package org.batfish.representation.cumulus; import java.io.Serializable; import java.util.Map; import java.util.Objects; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.batfish.datamodel.BgpPeerConfig; import org.batfish.datamodel.LongSpace; /** Parent for all BGP neighbors. */ public abstract class BgpNeighbor implements Serializable { public static class RemoteAs implements Serializable { @Nullable final Long _asn; @Nonnull final RemoteAsType _type; public static RemoteAs explicit(long asn) { return new RemoteAs(asn, RemoteAsType.EXPLICIT); } public static RemoteAs external() { return new RemoteAs(null, RemoteAsType.EXTERNAL); } public static RemoteAs internal() { return new RemoteAs(null, RemoteAsType.INTERNAL); } @Override public boolean equals(Object o) { if (this == o) { return true; } else if (!(o instanceof RemoteAs)) { return false; } RemoteAs remoteAs = (RemoteAs) o; return Objects.equals(_asn, remoteAs._asn) && _type == remoteAs._type; } @Override public int hashCode() { return Objects.hash(_asn, _type); } /** * Returns the remote AS values for this remote AS configuration with the given local ASN, or * {@link LongSpace#EMPTY} if {@code localAs} is required to compute the AS values but is {@code * null}. */ public @Nonnull LongSpace getRemoteAs(@Nullable Long localAs) { if (_type == RemoteAsType.EXPLICIT) { assert _asn != null; return LongSpace.of(_asn); } else if (localAs == null) { // For either INTERNAL or EXTERNAL, we need to know the local AS to implement this. return LongSpace.EMPTY; } else if (_type == RemoteAsType.EXTERNAL) { // Everything but the local ASN. return BgpPeerConfig.ALL_AS_NUMBERS.difference(LongSpace.of(localAs)); } else { assert _type == RemoteAsType.INTERNAL; return LongSpace.of(localAs); } } /** * Returns {@code true} if this remote AS is known to be different from the given {@code * localAs}, and {@code false} otherwise. * * <p>Returns {@code false} when the result is unknown, aka, when {@code localAs} is {@code * null} and this is an explicitly numbered peer. */ public boolean isKnownEbgp(@Nullable Long localAs) { return _type == RemoteAsType.EXTERNAL || _type == RemoteAsType.EXPLICIT && localAs != null && !localAs.equals(_asn); } /** * Returns {@code true} if this remote AS is known to be the same as the given {@code localAs}, * and {@code false} otherwise. * * <p>Returns {@code false} when the result is unknown, aka, when {@code localAs} is {@code * null} and this is an explicitly numbered peer. */ public boolean isKnownIbgp(@Nullable Long localAs) { return _type == RemoteAsType.INTERNAL || _type == RemoteAsType.EXPLICIT && localAs != null && localAs.equals(_asn); } private RemoteAs(@Nullable Long asn, RemoteAsType type) { _asn = asn; _type = type; } } private final @Nonnull String _name; private @Nullable String _description; private @Nullable String _peerGroup; // Inheritable properties private @Nullable RemoteAs _remoteAs; private @Nullable BgpNeighborIpv4UnicastAddressFamily _ipv4UnicastAddressFamily; private @Nullable BgpNeighborL2vpnEvpnAddressFamily _l2vpnEvpnAddressFamily; private @Nullable Boolean _ebgpMultihop; private @Nullable BgpNeighborSource _bgpNeighborSource; private @Nullable Long _localAs; // Whether this configuration has inherited from its parent. private boolean _inherited = false; public BgpNeighbor(String name) { _name = name; } public @Nonnull String getName() { return _name; } @Nullable public String getDescription() { return _description; } public void setDescription(@Nullable String description) { _description = description; } @Nullable public BgpNeighborIpv4UnicastAddressFamily getIpv4UnicastAddressFamily() { return _ipv4UnicastAddressFamily; } public BgpNeighbor setIpv4UnicastAddressFamily( @Nullable BgpNeighborIpv4UnicastAddressFamily ipv4UnicastAddressFamily) { _ipv4UnicastAddressFamily = ipv4UnicastAddressFamily; return this; } @Nullable public BgpNeighborL2vpnEvpnAddressFamily getL2vpnEvpnAddressFamily() { return _l2vpnEvpnAddressFamily; } public BgpNeighbor setL2vpnEvpnAddressFamily( @Nullable BgpNeighborL2vpnEvpnAddressFamily l2vpnEvpnAddressFamily) { _l2vpnEvpnAddressFamily = l2vpnEvpnAddressFamily; return this; } @Nullable public String getPeerGroup() { return _peerGroup; } public void setPeerGroup(@Nullable String peerGroup) { _peerGroup = peerGroup; } public @Nullable Long getLocalAs() { return _localAs; } public @Nullable RemoteAs getRemoteAs() { return _remoteAs; } public @Nullable Boolean getEbgpMultihop() { return _ebgpMultihop; } public void setEbgpMultihop(@Nullable Boolean ebgpMultihop) { _ebgpMultihop = ebgpMultihop; } public void setLocalAs(@Nullable Long localAs) { _localAs = localAs; } public void setRemoteAs(@Nullable RemoteAs remoteAs) { _remoteAs = remoteAs; } protected void inheritFrom(@Nonnull Map<String, BgpNeighbor> peers) { if (_inherited) { return; } _inherited = true; @Nullable BgpNeighbor other = _peerGroup == null ? null : peers.get(_peerGroup); if (other == null) { return; } // Do not inherit description. // Do not inherit name. // Do not inherit peer group. if (_bgpNeighborSource == null) { _bgpNeighborSource = other.getBgpNeighborSource(); } if (_ebgpMultihop == null) { _ebgpMultihop = other.getEbgpMultihop(); } if (_remoteAs == null) { _remoteAs = other.getRemoteAs(); } if (_ipv4UnicastAddressFamily == null) { _ipv4UnicastAddressFamily = other.getIpv4UnicastAddressFamily(); } else if (other.getIpv4UnicastAddressFamily() != null) { _ipv4UnicastAddressFamily.inheritFrom(other.getIpv4UnicastAddressFamily()); } if (_l2vpnEvpnAddressFamily == null) { _l2vpnEvpnAddressFamily = other.getL2vpnEvpnAddressFamily(); } else if (other.getL2vpnEvpnAddressFamily() != null) { _l2vpnEvpnAddressFamily.inheritFrom(other.getL2vpnEvpnAddressFamily()); } if (_localAs == null) { _localAs = other.getLocalAs(); } } @Nullable public BgpNeighborSource getBgpNeighborSource() { return _bgpNeighborSource; } public void setBgpNeighborSource(@Nullable BgpNeighborSource bgpNeighborSource) { _bgpNeighborSource = bgpNeighborSource; } }
3e08ba32ea68e669c41ea931acf684240b84e3fd
383
java
Java
context-handler/src/main/java/gov/samhsa/c2s/contexthandler/service/xacml/XACMLXPath.java
bhits/context-handler
e092da88f657024abbd6d9aa4da052fc769b2ea6
[ "Apache-2.0" ]
6
2016-11-01T19:39:21.000Z
2019-07-18T00:22:50.000Z
context-handler/src/main/java/gov/samhsa/c2s/contexthandler/service/xacml/XACMLXPath.java
bhits-dev/context-handler
9c3a6b0f785d8ccc83b2cad9dcb41a753309ca30
[ "Apache-2.0" ]
null
null
null
context-handler/src/main/java/gov/samhsa/c2s/contexthandler/service/xacml/XACMLXPath.java
bhits-dev/context-handler
9c3a6b0f785d8ccc83b2cad9dcb41a753309ca30
[ "Apache-2.0" ]
2
2017-09-05T01:26:03.000Z
2020-03-23T03:41:18.000Z
34.818182
113
0.801567
3,691
package gov.samhsa.c2s.contexthandler.service.xacml; public class XACMLXPath { public static final String XPATH_POLICY_SET_ID = "/xacml2:PolicySet/@PolicySetId"; public static final String XPATH_POLICY_ID = "/xacml2:Policy/@PolicyId"; public static final String XPATH_POLICY_SET_POLICY_COMBINING_ALG_ID = "/xacml2:PolicySet/@PolicyCombiningAlgId"; private XACMLXPath() { }; }
3e08bbedff63402b68fda81521b2847a5d310593
1,363
java
Java
src/main/java/datastructureproject/PerformanceTest.java
AnnaKuokkanen/Chess
d521ddf6f7bbf28bf5f4464beff80290335f78fb
[ "MIT" ]
null
null
null
src/main/java/datastructureproject/PerformanceTest.java
AnnaKuokkanen/Chess
d521ddf6f7bbf28bf5f4464beff80290335f78fb
[ "MIT" ]
1
2020-08-26T06:13:39.000Z
2020-08-26T06:13:39.000Z
src/main/java/datastructureproject/PerformanceTest.java
AnnaKuokkanen/Chess
d521ddf6f7bbf28bf5f4464beff80290335f78fb
[ "MIT" ]
null
null
null
29.630435
97
0.471753
3,692
package datastructureproject; import chess.bot.MyBot; import chess.engine.GameState; /** * Performance tests for MyBot. * * Test makes */ public class PerformanceTest { private static MyBot bot; public static void main(String[] args) { int[] depths = new int[] {1, 2, 3, 4, 5}; int moves = 20; long[][] times = new long[depths.length][moves]; for (int i = 0; i < depths.length; i++) { bot = new MyBot(depths[i]); GameState gamestate = new GameState(); for (int j = 0; j < moves; j++) { if (j == 0) { System.out.println("Starting to search with depth " + depths[i]); } long begin = System.nanoTime(); bot.nextMove(gamestate); long finish = System.nanoTime(); System.out.println("Time passed: " + (finish - begin)); times[i][j] = finish - begin; } } for (int i = 0; i < depths.length; i++) { long sum = 0; for (int j = 0; j < times.length; j++) { sum += times[i][j]; } long average = sum / times.length; System.out.println("Average time for depth " + depths[i] + " is " + average + " ns"); } } }
3e08bc4fcb83459b59db09a86f2816d417d8442a
559
java
Java
src/test/java/edu/hipsec/xrdtiffoperations/bytewrappers/base/ByteWrapperTest.java
quantumjockey/xrdfileoperations
56c6457a3132a98476e1f762aeb6041ddbaabbd7
[ "BSD-Source-Code" ]
null
null
null
src/test/java/edu/hipsec/xrdtiffoperations/bytewrappers/base/ByteWrapperTest.java
quantumjockey/xrdfileoperations
56c6457a3132a98476e1f762aeb6041ddbaabbd7
[ "BSD-Source-Code" ]
null
null
null
src/test/java/edu/hipsec/xrdtiffoperations/bytewrappers/base/ByteWrapperTest.java
quantumjockey/xrdfileoperations
56c6457a3132a98476e1f762aeb6041ddbaabbd7
[ "BSD-Source-Code" ]
null
null
null
26.619048
93
0.533095
3,693
package edu.hipsec.xrdtiffoperations.bytewrappers.base; import org.junit.Test; public abstract class ByteWrapperTest<T extends ByteWrapper> { /////////// Fields ////////////////////////////////////////////////////////////////////// protected byte[] bytes; protected T wrapper; /////////// Tests /////////////////////////////////////////////////////////////////////// @Test public abstract void constructor_checkArraySize_expectedByteLengthForType(); @Test public abstract void get_valueOfTypeConverted_returnInput(); }
3e08bc598fe7c7627613e9c981a66c0e00a40566
854
java
Java
ServiceApp/app/src/main/java/teste/app/com/serviceapp/MainActivity.java
brunocbcsilva/AndroidCodigosFontes
ddbfbe5c118657cc694c5ed157d027e235f49cad
[ "MIT" ]
null
null
null
ServiceApp/app/src/main/java/teste/app/com/serviceapp/MainActivity.java
brunocbcsilva/AndroidCodigosFontes
ddbfbe5c118657cc694c5ed157d027e235f49cad
[ "MIT" ]
null
null
null
ServiceApp/app/src/main/java/teste/app/com/serviceapp/MainActivity.java
brunocbcsilva/AndroidCodigosFontes
ddbfbe5c118657cc694c5ed157d027e235f49cad
[ "MIT" ]
null
null
null
26.6875
68
0.704918
3,694
package teste.app.com.serviceapp; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.os.Bundle; import android.app.Activity; import android.util.Log; import android.view.View; public class MainActivity extends Activity { String msg = "Android : "; /**Chamado quando o service é criado. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Log.d(msg, "The onCreate() event"); } public void startService(View view) { startService(new Intent(getBaseContext(), MyService.class)); } // Método para parar o Service public void stopService(View view) { stopService(new Intent(getBaseContext(), MyService.class)); } }
3e08bca62e323ab6da7104e6a3a64188e3c3ea7f
404
java
Java
core/src/main/java/com/shazam/tocker/MappedPorts.java
michal-lyson/tocker
0a2bf77d698783709c4981904f27579004aab646
[ "Apache-2.0" ]
2
2017-06-08T08:39:32.000Z
2017-12-28T16:41:19.000Z
core/src/main/java/com/shazam/tocker/MappedPorts.java
michal-lyson/tocker
0a2bf77d698783709c4981904f27579004aab646
[ "Apache-2.0" ]
3
2016-11-07T14:42:03.000Z
2018-05-14T11:14:02.000Z
core/src/main/java/com/shazam/tocker/MappedPorts.java
michal-lyson/tocker
0a2bf77d698783709c4981904f27579004aab646
[ "Apache-2.0" ]
5
2017-04-04T09:04:27.000Z
2019-07-19T09:15:15.000Z
23.764706
107
0.710396
3,695
package com.shazam.tocker; import lombok.Builder; import java.util.Map; import java.util.Optional; @Builder public class MappedPorts { private final Map<Integer, Integer> portMaps; public int forContainerPort(int port) { return Optional.ofNullable(portMaps.get(port)) .orElseThrow(() -> new IllegalArgumentException(String.format("Port %d is not mapped", port))); } }
3e08bcb42bfd32286fd678ce9a3f4bf2c3b4c1d1
2,148
java
Java
gulimall-product/src/main/java/com/atguigu/gulimall/product/app/SkuInfoController.java
poppintk/gulimall
b9bacc483e746450dbbe4b2dc5c91c3223fc0342
[ "Apache-2.0" ]
null
null
null
gulimall-product/src/main/java/com/atguigu/gulimall/product/app/SkuInfoController.java
poppintk/gulimall
b9bacc483e746450dbbe4b2dc5c91c3223fc0342
[ "Apache-2.0" ]
1
2022-01-26T00:48:36.000Z
2022-02-10T00:32:45.000Z
gulimall-product/src/main/java/com/atguigu/gulimall/product/app/SkuInfoController.java
poppintk/gulimall
b9bacc483e746450dbbe4b2dc5c91c3223fc0342
[ "Apache-2.0" ]
null
null
null
23.659341
69
0.653507
3,696
package com.atguigu.gulimall.product.app; import com.atguigu.common.utils.PageUtils; import com.atguigu.common.utils.R; import com.atguigu.gulimall.product.entity.SkuInfoEntity; import com.atguigu.gulimall.product.service.SkuInfoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Arrays; import java.util.Map; /** * sku信息 * * @author ryan * @email [email protected] * @date 2021-05-12 00:48:47 */ @RestController @RequestMapping("product/skuinfo") public class SkuInfoController { @Autowired private SkuInfoService skuInfoService; @GetMapping("/{skuId}/price") public R getPrice(@PathVariable("skuId") Long skuId) { SkuInfoEntity byId = skuInfoService.getById(skuId); return R.ok().setData(byId.getPrice()); } /** * 列表 */ @RequestMapping("/list") //@RequiresPermissions("product:skuinfo:list") public R list(@RequestParam Map<String, Object> params) { PageUtils page = skuInfoService.queryPageByCondition(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{skuId}") //@RequiresPermissions("product:skuinfo:info") public R info(@PathVariable("skuId") Long skuId) { SkuInfoEntity skuInfo = skuInfoService.getById(skuId); return R.ok().put("skuInfo", skuInfo); } /** * 保存 */ @RequestMapping("/save") //@RequiresPermissions("product:skuinfo:save") public R save(@RequestBody SkuInfoEntity skuInfo) { skuInfoService.save(skuInfo); return R.ok(); } /** * 修改 */ @RequestMapping("/update") //@RequiresPermissions("product:skuinfo:update") public R update(@RequestBody SkuInfoEntity skuInfo) { skuInfoService.updateById(skuInfo); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") //@RequiresPermissions("product:skuinfo:delete") public R delete(@RequestBody Long[] skuIds) { skuInfoService.removeByIds(Arrays.asList(skuIds)); return R.ok(); } }
3e08bd37b0e7703af49b520a5e311b45265d3a60
12,165
java
Java
javaSources/JXLayer/org/jdesktop/jxlayer/plaf/ext/LockableUI.java
Gingerfridge/RasCAL_2019
efe5c97c1ec14ee4bd71c0bcfa58ff17d04406b8
[ "BSD-3-Clause" ]
5
2020-02-24T15:58:15.000Z
2021-05-06T17:49:42.000Z
javaSources/JXLayer/org/jdesktop/jxlayer/plaf/ext/LockableUI.java
Gingerfridge/RasCAL_2019
efe5c97c1ec14ee4bd71c0bcfa58ff17d04406b8
[ "BSD-3-Clause" ]
8
2020-03-04T14:11:29.000Z
2022-01-05T14:25:55.000Z
javaSources/JXLayer/org/jdesktop/jxlayer/plaf/ext/LockableUI.java
Gingerfridge/RasCAL_2019
efe5c97c1ec14ee4bd71c0bcfa58ff17d04406b8
[ "BSD-3-Clause" ]
1
2020-12-08T16:44:51.000Z
2020-12-08T16:44:51.000Z
38.865815
149
0.6097
3,697
/** * Copyright (c) 2006-2008, Alexander Potochkin * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the JXLayer project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jdesktop.jxlayer.plaf.ext; import org.jdesktop.jxlayer.JXLayer; import org.jdesktop.jxlayer.plaf.BufferedLayerUI; import org.jdesktop.jxlayer.plaf.effect.LayerEffect; import javax.swing.*; import java.awt.*; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; /** * An implementation of the {@code BufferedLayerUI} which provides * a lightweight disabling for the content of its {@link JXLayer}. * This allows temporarily blocking a part of the interface * with all it subcomponents, it is also useful when some kind of action * is in progress, e.g. reading data from a database. * <p/> * When {@code true} is passed to the {@link #setLocked(boolean)}, * the {@code JXLayer} of this {@code LockableLayerUI} becomes "locked". * It sets the "wait" mouse cursor and stops reacting * on mouse, keyboard and focus events. * <p/> * If {@code setLocked(boolean)} is called with {@code false} parameter * after that, the {@code JXLayer}, together with all its subcomponents, * gets back to live. * <p/> * Subclasses usually override {@link #paintLayer(Graphics2D,JXLayer)} or * {@link #getLayerEffects(JXLayer)} to implement some visual effects * when {@code JXLayer} is in locked state. * <p/> * Here is an example of using {@code LockableLayerUI}: * <pre> * JComponent myComponent = getMyComponent(); // just any component * <p/> * LockableLayerUI lockableUI = new LockableLayerUI(); * JXLayer&lt;JComponent&gt; layer = new JXLayer&lt;JComponent&gt;(myComponent, lockableUI); * <p/> * // locking the layer, use lockableUI.setLocked(false) to unlock * lockableUI.setLocked(true); * <p/> * // add the layer to a frame or a panel, like any other component * frame.add(layer); * </pre> * The LockableDemo is * <a href="https://jxlayer.dev.java.net/source/browse/jxlayer/trunk/src/demo/org/jdesktop/jxlayer/demo/LockableDemo.java?view=markup">available</a> */ public class LockableUI extends BufferedLayerUI<JComponent> { private boolean isLocked; private Component recentFocusOwner; private Cursor lockedCursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR); private LayerEffect[] lockedEffects = new LayerEffect[0]; private final FocusListener focusListener = new FocusListener() { public void focusGained(FocusEvent e) { // we don't want extra repaintings // when focus comes from another window if (e.getOppositeComponent() != null) { setDirty(true); } } public void focusLost(FocusEvent e) { } }; /** * Creates a new instance of LockableUI, * passed lockedEffects will be used for when this UI in the locked state * * @param lockedEffects effects to be used when this UI is locked * @see #setLocked(boolean) * @see #setLockedEffects(LayerEffect...) */ public LockableUI(LayerEffect... lockedEffects) { setLockedEffects(lockedEffects); } /** * {@inheritDoc} */ @Override public void installUI(JComponent c) { super.installUI(c); // we need to repaint the layer when it receives the focus // otherwise the focused component will have it on the buffer image c.addFocusListener(focusListener); } /** * {@inheritDoc} */ @Override public void uninstallUI(JComponent c) { super.uninstallUI(c); c.removeFocusListener(focusListener); } /** * Returns {@code true} if this {@code LockableLayerUI} * is in locked state and all {@link JXLayer}'s mouse, keyboard and focuse events * are temporarily blocked, otherwise returns {@code false}. * * @return {@code true} if this {@code LockableLayerUI} * is in locked state and all {@code JXLayer}'s mouse, keyboard and focuse events * are temporarily blocked, otherwise returns {@code false} */ public boolean isLocked() { return isLocked; } /** * If {@code isLocked} is {@code true} then all mouse, keyboard and focuse events * from the {@link JXLayer} of this {@code LockableLayerUI} * will be temporarily blocked. * * @param isLocked if {@code true} then all mouse, keyboard and focuse events * from the {@code JXLayer} of this {@code LockableLayerUI} will be temporarily blocked */ public void setLocked(boolean isLocked) { if (isLocked != isLocked()) { if (getLayer() != null) { Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager() .getPermanentFocusOwner(); boolean isFocusInsideLayer = focusOwner != null && SwingUtilities.isDescendingFrom(focusOwner, getLayer()); if (isLocked) { // hide the layer's view component // this is the only way to disable key shortcuts // installed on its subcomponents getLayer().getView().setVisible(false); if (isFocusInsideLayer) { recentFocusOwner = focusOwner; // setDirty() will be called from the layer's focusListener // when focus already left layer's view and hiding it // in the paintLayer() won't mess the focus up getLayer().requestFocusInWindow(); } else { setDirty(true); } // the mouse cursor is set to the glassPane getLayer().getGlassPane().setCursor(getLockedCursor()); } else { // show the view again getLayer().getView().setVisible(true); // restore the focus if it is still in the layer if (isFocusInsideLayer && recentFocusOwner != null) { recentFocusOwner.requestFocusInWindow(); } recentFocusOwner = null; getLayer().getGlassPane().setCursor(null); } } this.isLocked = isLocked; } } // If it is locked, the buffer image will be updated // only if the layer changes its size or setDirty(true) was called @Override protected boolean isIncrementalUpdate(JXLayer<JComponent> l) { return !isLocked(); } @Override protected void paintLayer(Graphics2D g2, JXLayer<JComponent> l) { if (isLocked()) { // Note: this code will be called only if layer changes its size, // or setDirty(true) was called, // otherwise the previously created buffer is used l.getView().setVisible(true); l.paint(g2); l.getView().setVisible(false); } else { // if not locked, paint as usual l.paint(g2); } } // Repaint, if the LookAndFeel was changed @Override public void updateUI(JXLayer<JComponent> l) { if (isLocked()) { setDirty(true); } } /** * Returns the mouse cursor to be used * by this {@code LockableLayerUI} when it locked state. * * @return the mouse cursor to be used * by this {@code LockableLayerUI} when it locked state * @see #getLockedCursor() * @see #setLocked(boolean) */ public Cursor getLockedCursor() { return lockedCursor; } /** * Sets the mouse cursor to be used * by this {@code LockableLayerUI} when it locked state. * * @param lockedCursor the mouse cursor to be used * by this {@code LockableLayerUI} when it locked state */ public void setLockedCursor(Cursor lockedCursor) { this.lockedCursor = lockedCursor; if (isLocked()) { getLayer().getGlassPane().setCursor(lockedCursor); } } /** * Returns the effects to be used when this UI is locked. * * @return the effects to be used when this UI is locked * @see #setLocked(boolean) */ public LayerEffect[] getLockedEffects() { LayerEffect[] result = new LayerEffect[lockedEffects.length]; System.arraycopy(lockedEffects, 0, result, 0, result.length); return result; } /* * This method returns the array of {@code LayerEffect}s * set using {@link #setLayerEffects(LayerEffect...)} * <p/> * If a {@code LockableUI} provides more extensive API * to support different {@code Effect}s depending on its state * or on the state of the passed {@code JXLayer}, * this method should be overridden. * * @see #setLockedEffects (LayerEffect...) * @see #getLockedEffects() */ protected LayerEffect[] getLockedEffects(JXLayer<JComponent> l) { return getLockedEffects(); } /** * Sets the effects to be used when this UI is locked. * * @param lockedEffects the effects to be used when this UI is locked * @see #setLocked(boolean) */ public void setLockedEffects(LayerEffect... lockedEffects) { LayerEffect[] oldEffects = getLockedEffects(); if (lockedEffects == null) { lockedEffects = new LayerEffect[0]; } for (LayerEffect effect : getLockedEffects()) { effect.removeLayerItemListener(this); } this.lockedEffects = new LayerEffect[lockedEffects.length]; System.arraycopy(lockedEffects, 0, this.lockedEffects, 0, lockedEffects.length); for (LayerEffect lockedEffect : lockedEffects) { lockedEffect.addLayerItemListener(this); } if (!isEnabled() || oldEffects.equals(lockedEffects)) { return; } if (isLocked()) { setDirty(true); } } /** * {@inheritDoc} */ @Override protected LayerEffect[] getLayerEffects(JXLayer<JComponent> l) { if (isLocked()) { return getLockedEffects(l); } else { return super.getLayerEffects(l); } } }
3e08bd6634ed3582a975b44f3ba528e87f35a9d3
2,057
java
Java
utils/src/main/java/com/cloud/utils/storage/QCOW2Utils.java
FilippoProjetto/cloudstack
5471802f862dd617f63d12eb56c9aa62759e4309
[ "Apache-2.0" ]
14
2015-01-12T13:46:12.000Z
2021-07-19T19:33:28.000Z
utils/src/main/java/com/cloud/utils/storage/QCOW2Utils.java
HeinleinSupport/cloudstack
f948e96299f65f2c83ee902b0b46ea34a559064b
[ "Apache-2.0" ]
20
2020-12-19T22:32:23.000Z
2022-02-01T01:07:06.000Z
utils/src/main/java/com/cloud/utils/storage/QCOW2Utils.java
Rostov1991/cloudstack
4abe8385e0721793d5dae8f195303d010c8ff8d2
[ "Apache-2.0" ]
8
2015-07-17T12:36:51.000Z
2018-08-09T16:23:40.000Z
34.283333
91
0.711716
3,698
// // 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.cloud.utils.storage; import java.io.IOException; import java.io.InputStream; import com.cloud.utils.NumbersUtil; public final class QCOW2Utils { private static final int VIRTUALSIZE_HEADER_LOCATION = 24; private static final int VIRTUALSIZE_HEADER_LENGTH = 8; /** * Private constructor -> This utility class cannot be instantiated. */ private QCOW2Utils() {} /** * @return the header location of the virtual size field. */ public static int getVirtualSizeHeaderLocation() { return VIRTUALSIZE_HEADER_LOCATION; } /** * @param inputStream The QCOW2 object in stream format. * @return The virtual size of the QCOW2 object. */ public static long getVirtualSize(InputStream inputStream) throws IOException { byte[] bytes = new byte[VIRTUALSIZE_HEADER_LENGTH]; if (inputStream.skip(VIRTUALSIZE_HEADER_LOCATION) != VIRTUALSIZE_HEADER_LOCATION) { throw new IOException("Unable to skip to the virtual size header"); } if (inputStream.read(bytes) != VIRTUALSIZE_HEADER_LENGTH) { throw new IOException("Unable to properly read the size"); } return NumbersUtil.bytesToLong(bytes); } }
3e08be173a473bf86886728b661fe5afdbe2946b
5,590
java
Java
score-http/score-http/src/main/java/org/oagi/score/export/model/BDTSC.java
OAGi/Score
3094555ea14624fe180e921957a418b0bd33147b
[ "MIT" ]
5
2020-02-03T16:02:12.000Z
2021-07-29T18:18:52.000Z
score-http/score-http/src/main/java/org/oagi/score/export/model/BDTSC.java
OAGi/Score
3094555ea14624fe180e921957a418b0bd33147b
[ "MIT" ]
566
2019-12-09T17:06:44.000Z
2022-03-28T14:15:48.000Z
score-http/score-http/src/main/java/org/oagi/score/export/model/BDTSC.java
OAGi/Score
3094555ea14624fe180e921957a418b0bd33147b
[ "MIT" ]
2
2019-12-06T19:33:58.000Z
2020-10-25T07:20:15.000Z
33.878788
130
0.612701
3,699
package org.oagi.score.export.model; import org.oagi.score.provider.ImportedDataProvider; import org.oagi.score.repo.api.impl.jooq.entity.tables.records.*; import java.util.List; import java.util.stream.Collectors; import static org.oagi.score.common.ScoreConstants.OAGIS_VERSION; public class BDTSC implements Component { private DtScRecord dtSc; private ImportedDataProvider importedDataProvider; public BDTSC(DtScRecord dtSc, ImportedDataProvider importedDataProvider) { this.importedDataProvider = importedDataProvider; this.dtSc = dtSc; } public String getName() { String propertyTerm = dtSc.getPropertyTerm(); if ("MIME".equals(propertyTerm) || "URI".equals(propertyTerm)) { propertyTerm = propertyTerm.toLowerCase(); } String representationTerm = dtSc.getRepresentationTerm(); if (propertyTerm.equals(representationTerm) || "Text".equals(representationTerm)) { // exceptional case. 'expressionLanguageText' must be 'expressionLanguage'. representationTerm = ""; } if (OAGIS_VERSION < 10.3D) { // exceptional case. 'preferredIndicator' must be 'preferred'. if ("oagis-id-9bb9add40b5b415c8489b08bd4484907".equals(dtSc.getGuid())) { representationTerm = ""; } } if (propertyTerm.contains(representationTerm)) { String attrName = Character.toLowerCase(propertyTerm.charAt(0)) + propertyTerm.substring(1); return attrName.replaceAll(" ", ""); } else { String attrName = Character.toLowerCase(propertyTerm.charAt(0)) + propertyTerm.substring(1) + representationTerm.replace("Identifier", "ID"); return attrName.replaceAll(" ", ""); } } public String getGuid() { return GUID_PREFIX + dtSc.getGuid(); } public DtScRecord getBdtSc() { return dtSc; } private String typeName; private CdtScAwdPriXpsTypeMapRecord cdtScAwdPriXpsTypeMap; private XbtRecord xbt; private AgencyIdListRecord agencyIdList; private CodeListRecord codeList; public XbtRecord getXbt() { ensureTypeName(); return xbt; } public CdtScAwdPriRecord getCdtScAwdPri() { ensureTypeName(); return importedDataProvider.findCdtScAwdPri( cdtScAwdPriXpsTypeMap.getCdtScAwdPriId() ); } public CdtPriRecord getCdtPri() { CdtScAwdPriRecord cdtScAwdPri = getCdtScAwdPri(); return importedDataProvider.findCdtPri(cdtScAwdPri.getCdtPriId()); } public AgencyIdListRecord getAgencyIdList() { ensureTypeName(); return agencyIdList; } public CodeListRecord getCodeList() { ensureTypeName(); return codeList; } @Override public String getTypeName() { ensureTypeName(); return typeName; } private void ensureTypeName() { if (typeName != null) { return; } List<BdtScPriRestriRecord> bdtScPriRestriList = importedDataProvider.findBdtScPriRestriListByDtScId(dtSc.getDtScId()); List<BdtScPriRestriRecord> codeListBdtScPriRestri = bdtScPriRestriList.stream() .filter(e -> e.getCodeListId() != null) .collect(Collectors.toList()); if (codeListBdtScPriRestri.size() > 1) { throw new IllegalStateException(); } if (codeListBdtScPriRestri.isEmpty()) { List<BdtScPriRestriRecord> agencyIdBdtScPriRestri = bdtScPriRestriList.stream() .filter(e -> e.getAgencyIdListId() != null) .collect(Collectors.toList()); if (agencyIdBdtScPriRestri.size() > 1) { throw new IllegalStateException(); } if (agencyIdBdtScPriRestri.isEmpty()) { List<BdtScPriRestriRecord> defaultBdtScPriRestri = bdtScPriRestriList.stream() .filter(e -> e.getIsDefault() == 1) .collect(Collectors.toList()); if (defaultBdtScPriRestri.isEmpty() || defaultBdtScPriRestri.size() > 1) { throw new IllegalStateException(); } cdtScAwdPriXpsTypeMap = importedDataProvider.findCdtScAwdPriXpsTypeMap(defaultBdtScPriRestri.get(0).getCdtScAwdPriXpsTypeMapId()); xbt = importedDataProvider.findXbt(cdtScAwdPriXpsTypeMap.getXbtId()); typeName = xbt.getBuiltinType(); } else { agencyIdList = importedDataProvider.findAgencyIdList(agencyIdBdtScPriRestri.get(0).getAgencyIdListId()); typeName = agencyIdList.getName() + "ContentType"; } } else { codeList = importedDataProvider.findCodeList(codeListBdtScPriRestri.get(0).getCodeListId()); typeName = codeList.getName() + "ContentType"; } } public int getMinCardinality() { return dtSc.getCardinalityMin(); } public int getMaxCardinality() { return dtSc.getCardinalityMax(); } public boolean hasBasedBDTSC() { return (dtSc.getBasedDtScId() != null); } public String getDefinition() { return dtSc.getDefinition(); } public String getDefinitionSource() { return dtSc.getDefinitionSource(); } }
3e08be8a255f2c5e07449333f8741f309aa25874
14,593
java
Java
runtime/src/test/java/com/flipkart/flux/resource/StateMachineResourceTest.java
shyamakirala/flux
7139a14966b5f9843c0fa17345ebdf8c2758b6a6
[ "Apache-2.0" ]
null
null
null
runtime/src/test/java/com/flipkart/flux/resource/StateMachineResourceTest.java
shyamakirala/flux
7139a14966b5f9843c0fa17345ebdf8c2758b6a6
[ "Apache-2.0" ]
null
null
null
runtime/src/test/java/com/flipkart/flux/resource/StateMachineResourceTest.java
shyamakirala/flux
7139a14966b5f9843c0fa17345ebdf8c2758b6a6
[ "Apache-2.0" ]
null
null
null
61.058577
260
0.748098
3,700
/* * Copyright 2012-2016, the original author or authors. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.flipkart.flux.resource; import com.fasterxml.jackson.databind.ObjectMapper; import com.flipkart.flux.api.StateMachineDefinition; import com.flipkart.flux.client.FluxClientInterceptorModule; import com.flipkart.flux.constant.RuntimeConstants; import com.flipkart.flux.dao.TestWorkflow; import com.flipkart.flux.dao.iface.EventsDAO; import com.flipkart.flux.dao.iface.StateMachinesDAO; import com.flipkart.flux.domain.Event; import com.flipkart.flux.domain.State; import com.flipkart.flux.domain.StateMachine; import com.flipkart.flux.domain.Status; import com.flipkart.flux.guice.module.AkkaModule; import com.flipkart.flux.guice.module.ContainerModule; import com.flipkart.flux.guice.module.HibernateModule; import com.flipkart.flux.impl.boot.TaskModule; import com.flipkart.flux.initializer.OrderedComponentBooter; import com.flipkart.flux.module.DeploymentUnitTestModule; import com.flipkart.flux.module.RuntimeTestModule; import com.flipkart.flux.representation.StateMachinePersistenceService; import com.flipkart.flux.rule.DbClearRule; import com.flipkart.flux.runner.GuiceJunit4Runner; import com.flipkart.flux.runner.Modules; import com.flipkart.flux.util.TestUtils; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import org.apache.commons.io.IOUtils; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import javax.inject.Inject; import javax.ws.rs.core.Response; import static org.assertj.core.api.Assertions.assertThat; @RunWith(GuiceJunit4Runner.class) @Modules({DeploymentUnitTestModule.class,HibernateModule.class,RuntimeTestModule.class,ContainerModule.class,AkkaModule.class,TaskModule.class,FluxClientInterceptorModule.class}) public class StateMachineResourceTest { @Inject @Rule public DbClearRule dbClearRule; @Inject private StateMachinesDAO stateMachinesDAO; @Inject private EventsDAO eventsDAO; @Inject OrderedComponentBooter orderedComponentBooter; @Inject StateMachinePersistenceService stateMachinePersistenceService; public static final String STATE_MACHINE_RESOURCE_URL = "http://localhost:9998" + RuntimeConstants.API_CONTEXT_PATH + RuntimeConstants.STATE_MACHINE_RESOURCE_RELATIVE_PATH; private static final String SLASH = "/"; private ObjectMapper objectMapper; @Before public void setUp() throws Exception { objectMapper = new ObjectMapper(); } @AfterClass public static void afterClass() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } @Test public void testCreateStateMachine() throws Exception { String stateMachineDefinitionJson = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("state_machine_definition.json")); final HttpResponse<String> response = Unirest.post(STATE_MACHINE_RESOURCE_URL).header("Content-Type","application/json").body(stateMachineDefinitionJson).asString(); assertThat(response.getStatus()).isEqualTo(Response.Status.CREATED.getStatusCode()); assertThat(stateMachinesDAO.findByName("test_state_machine")).hasSize(1); Thread.sleep(600); TestUtils.assertStateMachineEquality(stateMachinesDAO.findByName("test_state_machine").iterator().next(), TestUtils.getStandardTestMachine()); } @Test public void testUnsideline() throws Exception { String stateMachineDefinitionJson = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("state_machine_definition.json")); final HttpResponse<String> smCreationResponse = Unirest.post(STATE_MACHINE_RESOURCE_URL).header("Content-Type","application/json").body(stateMachineDefinitionJson).asString(); Event event = eventsDAO.findBySMIdAndName(Long.parseLong(smCreationResponse.getBody()), "event0"); assertThat(event.getStatus()).isEqualTo(Event.EventStatus.pending); // ask the task to fail with retriable error. TestWorkflow.shouldFail = true; try { String eventJson = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("event_data.json")); final HttpResponse<String> eventPostResponse = Unirest.post(STATE_MACHINE_RESOURCE_URL + SLASH + smCreationResponse.getBody() + "/context/events").header("Content-Type", "application/json").body(eventJson).asString(); assertThat(eventPostResponse.getStatus()).isEqualTo(Response.Status.ACCEPTED.getStatusCode()); // give some time to execute Thread.sleep(4000); //status of state should be sidelined Long smId = Long.parseLong(smCreationResponse.getBody()); State state4 = stateMachinesDAO.findById(smId).getStates().stream().filter(e -> e.getName().equals("test_state4")).findFirst().orElse(null); assertThat(state4).isNotNull(); assertThat(state4.getStatus()).isEqualTo(Status.sidelined); TestWorkflow.shouldFail = false; // unsideline final HttpResponse<String> unsidelineResponse = Unirest.put(STATE_MACHINE_RESOURCE_URL + "/" + smId + "/" + state4.getId() + "/unsideline").asString(); assertThat(unsidelineResponse.getStatus()).isEqualTo(Response.Status.ACCEPTED.getStatusCode()); Thread.sleep(500); state4 = stateMachinesDAO.findById(smId).getStates().stream().filter(e -> e.getName().equals("test_state4")).findFirst().orElse(null); assertThat(state4).isNotNull(); assertThat(state4.getStatus()).isEqualTo(Status.completed); } finally { TestWorkflow.shouldFail = false; } } @Test public void testCreateStateMachine_shouldBombDueToDuplicateCorrelationId() throws Exception { String stateMachineDefinitionJson = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("state_machine_definition.json")); final HttpResponse<String> response = Unirest.post(STATE_MACHINE_RESOURCE_URL).header("Content-Type","application/json").body(stateMachineDefinitionJson).asString(); assertThat(response.getStatus()).isEqualTo(Response.Status.CREATED.getStatusCode()); assertThat(stateMachinesDAO.findByName("test_state_machine")).hasSize(1); final HttpResponse<String> secondResponse = Unirest.post(STATE_MACHINE_RESOURCE_URL).header("Content-Type","application/json").body(stateMachineDefinitionJson).asString(); assertThat(secondResponse.getStatus()).isEqualTo(Response.Status.CONFLICT.getStatusCode()); } @Test public void testPostEvent() throws Exception { String stateMachineDefinitionJson = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("state_machine_definition.json")); final HttpResponse<String> smCreationResponse = Unirest.post(STATE_MACHINE_RESOURCE_URL).header("Content-Type","application/json").body(stateMachineDefinitionJson).asString(); Event event = eventsDAO.findBySMIdAndName(Long.parseLong(smCreationResponse.getBody()), "event0"); assertThat(event.getStatus()).isEqualTo(Event.EventStatus.pending); String eventJson = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("event_data.json")); final HttpResponse<String> eventPostResponse = Unirest.post(STATE_MACHINE_RESOURCE_URL+SLASH+smCreationResponse.getBody()+"/context/events").header("Content-Type","application/json").body(eventJson).asString(); assertThat(eventPostResponse.getStatus()).isEqualTo(Response.Status.ACCEPTED.getStatusCode()); // give some time to execute Thread.sleep(500); event = eventsDAO.findBySMIdAndName(Long.parseLong(smCreationResponse.getBody()), "event0"); assertThat(event.getStatus()).isEqualTo(Event.EventStatus.triggered); assertThat(event).isEqualToIgnoringGivenFields(TestUtils.getStandardTestEvent(), "stateMachineInstanceId", "id", "createdAt", "updatedAt"); // event3 was waiting on event1, so event3 should also be triggered event = eventsDAO.findBySMIdAndName(Long.parseLong(smCreationResponse.getBody()), "event3"); assertThat(event.getStatus()).isEqualTo(Event.EventStatus.triggered); boolean anyNotCompleted = stateMachinesDAO.findById(Long.parseLong(smCreationResponse.getBody())).getStates().stream().anyMatch(e -> !e.getStatus().equals(Status.completed)); assertThat(anyNotCompleted).isFalse(); } @Test public void testPostEvent_withCorrelationId() throws Exception { String stateMachineDefinitionJson = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("state_machine_definition.json")); final HttpResponse<String> smCreationResponse = Unirest.post(STATE_MACHINE_RESOURCE_URL).header("Content-Type","application/json").body(stateMachineDefinitionJson).asString(); Event event = eventsDAO.findBySMIdAndName(Long.parseLong(smCreationResponse.getBody()), "event0"); assertThat(event.getStatus()).isEqualTo(Event.EventStatus.pending); String eventJson = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("event_data.json")); final HttpResponse<String> eventPostResponse = Unirest.post(STATE_MACHINE_RESOURCE_URL+SLASH+"magic_number_1"+"/context/events?searchField=correlationId").header("Content-Type","application/json").body(eventJson).asString(); assertThat(eventPostResponse.getStatus()).isEqualTo(Response.Status.ACCEPTED.getStatusCode()); // give some time to execute Thread.sleep(500); event = eventsDAO.findBySMIdAndName(Long.parseLong(smCreationResponse.getBody()), "event0"); assertThat(event.getStatus()).isEqualTo(Event.EventStatus.triggered); assertThat(event).isEqualToIgnoringGivenFields(TestUtils.getStandardTestEvent(), "stateMachineInstanceId", "id", "createdAt", "updatedAt"); // event3 was waiting on event1, so event3 should also be triggered event = eventsDAO.findBySMIdAndName(Long.parseLong(smCreationResponse.getBody()), "event3"); assertThat(event.getStatus()).isEqualTo(Event.EventStatus.triggered); boolean anyNotCompleted = stateMachinesDAO.findById(Long.parseLong(smCreationResponse.getBody())).getStates().stream().anyMatch(e -> !e.getStatus().equals(Status.completed)); assertThat(anyNotCompleted).isFalse(); } @Test public void testPostEvent_againstNonExistingCorrelationId() throws Exception { String stateMachineDefinitionJson = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("state_machine_definition.json")); final HttpResponse<String> smCreationResponse = Unirest.post(STATE_MACHINE_RESOURCE_URL).header("Content-Type","application/json").body(stateMachineDefinitionJson).asString(); Event event = eventsDAO.findBySMIdAndName(Long.parseLong(smCreationResponse.getBody()), "event0"); assertThat(event.getStatus()).isEqualTo(Event.EventStatus.pending); String eventJson = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("event_data.json")); // state machine with correlationId magic_number_2 does not exist. The following call should bomb final HttpResponse<String> eventPostResponse = Unirest.post(STATE_MACHINE_RESOURCE_URL+SLASH+"magic_number_2"+"/context/events?searchField=correlationId").header("Content-Type","application/json").body(eventJson).asString(); assertThat(eventPostResponse.getStatus()).isEqualTo(Response.Status.NOT_FOUND.getStatusCode()); } @Test public void testFsmGraphCreation() throws Exception { final StateMachine stateMachine = stateMachinePersistenceService.createStateMachine(objectMapper.readValue(this.getClass().getClassLoader().getResource("state_machine_definition_fork_join.json"), StateMachineDefinition.class)); final HttpResponse<String> stringHttpResponse = Unirest.get(STATE_MACHINE_RESOURCE_URL + "/" + stateMachine.getId() + "/fsmdata").header("Content-Type", "application/json").asString(); assertThat(stringHttpResponse.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); //TODO - we need a better assert here, but since we're using database IDs in the implementation, we cannot simply validate it with a static json } @Test public void testGetErroredStates() throws Exception { final StateMachine sm = stateMachinePersistenceService.createStateMachine(objectMapper.readValue(this.getClass().getClassLoader().getResource("state_machine_definition.json"), StateMachineDefinition.class)); /* mark 1 of the state as errored */ sm.getStates().stream().findFirst().get().setStatus(Status.errored); /* persist */ final StateMachine firstSM = stateMachinesDAO.create(new StateMachine(sm.getVersion(), sm.getName(), sm.getDescription(), sm.getStates(), "uniqueCorId1")); /* change name and persist as 2nd statemachine */ final String differentSMName = "differentStateMachine"; final StateMachine secondSM = stateMachinesDAO.create(new StateMachine(sm.getVersion(), differentSMName, sm.getDescription(), sm.getStates(), "uniqueCorId2")); /* fetch errored states with name "differentStateMachine" */ final HttpResponse<String> stringHttpResponse = Unirest.get(STATE_MACHINE_RESOURCE_URL + "/" + differentSMName + "/states/errored?fromSmId=" + firstSM.getId() + "&toSmId=" + (secondSM.getId() + 1)).header("Content-Type", "application/json").asString(); assertThat(stringHttpResponse.getStatus()).isEqualTo(200); assertThat(stringHttpResponse.getBody()).isEqualTo("[[" + secondSM.getId() + "," + secondSM.getStates().stream().filter(e -> Status.errored.equals(e.getStatus())).findFirst().get().getId() + "," + "\"errored\"]]"); } }
3e08bf709b662255fa2eb56fbf0ac992f45c86cc
746
java
Java
src/main/java/com/alipay/api/domain/PreAmountClauseResult.java
fossabot/alipay-sdk-java-all
3972bc64e041eeef98e95d6fcd62cd7e6bf56964
[ "Apache-2.0" ]
null
null
null
src/main/java/com/alipay/api/domain/PreAmountClauseResult.java
fossabot/alipay-sdk-java-all
3972bc64e041eeef98e95d6fcd62cd7e6bf56964
[ "Apache-2.0" ]
null
null
null
src/main/java/com/alipay/api/domain/PreAmountClauseResult.java
fossabot/alipay-sdk-java-all
3972bc64e041eeef98e95d6fcd62cd7e6bf56964
[ "Apache-2.0" ]
null
null
null
17.348837
68
0.659517
3,701
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 订单业务中,商户的前置费用明细条目 * * @author auto create * @since 1.0, 2019-11-14 14:05:35 */ public class PreAmountClauseResult extends AlipayObject { private static final long serialVersionUID = 6511665696768341363L; /** * 具体的金额 */ @ApiField("amount") private String amount; /** * 用于指定金额的描述信息 */ @ApiField("desc") private String desc; public String getAmount() { return this.amount; } public void setAmount(String amount) { this.amount = amount; } public String getDesc() { return this.desc; } public void setDesc(String desc) { this.desc = desc; } }
3e08bfb47ace718d393282414510815e41177721
5,960
java
Java
edo/impl/src/main/java/org/kuali/kpme/edo/candidate/EdoSelectedCandidate.java
cniesen/kpme
cf1b17d0b947619428e1677ecde5da71de4b36c0
[ "ECL-2.0" ]
null
null
null
edo/impl/src/main/java/org/kuali/kpme/edo/candidate/EdoSelectedCandidate.java
cniesen/kpme
cf1b17d0b947619428e1677ecde5da71de4b36c0
[ "ECL-2.0" ]
null
null
null
edo/impl/src/main/java/org/kuali/kpme/edo/candidate/EdoSelectedCandidate.java
cniesen/kpme
cf1b17d0b947619428e1677ecde5da71de4b36c0
[ "ECL-2.0" ]
null
null
null
28.653846
135
0.702852
3,702
package org.kuali.kpme.edo.candidate; import org.apache.commons.lang.StringUtils; import org.kuali.kpme.edo.service.EdoServiceLocator; import org.kuali.kpme.edo.dossier.EdoDossierBo; import org.kuali.kpme.edo.util.EdoConstants; import org.kuali.kpme.edo.api.candidate.EdoCandidate; import org.kuali.kpme.edo.api.dossier.EdoDossier; import org.kuali.kpme.edo.api.dossier.type.EdoDossierType; import java.math.BigDecimal; /** * $HeadURL$ * $Revision$ * Created with IntelliJ IDEA. * User: bradleyt * Date: 11/8/12 * Time: 3:23 PM * To change this template use File | Settings | File Templates. */ public class EdoSelectedCandidate { private boolean isSelected; private String candidateID; private String candidateLastname; private String candidateFirstname; private String candidateUsername; private String candidateCampusCode; private String candidateSchoolID; private String candidateDepartmentID; private BigDecimal candidateDossierID; private String aoe; private String rankSought; private String dossierTypeCode; private String dossierStatus; private String dossierTypeName; private String dossierTypeFlag; private String dossierWorkflowId; private String aoeDescription; public String getDossierTypeName() { return dossierTypeName; } public void setDossierTypeName(String dossierTypeName) { this.dossierTypeName = dossierTypeName; } public EdoSelectedCandidate() {} public EdoSelectedCandidate(EdoCandidate edoCandidate, Boolean isSelected) { EdoDossier dossier = EdoServiceLocator.getEdoDossierService().getCurrentDossierPrincipalName(edoCandidate.getPrincipalName()); EdoDossierType dossierType = EdoServiceLocator.getEdoDossierTypeService().getEdoDossierTypeById(dossier.getEdoDossierTypeId()); setSelected(isSelected); setCandidateID(edoCandidate.getEdoCandidateId()); setCandidateLastname(edoCandidate.getLastName()); setCandidateFirstname(edoCandidate.getFirstName()); setCandidateUsername(edoCandidate.getPrincipalName()); //setCandidateCampusCode(edoCandidate.getCandidacyCampus()); setCandidateDepartmentID(edoCandidate.getPrimaryDeptId()); setCandidateSchoolID(edoCandidate.getCandidacySchool()); setAoe(dossier.getAoeCode()); setDossierTypeCode(dossierType.getDossierTypeCode()); setCandidateDossierID(new BigDecimal(dossier.getEdoDossierId())); setDossierWorkflowId(dossier.getWorkflowId()); } public String getDossierWorkflowId() { return dossierWorkflowId; } public void setDossierWorkflowId(String dossierWorkflowId) { this.dossierWorkflowId = dossierWorkflowId; } public boolean isSelected() { return isSelected; } public void setSelected(boolean selected) { isSelected = selected; } public String getCandidateCampusCode() { return candidateCampusCode; } public void setCandidateCampusCode(String candidateCampusCode) { this.candidateCampusCode = candidateCampusCode; } public String getCandidateSchoolID() { return candidateSchoolID; } public void setCandidateSchoolID(String candidateSchoolID) { this.candidateSchoolID = candidateSchoolID; } public String getCandidateDepartmentID() { return candidateDepartmentID; } public void setCandidateDepartmentID(String candidateDeparmentID) { this.candidateDepartmentID = candidateDeparmentID; } public String getCandidateID() { return candidateID; } public void setCandidateID(String candidateID) { this.candidateID = candidateID; } public String getCandidateFirstname() { return candidateFirstname; } public void setCandidateFirstname(String candidateFirstname) { this.candidateFirstname = candidateFirstname; } public String getCandidateLastname() { return candidateLastname; } public void setCandidateLastname(String candidateLastname) { this.candidateLastname = candidateLastname; } public String getCandidateUsername() { return candidateUsername; } public void setCandidateUsername(String candidateUsername) { this.candidateUsername = candidateUsername; } public BigDecimal getCandidateDossierID() { return candidateDossierID; } public void setCandidateDossierID(BigDecimal candidateDossierID) { this.candidateDossierID = candidateDossierID; } public String getRankSought() { return rankSought; } public void setRankSought(String rankSought) { this.rankSought = rankSought; } public String getAoe() { return aoe; } public void setAoe(String aoe) { this.aoe = aoe; } public String getDossierTypeCode() { return dossierTypeCode; } public void setDossierTypeCode(String dossierTypeCode) { this.dossierTypeCode = dossierTypeCode; setDossierTypeFlag(); } public String getDossierTypeFlag() { return dossierTypeFlag; } public void setDossierTypeFlag() { if (this.dossierTypeCode.startsWith("T")) { this.dossierTypeFlag = "Yes"; } else { this.dossierTypeFlag = "No"; } } public String getDossierStatus() { return dossierStatus; } public void setDossierStatus(String dossierStatus) { this.dossierStatus = dossierStatus; } public String getAoeDescription() { String aoeDescription = StringUtils.EMPTY; if (StringUtils.isNotBlank(this.aoe)) { String aoeValue = EdoConstants.AREA_OF_EXCELLENCE.get(this.aoe); if (StringUtils.isNotBlank(aoeValue)) { aoeDescription = aoeValue; } } return aoeDescription; } }
3e08bfc063ef90aa15d256ddfb080b530cdf523c
1,372
java
Java
orcamento-familiar/src/main/java/alura/orcamentofamiliar/usuario/adapter/out/persistence/UsuarioPersistenceAdapter.java
michaeldiogo253/planejamento-familiar-rest
f7ec67e0b624ad1c5fad792b4b04c1ed05c00f83
[ "MIT" ]
null
null
null
orcamento-familiar/src/main/java/alura/orcamentofamiliar/usuario/adapter/out/persistence/UsuarioPersistenceAdapter.java
michaeldiogo253/planejamento-familiar-rest
f7ec67e0b624ad1c5fad792b4b04c1ed05c00f83
[ "MIT" ]
null
null
null
orcamento-familiar/src/main/java/alura/orcamentofamiliar/usuario/adapter/out/persistence/UsuarioPersistenceAdapter.java
michaeldiogo253/planejamento-familiar-rest
f7ec67e0b624ad1c5fad792b4b04c1ed05c00f83
[ "MIT" ]
null
null
null
37.081081
127
0.789359
3,703
package alura.orcamentofamiliar.usuario.adapter.out.persistence; import alura.orcamentofamiliar.usuario.application.port.out.FindUsuarioByIdPort; import alura.orcamentofamiliar.usuario.application.port.out.FindUsuarioByLoginPort; import alura.orcamentofamiliar.usuario.application.port.out.SalvarUsuarioPort; import alura.orcamentofamiliar.usuario.domain.Usuario; import alura.orcamentofamiliar.util.exceptions.ResourceNotFoundException; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component @RequiredArgsConstructor(onConstructor = @__(@Autowired)) public class UsuarioPersistenceAdapter implements SalvarUsuarioPort, FindUsuarioByIdPort, FindUsuarioByLoginPort { private final UsuarioRepository usuarioRepository; @Override public void salvarUsuario(Usuario usuario) { usuarioRepository.save(usuario); } @Override public Usuario findUsuarioById(Long id) { return usuarioRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException("Usuario não encontrado")); } @Override public Usuario findUsuarioByLogin(String login) { return usuarioRepository.findByLogin(login).orElseThrow(() -> new ResourceNotFoundException("Usuario não encontrado")); } }
3e08c05210bd74a7d662cc623d19c1b08554ac11
27,567
java
Java
triana-shiwaall/src/main/java/org/trianacode/shiwaall/iwir/importer/utils/ImportIwir.java
CSCSI/Triana
da48ffaa0183f59e3fe7c6dc59d9f91234e65809
[ "Apache-2.0" ]
8
2015-11-02T10:12:13.000Z
2019-01-15T21:45:38.000Z
triana-shiwaall/src/main/java/org/trianacode/shiwaall/iwir/importer/utils/ImportIwir.java
CSCSI/Triana
da48ffaa0183f59e3fe7c6dc59d9f91234e65809
[ "Apache-2.0" ]
1
2015-08-28T13:52:42.000Z
2016-01-22T13:06:00.000Z
triana-shiwaall/src/main/java/org/trianacode/shiwaall/iwir/importer/utils/ImportIwir.java
CSCSI/Triana
da48ffaa0183f59e3fe7c6dc59d9f91234e65809
[ "Apache-2.0" ]
2
2022-03-08T14:04:52.000Z
2022-03-09T05:30:21.000Z
44.391304
170
0.585301
3,704
package org.trianacode.shiwaall.iwir.importer.utils; import org.shiwa.desktop.data.transfer.FGIWorkflowReader; import org.shiwa.fgi.iwir.*; import org.trianacode.TrianaInstance; import org.trianacode.enactment.AddonUtils; import org.trianacode.shiwaall.iwir.execute.Executable; import org.trianacode.shiwaall.iwir.factory.TaskHolderFactory; import org.trianacode.shiwaall.test.InOut; import org.trianacode.taskgraph.*; import org.trianacode.taskgraph.Task; import org.trianacode.taskgraph.proxy.ProxyInstantiationException; import org.trianacode.taskgraph.tool.Tool; import javax.xml.bind.JAXBException; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; // TODO: Auto-generated Javadoc /** * Created by IntelliJ IDEA. * User: Ian Harvey * Date: 24/10/2011 * Time: 14:49 * To change this template use File | Settings | File Templates. */ public class ImportIwir { /** The abstract hash map. */ private HashMap<AbstractTask, Task> abstractHashMap = new HashMap<AbstractTask, Task>(); /** The data links. */ private HashSet<DataLink> dataLinks = new HashSet<DataLink>(); /** The std. */ boolean std = false; /** The fgi workflow reader. */ private FGIWorkflowReader fgiWorkflowReader = null; /** The Constant IWIR_NODE. */ public static final String IWIR_NODE = "iwirNode"; /** * Std out. * * @param string the string */ private void stdOut(String string){ if(std){ System.out.println(string); } } /** * The main method. * * @param args the arguments * @throws IOException Signals that an I/O exception has occurred. * @throws CableException the cable exception * @throws JAXBException the jAXB exception * @throws ProxyInstantiationException the proxy instantiation exception * @throws TaskException the task exception */ public static void main(String[] args) throws IOException, CableException, JAXBException, ProxyInstantiationException, TaskException { ImportIwir importIwir = new ImportIwir(); IWIR iwir = new IWIR(new File("/Users/ian/Downloads/fgibundle/workflow.xml.iwir")); TrianaInstance engine = new TrianaInstance(args); engine.init(); TaskGraph taskGraph = importIwir.taskFromIwir(iwir, null); System.exit(0); } /** * sets the fgiWorkflowReader for this bundle. * * @param fgiBundleFile the fgi bundle file * @throws JAXBException the jAXB exception * @throws IOException Signals that an I/O exception has occurred. */ private void initFGIWorkflowReader(File fgiBundleFile) throws JAXBException, IOException { if(fgiBundleFile != null){ System.out.println("fgiBundleFile = " + fgiBundleFile.exists() + " " + fgiBundleFile.getAbsolutePath()); fgiWorkflowReader = new FGIWorkflowReader(fgiBundleFile); } else { System.out.println("No fgi bundle returned, " + "best effort triana-only tools will be used"); } } /** * Task from iwir. * * @param iwir the iwir * @param fgiBundle the fgi bundle * @return the task graph * @throws TaskException the task exception * @throws ProxyInstantiationException the proxy instantiation exception * @throws CableException the cable exception * @throws JAXBException the jAXB exception * @throws IOException Signals that an I/O exception has occurred. */ public TaskGraph taskFromIwir(IWIR iwir, File fgiBundle) throws TaskException, ProxyInstantiationException, CableException, JAXBException, IOException { initFGIWorkflowReader(fgiBundle); //create a new taskgraph for the workflow AbstractTask mainTask = iwir.getTask(); TaskGraph taskGraph = TaskGraphManager.createTaskGraph(); //recurse the iwir structure, add to taskgraph recordAbstractTasksAndDataLinks(mainTask, taskGraph); stdOut(taskGraph.toString()); //The following block of code looks for root IWIR ports which //map to more than one task. Triana likes one 2 one mappings, IWIR allows one 2 many. // Make a copy of all the data links to iterate through ArrayList<DataLink> copyOfDataLinks = new ArrayList<DataLink>(); copyOfDataLinks.addAll(dataLinks); //for matching ports to new "splitting" tasks HashMap<AbstractPort, Task> alternativeNodes = new HashMap<AbstractPort, Task>(); // map of the root input port to the multiple datalink it has connected to it HashMap<AbstractPort, ArrayList<DataLink>> collisions = new HashMap<AbstractPort, ArrayList<DataLink>>(); //iterate through datalinks for (DataLink dataLink : dataLinks) { //check to see if ports task is the root taskgraph. if(abstractHashMap.get(dataLink.getFromPort().getMyTask()) == taskGraph && !collisions.containsKey(dataLink.getFromPort()) ){ AbstractPort sendingPort = dataLink.getFromPort(); ArrayList<DataLink> collidingLinks = new ArrayList<DataLink>(); //iterate through the copy of the links for(DataLink anotherDataLink : copyOfDataLinks) { //if the link is not itself && they have the same "from" port, its a collision if( dataLink != anotherDataLink && dataLink.getFrom().equals(anotherDataLink.getFrom())){ System.out.println("####### port collision, " + dataLink.getFrom() + " : " + dataLink.getTo() + " : " + anotherDataLink.getTo() ); //build up a list of colliding datalinks from this port collidingLinks.add(anotherDataLink); } } //if there is more than one datalink on this port, // add the original link too, and store the port if(collidingLinks.size() > 0){ System.out.println("port " + sendingPort.getName() + " collides with " + collidingLinks.size()); collidingLinks.add(dataLink); collisions.put(sendingPort, collidingLinks); } } } //go through the colliding ports for(AbstractPort abstractPort : collisions.keySet()){ Task scopedTaskgraph = abstractHashMap.get(abstractPort.getMyTask()); if( scopedTaskgraph instanceof TaskGraph){ System.out.println("Will create now splitting task in " + taskGraph.getToolName()); //create the splitting tool which passes one input to multiple receiveing nodes Tool tool = AddonUtils.makeTool(InOut.class, abstractPort.getUniqueId(), scopedTaskgraph.getProperties()); Task task = taskGraph.createTask(tool); // taskGraph.connect(task.addDataOutputNode(), abstractHashMap.get(abstractPort.getMyTask()).addDataInputNode()); //add connection from splitting node to each new port. for(DataLink anotherDataLink : collisions.get(abstractPort)){ Task receivingTask = abstractHashMap.get(anotherDataLink.getToPort().getMyTask()); Node receivingNode = receivingTask.addDataInputNode(); Node sendingNode = task.addDataOutputNode(); taskGraph.connect(sendingNode, receivingNode); //Record the links for data matching up later if(receivingTask.isParameterName(Executable.EXECUTABLE)){ Executable executable = (Executable) receivingTask.getParameter(Executable.EXECUTABLE); // executable.addPort(receivingNode.getTopLevelNode().getName(), anotherDataLink.getToPort().getName()); executable.addExecutableNodeMapping(receivingNode, anotherDataLink.getToPort()); receivingTask.setParameter(Executable.EXECUTABLE, executable); } if(task.isParameterName(Executable.EXECUTABLE)){ Executable executable = (Executable) task.getParameter(Executable.EXECUTABLE); // executable.addPort(sendingNode.getTopLevelNode().getName(), anotherDataLink.getFromPort().getName()); executable.addExecutableNodeMapping(sendingNode, anotherDataLink.getFromPort()); receivingTask.setParameter(Executable.EXECUTABLE, executable); } } //for future reference, this port now maps to one specific task alternativeNodes.put(abstractPort, task); } } //continue with standard cable creation. HashSet<AbstractPort> toIgnore = new HashSet<AbstractPort>(); for (DataLink dataLink : dataLinks) { if(!toIgnore.contains(dataLink.getFromPort())){ stdOut("\nLink from " + dataLink.getFromPort() + " (" + dataLink.getFromPort().getType().toString() + ") " + " to " + dataLink.getToPort() + " (" + dataLink.getToPort().getType().toString() + ")" ); AbstractPort outgoingPort = dataLink.getFromPort(); AbstractPort incomingPort = dataLink.getToPort(); stdOut(outgoingPort.getPredecessors().toString()); stdOut(outgoingPort.getAllSuccessors().toString()); stdOut(incomingPort.getPredecessors().toString()); stdOut(incomingPort.getAllSuccessors().toString()); AbstractTask sendingAbstract = outgoingPort.getMyTask(); AbstractTask receivingAbstract = incomingPort.getMyTask(); Task sendingTask = abstractHashMap.get(sendingAbstract); Task receivingTask = abstractHashMap.get(receivingAbstract); if(alternativeNodes.keySet().contains(outgoingPort)){ receivingTask = alternativeNodes.get(outgoingPort); toIgnore.add(outgoingPort); } // stdOut("Will connect " + sendingTask + " to " + receivingTask); if (sendingTask == receivingTask.getParent()) { Node receivingNode = receivingTask.addDataInputNode(); Node graphNode = ((TaskGraph) sendingTask).addDataInputNode(receivingNode); inputChain(outgoingPort, graphNode); TaskGraph parentGraph = ((TaskGraph)sendingTask); parentGraph.setParameter(outgoingPort.getName(), graphNode.getAbsoluteNodeIndex()); System.out.println("fromPort " + outgoingPort.getName() + " graphPort " + graphNode.getName() + " index " + graphNode.getAbsoluteNodeIndex() ); if(receivingTask.isParameterName(Executable.EXECUTABLE)){ Executable executable = (Executable) receivingTask.getParameter(Executable.EXECUTABLE); // executable.addPort(receivingNode.getTopLevelNode().getName(), incomingPort.getName()); executable.addExecutableNodeMapping(receivingNode, incomingPort); receivingTask.setParameter(Executable.EXECUTABLE, executable); } } if (receivingTask == sendingTask.getParent()) { Node sendingNode = sendingTask.addDataOutputNode(); Node graphNode = ((TaskGraph) receivingTask).addDataOutputNode(sendingNode); outputChain(incomingPort, graphNode); if(sendingTask.isParameterName(Executable.EXECUTABLE)){ Executable executable = (Executable) sendingTask.getParameter(Executable.EXECUTABLE); // executable.addPort(sendingNode.getTopLevelNode().getName(), outgoingPort.getName()); executable.addExecutableNodeMapping(sendingNode, outgoingPort); sendingTask.setParameter(Executable.EXECUTABLE, executable); } } //check both are atomic tasks if (sendingAbstract instanceof org.shiwa.fgi.iwir.Task && receivingAbstract instanceof org.shiwa.fgi.iwir.Task) { if (sendingTask.getParent() == receivingTask.getParent()) { TaskGraph scopeTaskgraph = sendingTask.getParent(); stdOut("Connecting " + sendingTask.getQualifiedToolName() + " to " + receivingTask.getQualifiedToolName() + " in " + scopeTaskgraph.getQualifiedToolName() ); Node sendingNode = sendingTask.addDataOutputNode(); Node receivingNode = receivingTask.addDataInputNode(); scopeTaskgraph.connect(sendingNode, receivingNode); if(sendingTask.isParameterName(Executable.EXECUTABLE)){ Executable executable = (Executable) sendingTask.getParameter(Executable.EXECUTABLE); // executable.addPort(sendingNode.getTopLevelNode().getName(), outgoingPort.getName()); executable.addExecutableNodeMapping(sendingNode, outgoingPort); sendingTask.setParameter(Executable.EXECUTABLE, executable); } if(receivingTask.isParameterName(Executable.EXECUTABLE)){ Executable executable = (Executable) receivingTask.getParameter(Executable.EXECUTABLE); // executable.addPort(receivingNode.getTopLevelNode().getName(), incomingPort.getName()); executable.addExecutableNodeMapping(receivingNode, incomingPort); receivingTask.setParameter(Executable.EXECUTABLE, executable); } } } } } return taskGraph; } /** * Input chain. * * @param outgoingPort the outgoing port * @param inputNode the input node */ private void inputChain(AbstractPort outgoingPort, Node inputNode) { try { for (DataLink dataLink : dataLinks) { if (dataLink.getToPort() == outgoingPort) { //TODO Task scopedTask = abstractHashMap.get(dataLink.getFromPort().getMyTask()); if (!(scopedTask instanceof TaskGraph)) { Node outputNode = scopedTask.addDataOutputNode(); scopedTask.getParent().connect(outputNode, inputNode); } } } } catch (Exception e) { e.printStackTrace(); } } /** * Output chain. * * @param iwirReceivingPort the iwir receiving port * @param graphOutputNode the graph output node * @throws NodeException the node exception * @throws CableException the cable exception */ private void outputChain(AbstractPort iwirReceivingPort, Node graphOutputNode) throws NodeException, CableException { for (DataLink dataLink : dataLinks) { if (dataLink.getFromPort() == iwirReceivingPort) { //TODO Task scopedTask = abstractHashMap.get(dataLink.getToPort().getMyTask()); if (!(scopedTask instanceof TaskGraph)) { Node inputNode = scopedTask.addDataInputNode(); scopedTask.getParent().connect(graphOutputNode, inputNode); } } } } /** * Creates the from iwir task. * * @param iwirTask the iwir task * @param tg the tg * @return the task * @throws TaskException the task exception * @throws JAXBException the jAXB exception * @throws IOException Signals that an I/O exception has occurred. * @throws ProxyInstantiationException the proxy instantiation exception */ private Task createFromIWIRTask(AbstractTask iwirTask, TaskGraph tg) throws TaskException, JAXBException, IOException, ProxyInstantiationException { //if the iwirTask is a standard IWIR Atomic Task, try to find and/or make a tool for it. //this requires the taskType string, the name and the taskgraph properties System.out.println("Making " + iwirTask.getUniqueId()); Task trianaTask = TaskTypeRepo.getTaskFromType( (org.shiwa.fgi.iwir.Task) iwirTask, fgiWorkflowReader, tg, true); // Tool newTask = TaskTypeRepo.getToolFromType( // (org.shiwa.fgi.iwir.Task) iwirTask, tg.getProperties()); System.out.println(); //add the iwir property strings to the triana task for (Property property : iwirTask.getProperties()) { trianaTask.setParameter(property.getName(), property.getValue()); trianaTask.setParameterType(property.getName(), Tool.USER_ACCESSIBLE); } return trianaTask; } /** * Adds the nodes. * * @param mainTask the main task * @param task the task * @param tg the tg * @throws NodeException the node exception */ private void addNodes(AbstractTask mainTask, Task task, TaskGraph tg) throws NodeException { Executable executable = null; if(task.isParameterName(Executable.EXECUTABLE)){ executable = (Executable) task.getParameter(Executable.EXECUTABLE); } for (AbstractPort port : mainTask.getAllInputPorts()) { System.out.println("Input port " + port.getName() + " " + port.getClass().getCanonicalName()); Node newNode = null; if (port instanceof InputPort) { newNode = tg.addDataInputNode(task.addDataInputNode()); } if (port instanceof LoopPort || port instanceof LoopElement) { // newNode = task.addParameterInputNode("loop"); newNode = tg.addDataInputNode(task.addDataInputNode()); stdOut("Loop port found " + port.getName()); } if(newNode != null && executable != null){ // executable.addPort(newNode.getTopLevelNode().getName(), port.getName()); executable.addExecutableNodeMapping(newNode.getTopLevelNode(), port); } } for (AbstractPort port : mainTask.getAllOutputPorts()) { Node newNode = null; if (port instanceof OutputPort) { newNode = tg.addDataOutputNode(task.addDataOutputNode()); } if (port instanceof LoopPort) { newNode = task.addParameterOutputNode("loop"); } if(newNode != null && executable != null){ // executable.addPort(newNode.getTopLevelNode().getName(), port.getName()); executable.addExecutableNodeMapping(newNode.getTopLevelNode(), port); } } if(executable != null){ task.setParameter(Executable.EXECUTABLE, executable); } } /** * Record abstract tasks and data links. * * @param mainTask the main task * @param tg the tg * @return the task graph * @throws ProxyInstantiationException the proxy instantiation exception * @throws TaskException the task exception * @throws IOException Signals that an I/O exception has occurred. * @throws JAXBException the jAXB exception */ private TaskGraph recordAbstractTasksAndDataLinks(AbstractTask mainTask, TaskGraph tg) throws ProxyInstantiationException, TaskException, IOException, JAXBException { // TaskGraph taskGraph = TaskGraphManager.createTaskGraph(); // taskGraph.setToolName(mainTask.getName()); tg.setToolName(mainTask.getName()); //If there is only one task in the workflow, the mainTask with be a Task (ie not Compound) if(mainTask instanceof org.shiwa.fgi.iwir.Task) { abstractHashMap.put(mainTask, tg); //create a new Triana Task from the IWIR info, and add to taskgraph Task task = createFromIWIRTask(mainTask, tg); addNodes(mainTask, task, tg); } else { dataLinks.addAll(((AbstractCompoundTask) mainTask).getDataLinks()); abstractHashMap.put(mainTask, tg); if (!(mainTask instanceof org.shiwa.fgi.iwir.Task) && !(mainTask instanceof BlockScope)) { Task controlTask = TaskHolderFactory.getTaskHolderFactory().addTaskHolder(mainTask, tg); // Task controlTask = tg.createTask(ToolUtils.initTool(taskHolder, tg.getProperties())); // taskGraph.createTask(ToolUtils.initTool(taskHolder, taskGraph.getProperties())); abstractHashMap.put(mainTask, controlTask); addNodes(mainTask, controlTask, tg); } for (AbstractTask iwirTask : mainTask.getChildren()) { if (iwirTask instanceof org.shiwa.fgi.iwir.Task) { // String taskType = ((org.shiwa.fgi.iwir.Task) iwirTask).getTasktype(); // // //if the iwirTask is a standard IWIR Atomic Task, try to find and/or make a tool for it. // //this requires the taskType string, the name and the taskgraph properties // // Tool newTask = TaskTypeToTool.getToolFromType( // (org.shiwa.fgi.iwir.Task) iwirTask, fgiWorkflowReader, tg.getProperties()); // // Task trianaTask = tg.createTask(newTask); // trianaTask.setToolName(iwirTask.getName()); // trianaTask.setParameter(Executable.TASKTYPE, taskType); // // //add the iwir property strings to the triana task // for (Property property : iwirTask.getProperties()) { // trianaTask.setParameter(property.getName(), property.getValue()); // trianaTask.setParameterType(property.getName(), Tool.USER_ACCESSIBLE); // } Task trianaTask = createFromIWIRTask(iwirTask, tg); abstractHashMap.put(iwirTask, trianaTask); } else { if (iwirTask instanceof AbstractCompoundTask) { TaskGraph innerTaskGraph = TaskGraphManager.createTaskGraph(); TaskGraph concreteTaskGraph = (TaskGraph) tg.createTask(innerTaskGraph); recordAbstractTasksAndDataLinks(iwirTask, concreteTaskGraph); // TaskGraph innerTaskGraph = recordAbstractTasksAndDataLinks(iwirTask); // TaskGraph concreteTaskGraph = (TaskGraph) taskGraph.createTask(innerTaskGraph); } } } } return tg; } //top level connections // if (sendingTask == taskGraph && receivingAbstract instanceof org.shiwa.fgi.iwir.Task) { // if (receivingTask.getParent() == sendingTask) { // stdOut("Connecting " + receivingTask + " to the parent graph"); // taskGraph.addDataInputNode(receivingTask.addDataInputNode()); // } // } // // if (receivingTask == taskGraph && sendingAbstract instanceof org.shiwa.fgi.iwir.Task) { // if (sendingTask.getParent() == taskGraph) { // stdOut("Connecting " + sendingTask + " to the parent graph"); // taskGraph.addDataOutputNode(sendingTask.addDataOutputNode()); // } // } // Node outputNode; // Node inputNode; // TaskGraph scopeTaskGraph = sendingTask.getParent(); //TODO Input chain // if(!(receivingTask instanceof TaskGraph)){ // for (AbstractPort abstractPort : incomingPort.getPredecessors()){ // stdOut("**predecessors " + // abstractHashMap.get(abstractPort.getMyTask()).getToolName()); // if(abstractPort.getPredecessors().size() != 0){ // List<AbstractPort> ports = abstractPort.getPredecessors(); // for(AbstractPort port : ports){ // stdOut(abstractHashMap.get(port.getMyTask())); // } // } // // // Node scopeNode = receivingTask.addDataInputNode(); // stdOut("Tasks input node " + scopeNode.getName()); // Task topLevelTask; // List<AbstractPort> abstractPorts = incomingPort.getPredecessors(); // while(abstractPorts.size() > 0){ // for(AbstractPort port : abstractPorts){ // topLevelTask = abstractHashMap.get(port.getMyTask()); // stdOut("pre " + topLevelTask.getToolName()); // // if(topLevelTask instanceof TaskGraph){ // TaskGraph scopeGraph = (TaskGraph)topLevelTask; // stdOut("node " + scopeNode.getName()); // stdOut("in graph " + scopeGraph.getToolName()); // Node newNode = scopeGraph.addDataInputNode(scopeNode); // stdOut("new node " + newNode.getName()); // scopeNode = newNode; // } // } // stdOut(abstractPorts.get(0).getPredecessors().size()); // abstractPorts = abstractPorts.get(0).getPredecessors(); // } // // } // // } // //TODO Output chain // if(!(sendingTask instanceof TaskGraph)){ // for( AbstractPort abstractPort : outgoingPort.getAllSuccessors()){ // stdOut("**successor " + // abstractHashMap.get(abstractPort.getMyTask()).getToolName()); // } // // } // stdOut("\nWill connect tasks " + sendingTask.getToolName() // + " to " + receivingTask.getToolName()); // if(sendingTask.getParent() == receivingTask.getParent() && scopeTaskGraph != null){ // outputNode = sendingTask.addDataOutputNode(); // inputNode = receivingTask.addDataInputNode(); // stdOut("In scope taskGraph : " + scopeTaskGraph); // scopeTaskGraph.connect(outputNode, inputNode); // } else { // // stdOut("Out of scope"); // } // // } //// addTaskGraphNodesFromIWIR(mainTask); // return taskGraph; // } }
3e08c0e1e375f9cd87631a863e8ade0818b58c81
1,197
java
Java
chapter_010/mapping/src/main/java/ru/sdroman/carsales/repository/Repository.java
roman-sd/java-a-to-z
5f59ece8793e0a3df099ff079954aaa7d900a918
[ "Apache-2.0" ]
null
null
null
chapter_010/mapping/src/main/java/ru/sdroman/carsales/repository/Repository.java
roman-sd/java-a-to-z
5f59ece8793e0a3df099ff079954aaa7d900a918
[ "Apache-2.0" ]
null
null
null
chapter_010/mapping/src/main/java/ru/sdroman/carsales/repository/Repository.java
roman-sd/java-a-to-z
5f59ece8793e0a3df099ff079954aaa7d900a918
[ "Apache-2.0" ]
null
null
null
24.9375
73
0.575606
3,705
package ru.sdroman.carsales.repository; import org.apache.log4j.Logger; import org.hibernate.HibernateException; import org.hibernate.Session; import ru.sdroman.carsales.hibernate.HibernateSessionFactory; import java.util.function.Function; /** * @author sdroman * @since 06.2018 */ public abstract class Repository { /** * Logger. */ private static final Logger LOG = Logger.getLogger(Repository.class); /** * Execute. * * @param command Function * @param <T> Type * @return result */ public <T> T execute(final Function<Session, T> command) { Session session = null; try { session = HibernateSessionFactory.getFactory().openSession(); session.beginTransaction(); return command.apply(session); } catch (HibernateException e) { if (session != null) { session.getTransaction().rollback(); } LOG.error(e.getMessage(), e); return null; } finally { if (session != null) { session.getTransaction().commit(); session.close(); } } } }
3e08c10ebdb1d39eb207e3b0a40826914a526953
22,150
java
Java
core/src/main/java/com/sequenceiq/cloudbreak/core/flow2/stack/upscale/StackUpscaleActions.java
sidseth/cloudbreak
83a48d7f918b7e2a1476f9c3573fb2eff0712c99
[ "Apache-2.0" ]
174
2017-07-14T03:20:42.000Z
2022-03-25T05:03:18.000Z
core/src/main/java/com/sequenceiq/cloudbreak/core/flow2/stack/upscale/StackUpscaleActions.java
sidseth/cloudbreak
83a48d7f918b7e2a1476f9c3573fb2eff0712c99
[ "Apache-2.0" ]
2,242
2017-07-12T05:52:01.000Z
2022-03-31T15:50:08.000Z
core/src/main/java/com/sequenceiq/cloudbreak/core/flow2/stack/upscale/StackUpscaleActions.java
sidseth/cloudbreak
83a48d7f918b7e2a1476f9c3573fb2eff0712c99
[ "Apache-2.0" ]
172
2017-07-12T08:53:48.000Z
2022-03-24T12:16:33.000Z
57.532468
161
0.704424
3,706
package com.sequenceiq.cloudbreak.core.flow2.stack.upscale; import static com.sequenceiq.cloudbreak.core.flow2.stack.upscale.AbstractStackUpscaleAction.HOSTNAMES; import static com.sequenceiq.cloudbreak.core.flow2.stack.upscale.AbstractStackUpscaleAction.INSTANCEGROUPNAME; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.statemachine.action.Action; import com.sequenceiq.cloudbreak.cloud.event.instance.CollectMetadataRequest; import com.sequenceiq.cloudbreak.cloud.event.instance.CollectMetadataResult; import com.sequenceiq.cloudbreak.cloud.event.instance.GetSSHFingerprintsRequest; import com.sequenceiq.cloudbreak.cloud.event.instance.GetSSHFingerprintsResult; import com.sequenceiq.cloudbreak.cloud.event.resource.UpscaleStackRequest; import com.sequenceiq.cloudbreak.cloud.event.resource.UpscaleStackResult; import com.sequenceiq.cloudbreak.cloud.event.resource.UpscaleStackValidationRequest; import com.sequenceiq.cloudbreak.cloud.event.resource.UpscaleStackValidationResult; import com.sequenceiq.cloudbreak.cloud.model.CloudInstance; import com.sequenceiq.cloudbreak.cloud.model.CloudResource; import com.sequenceiq.cloudbreak.cloud.model.CloudResourceStatus; import com.sequenceiq.cloudbreak.cloud.model.CloudStack; import com.sequenceiq.cloudbreak.cloud.model.InstanceStatus; import com.sequenceiq.cloudbreak.cloud.model.ResourceStatus; import com.sequenceiq.cloudbreak.clusterproxy.ClusterProxyEnablementService; import com.sequenceiq.cloudbreak.common.event.Selectable; import com.sequenceiq.cloudbreak.common.exception.CloudbreakServiceException; import com.sequenceiq.cloudbreak.common.exception.NotFoundException; import com.sequenceiq.cloudbreak.common.service.TransactionService.TransactionExecutionException; import com.sequenceiq.cloudbreak.converter.spi.InstanceMetaDataToCloudInstanceConverter; import com.sequenceiq.cloudbreak.converter.spi.ResourceToCloudResourceConverter; import com.sequenceiq.cloudbreak.converter.spi.StackToCloudStackConverter; import com.sequenceiq.cloudbreak.core.flow2.event.StackScaleTriggerEvent; import com.sequenceiq.cloudbreak.core.flow2.stack.AbstractStackFailureAction; import com.sequenceiq.cloudbreak.core.flow2.stack.StackFailureContext; import com.sequenceiq.cloudbreak.core.flow2.stack.downscale.StackScalingFlowContext; import com.sequenceiq.cloudbreak.core.flow2.stack.provision.StackCreationEvent; import com.sequenceiq.cloudbreak.domain.stack.Stack; import com.sequenceiq.cloudbreak.domain.stack.instance.InstanceGroup; import com.sequenceiq.cloudbreak.domain.stack.instance.InstanceMetaData; import com.sequenceiq.cloudbreak.reactor.api.event.StackEvent; import com.sequenceiq.cloudbreak.reactor.api.event.StackFailureEvent; import com.sequenceiq.cloudbreak.reactor.api.event.orchestration.ClusterProxyReRegistrationRequest; import com.sequenceiq.cloudbreak.reactor.api.event.resource.BootstrapNewNodesRequest; import com.sequenceiq.cloudbreak.reactor.api.event.resource.BootstrapNewNodesResult; import com.sequenceiq.cloudbreak.reactor.api.event.resource.ExtendHostMetadataRequest; import com.sequenceiq.cloudbreak.reactor.api.event.resource.ExtendHostMetadataResult; import com.sequenceiq.cloudbreak.reactor.api.event.stack.CleanupFreeIpaEvent; import com.sequenceiq.cloudbreak.service.environment.EnvironmentClientService; import com.sequenceiq.cloudbreak.service.metrics.MetricType; import com.sequenceiq.cloudbreak.service.publicendpoint.ClusterPublicEndpointManagementService; import com.sequenceiq.cloudbreak.service.resource.ResourceService; import com.sequenceiq.cloudbreak.service.stack.InstanceGroupService; import com.sequenceiq.cloudbreak.service.stack.InstanceMetaDataService; import com.sequenceiq.cloudbreak.service.stack.StackService; import com.sequenceiq.common.api.type.InstanceGroupType; import com.sequenceiq.environment.api.v1.environment.model.response.DetailedEnvironmentResponse; @Configuration public class StackUpscaleActions { private static final Logger LOGGER = LoggerFactory.getLogger(StackUpscaleActions.class); @Inject private ResourceToCloudResourceConverter cloudResourceConverter; @Inject private InstanceMetaDataService instanceMetaDataService; @Inject private StackUpscaleService stackUpscaleService; @Inject private StackToCloudStackConverter cloudStackConverter; @Inject private InstanceGroupService instanceGroupService; @Inject private InstanceMetaDataToCloudInstanceConverter metadataConverter; @Inject private ResourceService resourceService; @Inject private StackService stackService; @Inject private StackScalabilityCondition stackScalabilityCondition; @Inject private ClusterPublicEndpointManagementService clusterPublicEndpointManagementService; @Inject private EnvironmentClientService environmentClientService; @Bean(name = "UPSCALE_PREVALIDATION_STATE") public Action<?, ?> prevalidate() { return new AbstractStackUpscaleAction<>(StackScaleTriggerEvent.class) { @Override protected void prepareExecution(StackScaleTriggerEvent payload, Map<Object, Object> variables) { variables.put(INSTANCEGROUPNAME, payload.getInstanceGroup()); variables.put(ADJUSTMENT, payload.getAdjustment()); variables.put(HOSTNAMES, payload.getHostNames()); variables.put(REPAIR, payload.isRepair()); variables.put(NETWORK_SCALE_DETAILS, payload.getNetworkScaleDetails()); } @Override protected void doExecute(StackScalingFlowContext context, StackScaleTriggerEvent payload, Map<Object, Object> variables) { int instanceCountToCreate = getInstanceCountToCreate(context.getStack(), payload.getInstanceGroup(), payload.getAdjustment()); stackUpscaleService.addInstanceFireEventAndLog(context.getStack(), payload.getAdjustment(), payload.getInstanceGroup()); if (instanceCountToCreate > 0) { stackUpscaleService.startAddInstances(context.getStack(), payload.getAdjustment(), payload.getInstanceGroup()); sendEvent(context); } else { List<CloudResourceStatus> list = resourceService.getAllAsCloudResourceStatus(payload.getResourceId()); UpscaleStackResult result = new UpscaleStackResult(payload.getResourceId(), ResourceStatus.CREATED, list); sendEvent(context, result.selector(), result); } } @Override protected Selectable createRequest(StackScalingFlowContext context) { LOGGER.debug("Assembling upscale stack event for stack: {}", context.getStack()); int instanceCountToCreate = getInstanceCountToCreate(context.getStack(), context.getInstanceGroupName(), context.getAdjustment()); Stack updatedStack = instanceMetaDataService.saveInstanceAndGetUpdatedStack(context.getStack(), instanceCountToCreate, context.getInstanceGroupName(), false, context.getHostNames(), context.isRepair(), context.getStackNetworkScaleDetails()); CloudStack cloudStack = cloudStackConverter.convert(updatedStack); return new UpscaleStackValidationRequest<UpscaleStackValidationResult>(context.getCloudContext(), context.getCloudCredential(), cloudStack); } }; } @Bean(name = "ADD_INSTANCES_STATE") public Action<?, ?> addInstances() { return new AbstractStackUpscaleAction<>(UpscaleStackValidationResult.class) { @Override protected void doExecute(StackScalingFlowContext context, UpscaleStackValidationResult payload, Map<Object, Object> variables) { sendEvent(context); } @Override protected Selectable createRequest(StackScalingFlowContext context) { LOGGER.debug("Assembling upscale stack event for stack: {}", context.getStack()); int instanceCountToCreate = getInstanceCountToCreate(context.getStack(), context.getInstanceGroupName(), context.getAdjustment()); Stack updatedStack = instanceMetaDataService.saveInstanceAndGetUpdatedStack(context.getStack(), instanceCountToCreate, context.getInstanceGroupName(), true, context.getHostNames(), context.isRepair(), context.getStackNetworkScaleDetails()); List<CloudResource> resources = context.getStack().getResources().stream() .map(r -> cloudResourceConverter.convert(r)) .collect(Collectors.toList()); CloudStack updatedCloudStack = cloudStackConverter.convert(updatedStack); return new UpscaleStackRequest<UpscaleStackResult>(context.getCloudContext(), context.getCloudCredential(), updatedCloudStack, resources); } }; } private int getInstanceCountToCreate(Stack stack, String instanceGroupName, int adjustment) { Set<InstanceMetaData> instanceMetadata = instanceMetaDataService.unusedInstancesInInstanceGroupByName(stack.getId(), instanceGroupName); return stackScalabilityCondition.isScalable(stack, instanceGroupName) ? adjustment - instanceMetadata.size() : 0; } @Bean(name = "ADD_INSTANCES_FINISHED_STATE") public Action<?, ?> finishAddInstances() { return new AbstractStackUpscaleAction<>(UpscaleStackResult.class) { @Override protected void doExecute(StackScalingFlowContext context, UpscaleStackResult payload, Map<Object, Object> variables) { stackUpscaleService.finishAddInstances(context, payload); sendEvent(context); } @Override protected Selectable createRequest(StackScalingFlowContext context) { return new StackEvent(StackUpscaleEvent.EXTEND_METADATA_EVENT.event(), context.getStack().getId()); } }; } @Bean(name = "EXTEND_METADATA_STATE") public Action<?, ?> extendMetadata() { return new AbstractStackUpscaleAction<>(StackEvent.class) { @Override protected void doExecute(StackScalingFlowContext context, StackEvent payload, Map<Object, Object> variables) { stackUpscaleService.extendingMetadata(context.getStack()); sendEvent(context); } @Override protected Selectable createRequest(StackScalingFlowContext context) { List<CloudResource> cloudResources = context.getStack().getResources().stream() .map(r -> cloudResourceConverter.convert(r)) .collect(Collectors.toList()); List<CloudInstance> allKnownInstances = cloudStackConverter.buildInstances(context.getStack()); LOGGER.info("All known instances: {}", allKnownInstances); Set<String> unusedInstancesForGroup = instanceMetaDataService.unusedInstancesInInstanceGroupByName(context.getStack().getId(), context.getInstanceGroupName()).stream() .map(InstanceMetaData::getInstanceId) .collect(Collectors.toSet()); LOGGER.info("Unused instances for group: {}", unusedInstancesForGroup); List<CloudInstance> newCloudInstances = allKnownInstances.stream() .filter(cloudInstance -> InstanceStatus.CREATE_REQUESTED.equals(cloudInstance.getTemplate().getStatus()) || unusedInstancesForGroup.contains(cloudInstance.getInstanceId())) .collect(Collectors.toList()); return new CollectMetadataRequest(context.getCloudContext(), context.getCloudCredential(), cloudResources, newCloudInstances, allKnownInstances); } }; } @Bean(name = "EXTEND_METADATA_FINISHED_STATE") public Action<?, ?> finishExtendMetadata() { return new AbstractStackUpscaleAction<>(CollectMetadataResult.class) { @Override protected void doExecute(StackScalingFlowContext context, CollectMetadataResult payload, Map<Object, Object> variables) throws TransactionExecutionException { Set<String> upscaleCandidateAddresses = stackUpscaleService.finishExtendMetadata(context.getStack(), context.getAdjustment(), payload); variables.put(UPSCALE_CANDIDATE_ADDRESSES, upscaleCandidateAddresses); InstanceGroup ig = instanceGroupService.findOneWithInstanceMetadataByGroupNameInStack(payload.getResourceId(), context.getInstanceGroupName()) .orElseThrow(NotFoundException.notFound("instanceGroup", context.getInstanceGroupName())); if (InstanceGroupType.GATEWAY == ig.getInstanceGroupType()) { LOGGER.info("Gateway type instance group"); Stack stack = stackService.getByIdWithListsInTransaction(context.getStack().getId()); InstanceMetaData gatewayMetaData = stack.getPrimaryGatewayInstance(); if (null == gatewayMetaData) { throw new CloudbreakServiceException("Could not get gateway instance metadata from the cloud provider."); } DetailedEnvironmentResponse environment = environmentClientService.getByCrnAsInternal(stack.getEnvironmentCrn()); CloudInstance gatewayInstance = metadataConverter.convert(gatewayMetaData, environment, stack.getStackAuthentication()); LOGGER.info("Send GetSSHFingerprintsRequest because we need to collect SSH fingerprints"); Selectable sshFingerPrintReq = new GetSSHFingerprintsRequest<GetSSHFingerprintsResult>(context.getCloudContext(), context.getCloudCredential(), gatewayInstance); sendEvent(context, sshFingerPrintReq); } else { BootstrapNewNodesEvent bootstrapPayload = new BootstrapNewNodesEvent(context.getStack().getId()); sendEvent(context, StackUpscaleEvent.BOOTSTRAP_NEW_NODES_EVENT.event(), bootstrapPayload); } } }; } @Bean(name = "GATEWAY_TLS_SETUP_STATE") public Action<?, ?> tlsSetupAction() { return new AbstractStackUpscaleAction<>(GetSSHFingerprintsResult.class) { @Override protected void doExecute(StackScalingFlowContext context, GetSSHFingerprintsResult payload, Map<Object, Object> variables) throws Exception { stackUpscaleService.setupTls(context); StackEvent event = new StackEvent(payload.getResourceId()); sendEvent(context, StackCreationEvent.TLS_SETUP_FINISHED_EVENT.event(), event); } }; } @Bean(name = "RE_REGISTER_WITH_CLUSTER_PROXY_STATE") public Action<?, ?> reRegisterWithClusterProxy() { return new AbstractStackUpscaleAction<>(StackEvent.class) { @Inject private ClusterProxyEnablementService clusterProxyEnablementService; @Override protected void doExecute(StackScalingFlowContext context, StackEvent payload, Map<Object, Object> variables) { if (clusterProxyEnablementService.isClusterProxyApplicable(context.getStack().cloudPlatform())) { stackUpscaleService.reRegisterWithClusterProxy(context.getStack().getId()); sendEvent(context); } else { LOGGER.info("Cluster Proxy integration is DISABLED, skipping re-registering with Cluster Proxy service"); BootstrapNewNodesEvent bootstrapNewNodesEvent = new BootstrapNewNodesEvent(StackUpscaleEvent.CLUSTER_PROXY_RE_REGISTRATION_FINISHED_EVENT.event(), payload.getResourceId()); sendEvent(context, bootstrapNewNodesEvent); } } @Override protected Selectable createRequest(StackScalingFlowContext context) { return new ClusterProxyReRegistrationRequest(context.getStack().getId(), context.getInstanceGroupName(), context.getStack().getCloudPlatform()); } }; } @Bean(name = "BOOTSTRAP_NEW_NODES_STATE") public Action<?, ?> bootstrapNewNodes() { return new AbstractStackUpscaleAction<>(BootstrapNewNodesEvent.class) { @Override protected void doExecute(StackScalingFlowContext context, BootstrapNewNodesEvent payload, Map<Object, Object> variables) { stackUpscaleService.bootstrappingNewNodes(context.getStack()); Selectable request = new BootstrapNewNodesRequest(context.getStack().getId(), (Set<String>) variables.get(UPSCALE_CANDIDATE_ADDRESSES), context.getHostNames()); sendEvent(context, request); } }; } @Bean(name = "EXTEND_HOST_METADATA_STATE") public Action<?, ?> extendHostMetadata() { return new AbstractStackUpscaleAction<>(BootstrapNewNodesResult.class) { @Override protected void doExecute(StackScalingFlowContext context, BootstrapNewNodesResult payload, Map<Object, Object> variables) { stackUpscaleService.extendingHostMetadata(context.getStack()); Selectable request = new ExtendHostMetadataRequest(context.getStack().getId(), payload.getRequest().getUpscaleCandidateAddresses()); sendEvent(context, request); } }; } @Bean(name = "CLEANUP_FREEIPA_UPSCALE_STATE") public Action<?, ?> cleanupFreeIpaAction() { return new AbstractStackUpscaleAction<>(ExtendHostMetadataResult.class) { @Inject private InstanceMetaDataService instanceMetaDataService; @Override protected void doExecute(StackScalingFlowContext context, ExtendHostMetadataResult payload, Map<Object, Object> variables) { Set<InstanceMetaData> instanceMetaData = instanceMetaDataService.findNotTerminatedForStack(context.getStack().getId()); Set<String> ips = payload.getRequest().getUpscaleCandidateAddresses(); Set<String> hostNames = instanceMetaData.stream() .filter(im -> ips.contains(im.getPrivateIp())) .filter(im -> im.getDiscoveryFQDN() != null) .map(InstanceMetaData::getDiscoveryFQDN) .collect(Collectors.toSet()); CleanupFreeIpaEvent cleanupFreeIpaEvent = new CleanupFreeIpaEvent(context.getStack().getId(), hostNames, ips, isRepair(variables)); sendEvent(context, cleanupFreeIpaEvent); } }; } @Bean(name = "EXTEND_HOST_METADATA_FINISHED_STATE") public Action<?, ?> finishExtendHostMetadata() { return new AbstractStackUpscaleAction<>(CleanupFreeIpaEvent.class) { @Override protected void doExecute(StackScalingFlowContext context, CleanupFreeIpaEvent payload, Map<Object, Object> variables) { final Stack stack = context.getStack(); stackUpscaleService.finishExtendHostMetadata(stack); final Set<String> newAddresses = payload.getIps(); final Map<String, String> newAddressesByFqdn = stack.getNotDeletedInstanceMetaDataSet().stream() .filter(instanceMetaData -> newAddresses.contains(instanceMetaData.getPrivateIp())) .filter(instanceMetaData -> instanceMetaData.getDiscoveryFQDN() != null) .collect(Collectors.toMap(InstanceMetaData::getDiscoveryFQDN, InstanceMetaData::getPublicIpWrapper)); clusterPublicEndpointManagementService.upscale(stack, newAddressesByFqdn); getMetricService().incrementMetricCounter(MetricType.STACK_UPSCALE_SUCCESSFUL, stack); sendEvent(context); } @Override protected Selectable createRequest(StackScalingFlowContext context) { return new StackEvent(StackUpscaleEvent.UPSCALE_FINALIZED_EVENT.event(), context.getStack().getId()); } }; } @Bean(name = "UPSCALE_FAILED_STATE") public Action<?, ?> stackUpscaleFailedAction() { return new AbstractStackFailureAction<StackUpscaleState, StackUpscaleEvent>() { @Override protected void doExecute(StackFailureContext context, StackFailureEvent payload, Map<Object, Object> variables) { Set<String> hostNames = (Set<String>) variables.getOrDefault(HOSTNAMES, new HashSet<>()); String instanceGroupName = (String) variables.getOrDefault(INSTANCEGROUPNAME, null); stackUpscaleService.handleStackUpscaleFailure(isRepair(variables), hostNames, payload.getException(), payload.getResourceId(), instanceGroupName); getMetricService().incrementMetricCounter(MetricType.STACK_UPSCALE_FAILED, context.getStackView(), payload.getException()); sendEvent(context); } @Override protected Selectable createRequest(StackFailureContext context) { return new StackEvent(StackUpscaleEvent.UPSCALE_FAIL_HANDLED_EVENT.event(), context.getStackView().getId()); } }; } private boolean isRepair(Map<Object, Object> variables) { return (boolean) variables.getOrDefault(AbstractStackUpscaleAction.REPAIR, Boolean.FALSE); } }
3e08c11587639149a123b6c32b2b1612731596ad
1,714
java
Java
src/vogar/commands/CommandFailedException.java
TinkerEdgeR-Android/external_vogar
ccf18e064e312377067bdfea746ec85f8375f19a
[ "Apache-2.0" ]
1
2017-05-02T12:24:23.000Z
2017-05-02T12:24:23.000Z
src/vogar/commands/CommandFailedException.java
TinkerEdgeR-Android/external_vogar
ccf18e064e312377067bdfea746ec85f8375f19a
[ "Apache-2.0" ]
null
null
null
src/vogar/commands/CommandFailedException.java
TinkerEdgeR-Android/external_vogar
ccf18e064e312377067bdfea746ec85f8375f19a
[ "Apache-2.0" ]
null
null
null
30.070175
85
0.676779
3,707
/* * Copyright (C) 2009 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 vogar.commands; import java.util.List; /** * Thrown when an out of process executable does not return normally. */ public class CommandFailedException extends RuntimeException { private final List<String> args; private final List<String> outputLines; public CommandFailedException(List<String> args, List<String> outputLines) { super(formatMessage(args, outputLines)); this.args = args; this.outputLines = outputLines; } public List<String> getArgs() { return args; } public List<String> getOutputLines() { return outputLines; } public static String formatMessage(List<String> args, List<String> outputLines) { StringBuilder result = new StringBuilder(); result.append("Command failed:"); for (String arg : args) { result.append(" ").append(arg); } for (String outputLine : outputLines) { result.append("\n ").append(outputLine); } return result.toString(); } private static final long serialVersionUID = 0; }
3e08c120f6eaa32dba6b8ad0cb9a32edb3cd1d51
13,535
java
Java
model-sese-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/SettlementDetails147.java
luongnvUIT/prowide-iso20022
59210a4b67cd38759df2d0dd82ad19acf93ffe75
[ "Apache-2.0" ]
40
2020-10-13T13:44:59.000Z
2022-03-30T13:58:32.000Z
model-sese-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/SettlementDetails147.java
luongnvUIT/prowide-iso20022
59210a4b67cd38759df2d0dd82ad19acf93ffe75
[ "Apache-2.0" ]
25
2020-10-04T23:46:22.000Z
2022-03-30T12:31:03.000Z
model-sese-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/SettlementDetails147.java
luongnvUIT/prowide-iso20022
59210a4b67cd38759df2d0dd82ad19acf93ffe75
[ "Apache-2.0" ]
22
2020-12-22T14:50:22.000Z
2022-03-30T13:19:10.000Z
25.251866
100
0.606132
3,708
package com.prowidesoftware.swift.model.mx.dic; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * Details of settlement of a transaction. * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SettlementDetails147", propOrder = { "prty", "sttlmTxCond", "sttlgCpcty", "stmpDtyTaxBsis", "sctiesRTGS", "bnfclOwnrsh", "cshClrSys", "taxCpcty", "mktClntSd", "blckTrad", "lglRstrctns", "sttlmSysMtd", "netgElgblty", "ccpElgblty", "automtcBrrwg", "prtlSttlmInd", "elgblForColl" }) public class SettlementDetails147 { @XmlElement(name = "Prty") protected PriorityNumeric4Choice prty; @XmlElement(name = "SttlmTxCond") protected List<SettlementTransactionCondition18Choice> sttlmTxCond; @XmlElement(name = "SttlgCpcty") protected SettlingCapacity7Choice sttlgCpcty; @XmlElement(name = "StmpDtyTaxBsis") protected GenericIdentification30 stmpDtyTaxBsis; @XmlElement(name = "SctiesRTGS") protected SecuritiesRTGS4Choice sctiesRTGS; @XmlElement(name = "BnfclOwnrsh") protected BeneficialOwnership4Choice bnfclOwnrsh; @XmlElement(name = "CshClrSys") protected CashSettlementSystem4Choice cshClrSys; @XmlElement(name = "TaxCpcty") protected TaxCapacityParty4Choice taxCpcty; @XmlElement(name = "MktClntSd") protected MarketClientSide6Choice mktClntSd; @XmlElement(name = "BlckTrad") protected BlockTrade4Choice blckTrad; @XmlElement(name = "LglRstrctns") protected Restriction5Choice lglRstrctns; @XmlElement(name = "SttlmSysMtd") protected SettlementSystemMethod4Choice sttlmSysMtd; @XmlElement(name = "NetgElgblty") protected NettingEligibility4Choice netgElgblty; @XmlElement(name = "CCPElgblty") protected CentralCounterPartyEligibility4Choice ccpElgblty; @XmlElement(name = "AutomtcBrrwg") protected AutomaticBorrowing6Choice automtcBrrwg; @XmlElement(name = "PrtlSttlmInd") @XmlSchemaType(name = "string") protected SettlementTransactionCondition5Code prtlSttlmInd; @XmlElement(name = "ElgblForColl") protected Boolean elgblForColl; /** * Gets the value of the prty property. * * @return * possible object is * {@link PriorityNumeric4Choice } * */ public PriorityNumeric4Choice getPrty() { return prty; } /** * Sets the value of the prty property. * * @param value * allowed object is * {@link PriorityNumeric4Choice } * */ public SettlementDetails147 setPrty(PriorityNumeric4Choice value) { this.prty = value; return this; } /** * Gets the value of the sttlmTxCond property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the sttlmTxCond property. * * <p> * For example, to add a new item, do as follows: * <pre> * getSttlmTxCond().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link SettlementTransactionCondition18Choice } * * */ public List<SettlementTransactionCondition18Choice> getSttlmTxCond() { if (sttlmTxCond == null) { sttlmTxCond = new ArrayList<SettlementTransactionCondition18Choice>(); } return this.sttlmTxCond; } /** * Gets the value of the sttlgCpcty property. * * @return * possible object is * {@link SettlingCapacity7Choice } * */ public SettlingCapacity7Choice getSttlgCpcty() { return sttlgCpcty; } /** * Sets the value of the sttlgCpcty property. * * @param value * allowed object is * {@link SettlingCapacity7Choice } * */ public SettlementDetails147 setSttlgCpcty(SettlingCapacity7Choice value) { this.sttlgCpcty = value; return this; } /** * Gets the value of the stmpDtyTaxBsis property. * * @return * possible object is * {@link GenericIdentification30 } * */ public GenericIdentification30 getStmpDtyTaxBsis() { return stmpDtyTaxBsis; } /** * Sets the value of the stmpDtyTaxBsis property. * * @param value * allowed object is * {@link GenericIdentification30 } * */ public SettlementDetails147 setStmpDtyTaxBsis(GenericIdentification30 value) { this.stmpDtyTaxBsis = value; return this; } /** * Gets the value of the sctiesRTGS property. * * @return * possible object is * {@link SecuritiesRTGS4Choice } * */ public SecuritiesRTGS4Choice getSctiesRTGS() { return sctiesRTGS; } /** * Sets the value of the sctiesRTGS property. * * @param value * allowed object is * {@link SecuritiesRTGS4Choice } * */ public SettlementDetails147 setSctiesRTGS(SecuritiesRTGS4Choice value) { this.sctiesRTGS = value; return this; } /** * Gets the value of the bnfclOwnrsh property. * * @return * possible object is * {@link BeneficialOwnership4Choice } * */ public BeneficialOwnership4Choice getBnfclOwnrsh() { return bnfclOwnrsh; } /** * Sets the value of the bnfclOwnrsh property. * * @param value * allowed object is * {@link BeneficialOwnership4Choice } * */ public SettlementDetails147 setBnfclOwnrsh(BeneficialOwnership4Choice value) { this.bnfclOwnrsh = value; return this; } /** * Gets the value of the cshClrSys property. * * @return * possible object is * {@link CashSettlementSystem4Choice } * */ public CashSettlementSystem4Choice getCshClrSys() { return cshClrSys; } /** * Sets the value of the cshClrSys property. * * @param value * allowed object is * {@link CashSettlementSystem4Choice } * */ public SettlementDetails147 setCshClrSys(CashSettlementSystem4Choice value) { this.cshClrSys = value; return this; } /** * Gets the value of the taxCpcty property. * * @return * possible object is * {@link TaxCapacityParty4Choice } * */ public TaxCapacityParty4Choice getTaxCpcty() { return taxCpcty; } /** * Sets the value of the taxCpcty property. * * @param value * allowed object is * {@link TaxCapacityParty4Choice } * */ public SettlementDetails147 setTaxCpcty(TaxCapacityParty4Choice value) { this.taxCpcty = value; return this; } /** * Gets the value of the mktClntSd property. * * @return * possible object is * {@link MarketClientSide6Choice } * */ public MarketClientSide6Choice getMktClntSd() { return mktClntSd; } /** * Sets the value of the mktClntSd property. * * @param value * allowed object is * {@link MarketClientSide6Choice } * */ public SettlementDetails147 setMktClntSd(MarketClientSide6Choice value) { this.mktClntSd = value; return this; } /** * Gets the value of the blckTrad property. * * @return * possible object is * {@link BlockTrade4Choice } * */ public BlockTrade4Choice getBlckTrad() { return blckTrad; } /** * Sets the value of the blckTrad property. * * @param value * allowed object is * {@link BlockTrade4Choice } * */ public SettlementDetails147 setBlckTrad(BlockTrade4Choice value) { this.blckTrad = value; return this; } /** * Gets the value of the lglRstrctns property. * * @return * possible object is * {@link Restriction5Choice } * */ public Restriction5Choice getLglRstrctns() { return lglRstrctns; } /** * Sets the value of the lglRstrctns property. * * @param value * allowed object is * {@link Restriction5Choice } * */ public SettlementDetails147 setLglRstrctns(Restriction5Choice value) { this.lglRstrctns = value; return this; } /** * Gets the value of the sttlmSysMtd property. * * @return * possible object is * {@link SettlementSystemMethod4Choice } * */ public SettlementSystemMethod4Choice getSttlmSysMtd() { return sttlmSysMtd; } /** * Sets the value of the sttlmSysMtd property. * * @param value * allowed object is * {@link SettlementSystemMethod4Choice } * */ public SettlementDetails147 setSttlmSysMtd(SettlementSystemMethod4Choice value) { this.sttlmSysMtd = value; return this; } /** * Gets the value of the netgElgblty property. * * @return * possible object is * {@link NettingEligibility4Choice } * */ public NettingEligibility4Choice getNetgElgblty() { return netgElgblty; } /** * Sets the value of the netgElgblty property. * * @param value * allowed object is * {@link NettingEligibility4Choice } * */ public SettlementDetails147 setNetgElgblty(NettingEligibility4Choice value) { this.netgElgblty = value; return this; } /** * Gets the value of the ccpElgblty property. * * @return * possible object is * {@link CentralCounterPartyEligibility4Choice } * */ public CentralCounterPartyEligibility4Choice getCCPElgblty() { return ccpElgblty; } /** * Sets the value of the ccpElgblty property. * * @param value * allowed object is * {@link CentralCounterPartyEligibility4Choice } * */ public SettlementDetails147 setCCPElgblty(CentralCounterPartyEligibility4Choice value) { this.ccpElgblty = value; return this; } /** * Gets the value of the automtcBrrwg property. * * @return * possible object is * {@link AutomaticBorrowing6Choice } * */ public AutomaticBorrowing6Choice getAutomtcBrrwg() { return automtcBrrwg; } /** * Sets the value of the automtcBrrwg property. * * @param value * allowed object is * {@link AutomaticBorrowing6Choice } * */ public SettlementDetails147 setAutomtcBrrwg(AutomaticBorrowing6Choice value) { this.automtcBrrwg = value; return this; } /** * Gets the value of the prtlSttlmInd property. * * @return * possible object is * {@link SettlementTransactionCondition5Code } * */ public SettlementTransactionCondition5Code getPrtlSttlmInd() { return prtlSttlmInd; } /** * Sets the value of the prtlSttlmInd property. * * @param value * allowed object is * {@link SettlementTransactionCondition5Code } * */ public SettlementDetails147 setPrtlSttlmInd(SettlementTransactionCondition5Code value) { this.prtlSttlmInd = value; return this; } /** * Gets the value of the elgblForColl property. * * @return * possible object is * {@link Boolean } * */ public Boolean isElgblForColl() { return elgblForColl; } /** * Sets the value of the elgblForColl property. * * @param value * allowed object is * {@link Boolean } * */ public SettlementDetails147 setElgblForColl(Boolean value) { this.elgblForColl = value; return this; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } @Override public boolean equals(Object that) { return EqualsBuilder.reflectionEquals(this, that); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } /** * Adds a new item to the sttlmTxCond list. * @see #getSttlmTxCond() * */ public SettlementDetails147 addSttlmTxCond(SettlementTransactionCondition18Choice sttlmTxCond) { getSttlmTxCond().add(sttlmTxCond); return this; } }
3e08c1c6f8faf422111803068130bea6d744e656
4,665
java
Java
services/self-service/src/main/java/com/epam/dlab/backendapi/resources/SchedulerJobResource.java
ofuks/DLab
460804a2559843d099936fe40373093f9bf9edcb
[ "Apache-2.0" ]
null
null
null
services/self-service/src/main/java/com/epam/dlab/backendapi/resources/SchedulerJobResource.java
ofuks/DLab
460804a2559843d099936fe40373093f9bf9edcb
[ "Apache-2.0" ]
null
null
null
services/self-service/src/main/java/com/epam/dlab/backendapi/resources/SchedulerJobResource.java
ofuks/DLab
460804a2559843d099936fe40373093f9bf9edcb
[ "Apache-2.0" ]
null
null
null
36.445313
111
0.741479
3,709
/* * Copyright (c) 2018, EPAM SYSTEMS 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.epam.dlab.backendapi.resources; import com.epam.dlab.auth.UserInfo; import com.epam.dlab.backendapi.service.SchedulerJobService; import com.epam.dlab.dto.SchedulerJobDTO; import com.google.inject.Inject; import io.dropwizard.auth.Auth; import lombok.extern.slf4j.Slf4j; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * Manages scheduler jobs for exploratory environment */ @Path("/infrastructure_provision/exploratory_environment/scheduler") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Slf4j public class SchedulerJobResource { private SchedulerJobService schedulerJobService; @Inject public SchedulerJobResource(SchedulerJobService schedulerJobService) { this.schedulerJobService = schedulerJobService; } /** * Updates exploratory <code>exploratoryName<code/> for user <code>userInfo<code/> with new scheduler job data * * @param userInfo user info * @param exploratoryName name of exploratory resource * @param dto scheduler job data * @return response */ @POST @Path("/{exploratoryName}") public Response updateExploratoryScheduler(@Auth UserInfo userInfo, @PathParam("exploratoryName") String exploratoryName, SchedulerJobDTO dto) { schedulerJobService.updateExploratorySchedulerData(userInfo.getName(), exploratoryName, dto); return Response.ok().build(); } /** * Updates computational resource <code>computationalName<code/> affiliated with exploratory * <code>exploratoryName<code/> for user <code>userInfo<code/> with new scheduler job data * * @param userInfo user info * @param exploratoryName name of exploratory resource * @param computationalName name of computational resource * @param dto scheduler job data * @return response */ @POST @Path("/{exploratoryName}/{computationalName}") public Response upsertComputationalScheduler(@Auth UserInfo userInfo, @PathParam("exploratoryName") String exploratoryName, @PathParam("computationalName") String computationalName, SchedulerJobDTO dto) { schedulerJobService.updateComputationalSchedulerData(userInfo.getName(), exploratoryName, computationalName, dto); return Response.ok().build(); } /** * Returns scheduler job for exploratory resource <code>exploratoryName<code/> * * @param userInfo user info * @param exploratoryName name of exploratory resource * @return scheduler job data */ @GET @Path("/{exploratoryName}") public Response fetchSchedulerJobForUserAndExploratory(@Auth UserInfo userInfo, @PathParam("exploratoryName") String exploratoryName) { log.debug("Loading scheduler job for user {} and exploratory {}...", userInfo.getName(), exploratoryName); final SchedulerJobDTO schedulerJob = schedulerJobService.fetchSchedulerJobForUserAndExploratory(userInfo.getName(), exploratoryName); return Response.ok(schedulerJob).build(); } /** * Returns scheduler job for computational resource <code>computationalName<code/> affiliated with * exploratory <code>exploratoryName<code/> * * @param userInfo user info * @param exploratoryName name of exploratory resource * @param computationalName name of computational resource * @return scheduler job data */ @GET @Path("/{exploratoryName}/{computationalName}") public Response fetchSchedulerJobForComputationalResource(@Auth UserInfo userInfo, @PathParam("exploratoryName") String exploratoryName, @PathParam("computationalName") String computationalName) { log.debug("Loading scheduler job for user {}, exploratory {} and computational resource {}...", userInfo.getName(), exploratoryName, computationalName); final SchedulerJobDTO schedulerJob = schedulerJobService .fetchSchedulerJobForComputationalResource(userInfo.getName(), exploratoryName, computationalName); return Response.ok(schedulerJob).build(); } }
3e08c3ac3397f4c10908079b422dbc410acb72f5
3,168
java
Java
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services-api/src/test/java/org/apache/hadoop/yarn/service/ServiceClientTest.java
genSud/hadoop
727c033997990b4c76382ea7bb98f41695da591e
[ "Apache-2.0" ]
14
2016-10-11T08:28:13.000Z
2017-11-08T08:11:06.000Z
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services-api/src/test/java/org/apache/hadoop/yarn/service/ServiceClientTest.java
genSud/hadoop
727c033997990b4c76382ea7bb98f41695da591e
[ "Apache-2.0" ]
null
null
null
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services-api/src/test/java/org/apache/hadoop/yarn/service/ServiceClientTest.java
genSud/hadoop
727c033997990b4c76382ea7bb98f41695da591e
[ "Apache-2.0" ]
1
2019-05-17T02:24:34.000Z
2019-05-17T02:24:34.000Z
29.333333
75
0.717487
3,710
/* * 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.hadoop.yarn.service; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.exceptions.ApplicationNotFoundException; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.service.api.records.Service; import org.apache.hadoop.yarn.service.client.ServiceClient; import org.apache.hadoop.yarn.service.utils.ServiceApiUtil; /** * A mock version of ServiceClient - This class is design * to simulate various error conditions that will happen * when a consumer class calls ServiceClient. */ public class ServiceClientTest extends ServiceClient { private Configuration conf = new Configuration(); protected static void init() { } public ServiceClientTest() { super(); } @Override public Configuration getConfig() { return conf; } @Override public ApplicationId actionCreate(Service service) { String serviceName = service.getName(); ServiceApiUtil.validateNameFormat(serviceName, getConfig()); return ApplicationId.newInstance(System.currentTimeMillis(), 1); } @Override public Service getStatus(String appName) { if (appName == null) { throw new NullPointerException(); } if (appName.equals("jenkins")) { return new Service(); } else { throw new IllegalArgumentException(); } } @Override public int actionStart(String serviceName) throws YarnException, IOException { if (serviceName == null) { throw new NullPointerException(); } if (serviceName.equals("jenkins")) { return EXIT_SUCCESS; } else { throw new ApplicationNotFoundException(""); } } @Override public int actionStop(String serviceName, boolean waitForAppStopped) throws YarnException, IOException { if (serviceName == null) { throw new NullPointerException(); } if (serviceName.equals("jenkins")) { return EXIT_SUCCESS; } else { throw new ApplicationNotFoundException(""); } } @Override public int actionDestroy(String serviceName) { if (serviceName == null) { throw new NullPointerException(); } if (serviceName.equals("jenkins")) { return EXIT_SUCCESS; } else { throw new IllegalArgumentException(); } } }
3e08c3c5487f49504a6d2a31fd9597b12540d613
366
java
Java
src/main/java/io/crowdcode/jopt/joptbay/exceptions/BidTooLowException.java
crowdcode-de/joptbay
3c05ad40fa09371d1c8e0757f949f52c13bc6fc2
[ "Apache-2.0" ]
1
2019-11-24T14:20:30.000Z
2019-11-24T14:20:30.000Z
src/main/java/io/crowdcode/jopt/joptbay/exceptions/BidTooLowException.java
crowdcode-de/joptbay
3c05ad40fa09371d1c8e0757f949f52c13bc6fc2
[ "Apache-2.0" ]
null
null
null
src/main/java/io/crowdcode/jopt/joptbay/exceptions/BidTooLowException.java
crowdcode-de/joptbay
3c05ad40fa09371d1c8e0757f949f52c13bc6fc2
[ "Apache-2.0" ]
1
2020-04-27T15:29:27.000Z
2020-04-27T15:29:27.000Z
22.875
62
0.759563
3,711
package io.crowdcode.jopt.joptbay.exceptions; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; /** * @author Ingo Dueppe (CROWDCODE) */ @ResponseStatus(HttpStatus.NOT_ACCEPTABLE) public class BidTooLowException extends Exception { public BidTooLowException() { super("bid too low"); } }
3e08c3fc33f8ec5869a305ef2c392e3c1af2c1a1
9,358
java
Java
service/src/test/java/org/eclipse/keti/controller/test/HierarchicalResourcesIT.java
eclipse/keti
a1c8dbeba85235fc7dd23619316ed7e500bc0b14
[ "Apache-2.0" ]
23
2017-05-30T17:37:50.000Z
2021-08-17T05:51:10.000Z
service/src/test/java/org/eclipse/keti/controller/test/HierarchicalResourcesIT.java
eclipse/keti
a1c8dbeba85235fc7dd23619316ed7e500bc0b14
[ "Apache-2.0" ]
23
2018-01-14T17:54:19.000Z
2022-02-26T00:46:32.000Z
service/src/test/java/org/eclipse/keti/controller/test/HierarchicalResourcesIT.java
eclipse/keti
a1c8dbeba85235fc7dd23619316ed7e500bc0b14
[ "Apache-2.0" ]
14
2017-12-12T18:28:44.000Z
2021-03-19T11:41:36.000Z
55.047059
115
0.700898
3,712
/******************************************************************************* * Copyright 2018 General Electric Company * * 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. * * SPDX-License-Identifier: Apache-2.0 *******************************************************************************/ package org.eclipse.keti.controller.test; import org.eclipse.keti.acs.rest.BaseResource; import org.eclipse.keti.acs.rest.Zone; import org.eclipse.keti.acs.testutils.MockAcsRequestContext; import org.eclipse.keti.acs.testutils.MockMvcContext; import org.eclipse.keti.acs.testutils.MockSecurityContext; import org.eclipse.keti.acs.testutils.TestActiveProfilesResolver; import org.eclipse.keti.acs.zone.management.ZoneService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.web.context.WebApplicationContext; import org.testng.SkipException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.net.URLEncoder; import java.util.Arrays; import java.util.List; import static org.eclipse.keti.acs.testutils.XFiles.ASCENSION_ID; import static org.eclipse.keti.acs.testutils.XFiles.BASEMENT_SITE_ID; import static org.eclipse.keti.acs.testutils.XFiles.EVIDENCE_SCULLYS_TESTIMONY_ID; import static org.eclipse.keti.acs.testutils.XFiles.SITE_BASEMENT; import static org.eclipse.keti.acs.testutils.XFiles.SPECIAL_AGENTS_GROUP_ATTRIBUTE; import static org.eclipse.keti.acs.testutils.XFiles.TOP_SECRET_CLASSIFICATION; import static org.eclipse.keti.acs.testutils.XFiles.TYPE_MYTHARC; import static org.eclipse.keti.acs.testutils.XFiles.createThreeLevelResourceHierarchy; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @WebAppConfiguration @ContextConfiguration("classpath:controller-tests-context.xml") @ActiveProfiles(resolver = TestActiveProfilesResolver.class) public class HierarchicalResourcesIT extends AbstractTestNGSpringContextTests { private static final Zone TEST_ZONE = ResourcePrivilegeManagementControllerIT.TEST_UTILS.createTestZone("ResourceMgmtControllerIT"); @Autowired private ZoneService zoneService; @Autowired private WebApplicationContext wac; @Autowired private ConfigurableEnvironment configurableEnvironment; @BeforeClass public void beforeClass() throws Exception { if (!Arrays.asList(this.configurableEnvironment.getActiveProfiles()).contains("graph")) { throw new SkipException("This test only applies when using the \"graph\" profile"); } this.zoneService.upsertZone(TEST_ZONE); MockSecurityContext.mockSecurityContext(TEST_ZONE); MockAcsRequestContext.mockAcsRequestContext(); } @Test public void testPostAndGetHierarchicalResources() throws Exception { List<BaseResource> resources = createThreeLevelResourceHierarchy(); // Append a list of resources MockMvcContext postContext = ResourcePrivilegeManagementControllerIT.TEST_UTILS.createWACWithCustomPOSTRequestBuilder( this.wac, TEST_ZONE.getSubdomain(), ResourcePrivilegeManagementControllerIT.RESOURCE_BASE_URL); postContext.getMockMvc().perform(postContext.getBuilder().contentType(MediaType.APPLICATION_JSON) .content(ResourcePrivilegeManagementControllerIT.OBJECT_MAPPER .writeValueAsString(resources))) .andExpect(status().isNoContent()); // Get the child resource without query string specifier. MockMvcContext getContext0 = ResourcePrivilegeManagementControllerIT.TEST_UTILS.createWACWithCustomGETRequestBuilder( this.wac, TEST_ZONE.getSubdomain(), ResourcePrivilegeManagementControllerIT.RESOURCE_BASE_URL + "/" + URLEncoder.encode(EVIDENCE_SCULLYS_TESTIMONY_ID, "UTF-8")); getContext0.getMockMvc().perform(getContext0.getBuilder()).andExpect(status().isOk()) .andExpect(jsonPath("resourceIdentifier", is(EVIDENCE_SCULLYS_TESTIMONY_ID))) .andExpect(jsonPath("attributes[0].name", is(TOP_SECRET_CLASSIFICATION.getName()))) .andExpect(jsonPath("attributes[0].value", is(TOP_SECRET_CLASSIFICATION.getValue()))) .andExpect(jsonPath("attributes[0].issuer", is(TOP_SECRET_CLASSIFICATION.getIssuer()))) .andExpect(jsonPath("attributes[1]").doesNotExist()); // Get the child resource without inherited attributes. MockMvcContext getContext1 = ResourcePrivilegeManagementControllerIT.TEST_UTILS.createWACWithCustomGETRequestBuilder( this.wac, TEST_ZONE.getSubdomain(), ResourcePrivilegeManagementControllerIT.RESOURCE_BASE_URL + "/" + URLEncoder.encode(EVIDENCE_SCULLYS_TESTIMONY_ID, "UTF-8") + "?includeInheritedAttributes=false"); getContext1.getMockMvc().perform(getContext1.getBuilder()).andExpect(status().isOk()) .andExpect(jsonPath("resourceIdentifier", is(EVIDENCE_SCULLYS_TESTIMONY_ID))) .andExpect(jsonPath("attributes[0].name", is(TOP_SECRET_CLASSIFICATION.getName()))) .andExpect(jsonPath("attributes[0].value", is(TOP_SECRET_CLASSIFICATION.getValue()))) .andExpect(jsonPath("attributes[0].issuer", is(TOP_SECRET_CLASSIFICATION.getIssuer()))) .andExpect(jsonPath("attributes[1]").doesNotExist()); // Get the child resource with inherited attributes. MockMvcContext getContext2 = ResourcePrivilegeManagementControllerIT.TEST_UTILS.createWACWithCustomGETRequestBuilder( this.wac, TEST_ZONE.getSubdomain(), ResourcePrivilegeManagementControllerIT.RESOURCE_BASE_URL + "/" + URLEncoder.encode(EVIDENCE_SCULLYS_TESTIMONY_ID, "UTF-8") + "?includeInheritedAttributes=true"); getContext2.getMockMvc().perform(getContext2.getBuilder()).andExpect(status().isOk()) .andExpect(jsonPath("resourceIdentifier", is(EVIDENCE_SCULLYS_TESTIMONY_ID))) .andExpect(jsonPath("attributes[0].name", is(TOP_SECRET_CLASSIFICATION.getName()))) .andExpect(jsonPath("attributes[0].value", is(TOP_SECRET_CLASSIFICATION.getValue()))) .andExpect(jsonPath("attributes[0].issuer", is(TOP_SECRET_CLASSIFICATION.getIssuer()))) .andExpect(jsonPath("attributes[1].name", is(SPECIAL_AGENTS_GROUP_ATTRIBUTE.getName()))) .andExpect(jsonPath("attributes[1].value", is(SPECIAL_AGENTS_GROUP_ATTRIBUTE.getValue()))) .andExpect(jsonPath("attributes[1].issuer", is(SPECIAL_AGENTS_GROUP_ATTRIBUTE.getIssuer()))) .andExpect(jsonPath("attributes[2].name", is(TYPE_MYTHARC.getName()))) .andExpect(jsonPath("attributes[2].value", is(TYPE_MYTHARC.getValue()))) .andExpect(jsonPath("attributes[2].issuer", is(TYPE_MYTHARC.getIssuer()))) .andExpect(jsonPath("attributes[3].name", is(SITE_BASEMENT.getName()))) .andExpect(jsonPath("attributes[3].value", is(SITE_BASEMENT.getValue()))) .andExpect(jsonPath("attributes[3].issuer", is(SITE_BASEMENT.getIssuer()))); // Clean up after ourselves. deleteResource(EVIDENCE_SCULLYS_TESTIMONY_ID); deleteResource(ASCENSION_ID); deleteResource(BASEMENT_SITE_ID); } private void deleteResource(final String resourceIdentifier) throws Exception { String resourceToDeleteURI = ResourcePrivilegeManagementControllerIT.RESOURCE_BASE_URL + "/" + URLEncoder.encode(resourceIdentifier, "UTF-8"); MockMvcContext deleteContext = ResourcePrivilegeManagementControllerIT.TEST_UTILS.createWACWithCustomDELETERequestBuilder( this.wac, TEST_ZONE.getSubdomain(), resourceToDeleteURI); deleteContext.getMockMvc().perform(deleteContext.getBuilder()).andExpect(status().isNoContent()); } }
3e08c4a375348f6086072184db47f60d28fdb11e
764
java
Java
app/src/main/java/com/koma/filemanager/fileview/FileViewContract.java
komamj/FileManager
4d33663d9a215db54806929752ef7d9896b85e9d
[ "Apache-2.0" ]
15
2016-11-28T09:06:47.000Z
2021-06-04T21:37:18.000Z
app/src/main/java/com/koma/filemanager/fileview/FileViewContract.java
komamj/FileManager
4d33663d9a215db54806929752ef7d9896b85e9d
[ "Apache-2.0" ]
1
2017-09-29T13:22:26.000Z
2017-09-29T13:22:26.000Z
app/src/main/java/com/koma/filemanager/fileview/FileViewContract.java
komamj/FileManager
4d33663d9a215db54806929752ef7d9896b85e9d
[ "Apache-2.0" ]
4
2016-12-24T08:33:35.000Z
2021-09-16T07:24:02.000Z
21.828571
71
0.705497
3,713
package com.koma.filemanager.fileview; import com.koma.filemanager.base.BaseFile; import com.koma.filemanager.base.BasePresenter; import com.koma.filemanager.base.BaseView; import com.koma.filemanager.helper.event.SortEvent; import java.util.ArrayList; /** * Created by koma on 12/1/16. */ public interface FileViewContract { interface View extends BaseView<Presenter> { void refreshAdapter(ArrayList<BaseFile> files); void showLoadingView(); void hideLoadingView(); void showEmptyView(); String getPath(); void onSortSuccess(); } interface Presenter extends BasePresenter { void getFiles(String path); void sortFiles(ArrayList<BaseFile> files, SortEvent sortEvent); } }
3e08c4ae172e68eeee2ec9c2fee1cdb492726903
24,526
java
Java
ole-docstore/ole-docstore-engine/src/main/java/org/kuali/ole/docstore/service/IngestNIndexHandlerService.java
VU-libtech/OLE-INST
9f5efae4dfaf810fa671c6ac6670a6051303b43d
[ "ECL-2.0" ]
1
2017-01-26T03:50:56.000Z
2017-01-26T03:50:56.000Z
ole-docstore/ole-docstore-engine/src/main/java/org/kuali/ole/docstore/service/IngestNIndexHandlerService.java
VU-libtech/OLE-INST
9f5efae4dfaf810fa671c6ac6670a6051303b43d
[ "ECL-2.0" ]
3
2020-11-16T20:28:08.000Z
2021-03-22T23:41:19.000Z
ole-docstore/ole-docstore-engine/src/main/java/org/kuali/ole/docstore/service/IngestNIndexHandlerService.java
VU-libtech/OLE-INST
9f5efae4dfaf810fa671c6ac6670a6051303b43d
[ "ECL-2.0" ]
null
null
null
51.852008
147
0.597651
3,714
/* * Copyright 2011 The Kuali Foundation. * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.ole.docstore.service; import org.apache.commons.lang.time.StopWatch; import org.kuali.ole.RepositoryManager; import org.kuali.ole.docstore.common.document.content.instance.Instance; import org.kuali.ole.docstore.common.document.content.instance.InstanceCollection; import org.kuali.ole.docstore.common.document.content.instance.Item; import org.kuali.ole.docstore.model.enums.DocCategory; import org.kuali.ole.docstore.model.enums.DocFormat; import org.kuali.ole.docstore.model.enums.DocType; import org.kuali.ole.docstore.model.xmlpojo.ingest.Request; import org.kuali.ole.docstore.model.xmlpojo.ingest.RequestDocument; import org.kuali.ole.docstore.model.xmlpojo.ingest.Response; import org.kuali.ole.docstore.model.xmlpojo.ingest.ResponseDocument; import org.kuali.ole.docstore.model.xstream.ingest.RequestHandler; import org.kuali.ole.docstore.model.xstream.ingest.ResponseHandler; import org.kuali.ole.docstore.process.BulkIngestTimeManager; import org.kuali.ole.docstore.process.ProcessParameters; import org.kuali.ole.docstore.utility.BatchIngestStatistics; import org.kuali.ole.docstore.utility.BulkIngestStatistics; import org.kuali.ole.pojo.OleException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Required; import javax.jcr.Session; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Class to IngestNIndexHandlerService. * * @author Rajesh Chowdary K * @created Feb 15, 2012 * <p/> * Singleton instance of this class is created by Spring. */ public class IngestNIndexHandlerService { private static Logger logger = LoggerFactory.getLogger(IngestNIndexHandlerService.class); /** * Singleton instance of RequestHandler initialized by Spring DI. */ private RequestHandler requestHandler; /** * Singleton instance of DocumentIngester initialized by Spring DI. */ private DocumentIngester documentIngester; /** * Singleton instance of DocumentIndexer initialized by Spring DI. */ private DocumentIndexer documentIndexer; private static long docCount = 0; private BulkIngestStatistics bulkLoadStatistics = BulkIngestStatistics.getInstance(); private static List<RequestDocument> prevRequestDocs = null; private RepositoryManager repositoryManager; @Required public void setDocumentIngester(DocumentIngester documentIngester) { this.documentIngester = documentIngester; } @Required public void setDocumentIndexer(DocumentIndexer documentIndexer) { this.documentIndexer = documentIndexer; } @Required public void setRequestHandler(RequestHandler requestHandler) { this.requestHandler = requestHandler; } /** * Method to ingest & index xml String Request Document * * @param xmlRequestString * @return * @throws Exception */ public String ingestNIndexRequestDocuments(String xmlRequestString) throws Exception { Request request = null; request = requestHandler.toObject(xmlRequestString); Response response = ingestNIndexRequestDocuments(request); String xmlResponse = new ResponseHandler().toXML(response); return xmlResponse; } /** * ` * <p/> * Method to ingest & index xml String Request Document * * @param request * @return * @throws Exception */ public Response ingestNIndexRequestDocuments(Request request) throws Exception { for (RequestDocument doc : request.getRequestDocuments()) { doc.setUser(request.getUser()); } Session session = null; List<String> docUUIDs = new ArrayList<String>(); try { session = getRepositoryManager().getSession(request.getUser(), request.getOperation()); // Ingest & check for any unsupported Category/Type/Formats for (RequestDocument reqDoc : request.getRequestDocuments()) { if (DocCategory.WORK.isEqualTo(reqDoc.getCategory())) { if (DocType.BIB.isEqualTo(reqDoc.getType())) { // Biblographic if (DocFormat.MARC.isEqualTo(reqDoc.getFormat()) || DocFormat.DUBLIN_CORE.isEqualTo(reqDoc.getFormat()) || DocFormat.DUBLIN_UNQUALIFIED .isEqualTo(reqDoc.getFormat())) { docUUIDs.addAll(documentIngester.ingestBibNLinkedInstanceRequestDocuments(reqDoc, session)); documentIndexer.indexDocument(reqDoc); } else { logger.error("Unsupported Document Format : " + reqDoc.getFormat() + " Called."); throw new Exception("Unsupported Document Format : " + reqDoc.getFormat() + " Called."); } } else if (DocType.INSTANCE.isEqualTo(reqDoc.getType())) { // Instace if (DocFormat.OLEML.isEqualTo(reqDoc.getFormat())) { // OLE-ML documentIngester.ingestInstanceDocument(reqDoc, session, docUUIDs, null, null); documentIndexer.indexDocument(reqDoc); } else { logger.error("Unsupported Document Format : " + reqDoc.getFormat() + " Called."); throw new Exception("Unsupported Document Format : " + reqDoc.getFormat() + " Called."); } } else if (DocType.LICENSE.isEqualTo(reqDoc.getType())) { // License if (DocFormat.ONIXPL.isEqualTo(reqDoc.getFormat()) || DocFormat.PDF.isEqualTo(reqDoc.getFormat()) || DocFormat.DOC.isEqualTo(reqDoc.getFormat()) || DocFormat.XSLT .isEqualTo(reqDoc.getFormat())) { //Onixpl, pdf, doc, xslt. documentIngester.ingestWorkLicenseOnixplRequestDocument(reqDoc, session, docUUIDs); documentIndexer.indexDocument(reqDoc); } else { logger.error("Unsupported Document Format : " + reqDoc.getFormat() + " Called."); throw new Exception("Unsupported Document Format : " + reqDoc.getFormat() + " Called."); } } else { logger.error("Unsupported Document Type : " + reqDoc.getType() + " Called."); throw new Exception("Unsupported Document Type : " + reqDoc.getType() + " Called."); } } else if (DocCategory.SECURITY.isEqualTo(reqDoc.getCategory())) { // Security if (DocType.PATRON.isEqualTo(reqDoc.getType())) { // Patron if (DocFormat.OLEML.isEqualTo(reqDoc.getFormat())) { // oleml docUUIDs.addAll(documentIngester.ingestPatronRequestDocument(reqDoc, session, null)); documentIndexer.indexDocument(reqDoc); } else { logger.error("Unsupported Document Format : " + reqDoc.getFormat() + " Called."); throw new Exception("Unsupported Document Format : " + reqDoc.getFormat() + " Called."); } } else { logger.error("Unsupported Document Type : " + reqDoc.getType() + " Called."); throw new Exception("Unsupported Document Type : " + reqDoc.getType() + " Called."); } } else { logger.error("Unsupported Category : " + reqDoc.getCategory() + " Called."); throw new Exception("Unsupported Document Category : " + reqDoc.getCategory() + " Called."); } } // Commit: DocStore session.save(); } catch (Exception e) { logger.error("Document Ingest & Index Failed, Cause: " + e.getMessage(), e); documentIngester.rollbackDocStoreIngestedData(session, request.getRequestDocuments()); documentIndexer.rollbackIndexedData(request.getRequestDocuments()); throw e; } finally { if (session != null) { getRepositoryManager().logout(session); } } Response response = buildResponse(request); return response; } private RepositoryManager getRepositoryManager() throws OleException { if (null == repositoryManager) { repositoryManager = RepositoryManager.getRepositoryManager(); } return repositoryManager; } /** * Method to ingest and index bulk Request. * * @param request * @return */ public List<String> bulkIngestNIndex(Request request, Session session) { //RequestDocument requestDocument = request.getRequestDocuments().get(0); //DocumentManager documentManager = BeanLocator.getDocumentManagerFactory().getDocumentManager(requestDocument); BatchIngestStatistics batchStatistics = BulkIngestStatistics.getInstance().getCurrentBatch(); BulkIngestStatistics bulkLoadStatistics = BulkIngestStatistics.getInstance(); long commitSize = ProcessParameters.BULK_INGEST_COMMIT_SIZE; logger.debug("commitSize = " + commitSize); logger.debug("bulkIngestNIndex(" + request.getRequestDocuments().size() + ") START"); logger.debug("BULK_INGEST_IS_LINKING_ENABLED=" + ProcessParameters.BULK_INGEST_IS_LINKING_ENABLED); //Session session = null; List<String> docUUIDs = new ArrayList<String>(); StopWatch ingestTimer = new StopWatch(); StopWatch indexTimer = new StopWatch(); StopWatch totalTimer = new StopWatch(); StopWatch createNodesTimer = new StopWatch(); StopWatch sessionSaveTimer = new StopWatch(); StopWatch solrOptimizeTimer = new StopWatch(); long recCount = request.getRequestDocuments().size(); boolean isCommit = false; totalTimer.start(); try { ingestTimer.start(); createNodesTimer.start(); //session = RepositoryManager.getRepositoryManager().getSession(request.getUser(), request.getOperation()); List<RequestDocument> reqDocs = request.getRequestDocuments(); if (prevRequestDocs == null) { prevRequestDocs = new ArrayList<RequestDocument>(); } prevRequestDocs.addAll(request.getRequestDocuments()); logger.info("prevRequestDocs" + prevRequestDocs.size()); docUUIDs.addAll(documentIngester.ingestRequestDocumentsForBulk(reqDocs, session)); //docUUIDs.addAll(documentIngester.ingestRequestDocumentsForBulkUsingBTreeMgr(reqDocs, session)); //documentManager.store(reqDocs,session); createNodesTimer.stop(); try { ingestTimer.suspend(); indexTimer.start(); } catch (Exception e2) { logger.error(e2.getMessage() , e2 ); } bulkLoadStatistics.setCommitRecCount(bulkLoadStatistics.getCommitRecCount() + recCount); if (bulkLoadStatistics.getCommitRecCount() == commitSize || bulkLoadStatistics.isLastBatch()) { isCommit = true; } documentIndexer.indexDocumentsForBulk(reqDocs, isCommit); //documentManager.index(reqDocs,isCommit); try { indexTimer.suspend(); ingestTimer.resume(); } catch (Exception e2) { logger.error(e2.getMessage() , e2 ); } if (isCommit) { sessionSaveTimer.start(); logger.info("Bulk ingest: Repository commit started. Number of records being committed : " + bulkLoadStatistics.getCommitRecCount()); session.save(); bulkLoadStatistics.setCommitRecCount(0); prevRequestDocs = null; sessionSaveTimer.stop(); } try { ingestTimer.stop(); } catch (Exception e2) { logger.error(e2.getMessage() , e2 ); } // Documents processed can be different from records processed as in the case of Instance data. logger.debug("Documents processed:" + recCount); bulkLoadStatistics.setFileRecCount(bulkLoadStatistics.getFileRecCount() + recCount); logger.info("Bulk ingest: Records processed in the current file :" + bulkLoadStatistics.getFileRecCount()); } catch (Exception e) { bulkLoadStatistics.setCommitRecCount(0); try { ingestTimer.resume(); } catch (Exception e2) { logger.error(e2.getMessage() , e2 ); } //documentIngester.rollbackDocStoreIngestedData(session, request.getRequestDocuments()); documentIngester.rollbackDocStoreIngestedData(session, prevRequestDocs); ingestTimer.stop(); try { indexTimer.resume(); } catch (Exception e2) { logger.error(e2.getMessage() , e2 ); } //documentIndexer.rollbackIndexedData(request.getRequestDocuments()); //prevRequestDocs = prevRequestDocs.subList(0, prevRequestDocs.size() - request.getRequestDocuments().size()); //logger.info("prevRequestDocs before remove INDEXES = " + prevRequestDocs.size()); documentIndexer.rollbackIndexedData(prevRequestDocs); prevRequestDocs = null; try { indexTimer.stop(); } catch (Exception e2) { logger.error(e2.getMessage() , e2 ); } logger.error("Document Ingest & Index Failed, Cause: " + e.getMessage(), e); try { totalTimer.stop(); } catch (Exception e2) { logger.error(e2.getMessage() , e2 ); } logger.debug("Time Consumptions...:\tcreatingNodes(" + docUUIDs.size() + "):" + createNodesTimer + "\tSessionSave(" + docUUIDs.size() + "):" + sessionSaveTimer + "\tIngest(" + docUUIDs.size() + "):" + ingestTimer + "\tIndexing(" + docUUIDs.size() + "):" + indexTimer + "\tTotal Time: " + totalTimer); docUUIDs.clear(); } finally { /*if (session != null) { try { RepositoryManager.getRepositoryManager().logout(session); } catch (OleException e) { } } */ } try { totalTimer.stop(); } catch (Exception exe) { logger.error(exe.getMessage() , exe ); } logger.debug( "Time Consumptions...:\tcreatingNodes(" + docUUIDs.size() + "):" + createNodesTimer + "\tSessionSave(" + docUUIDs.size() + "):" + sessionSaveTimer + "\tIngest(" + docUUIDs.size() + "):" + ingestTimer + "\tIndexing(" + docUUIDs.size() + "):" + indexTimer + "\tTotal Time: " + totalTimer); logger.debug("bulkIngestNIndex(" + request.getRequestDocuments().size() + ") END"); batchStatistics.setTimeToCreateNodesInJcr(createNodesTimer.getTime()); batchStatistics.setTimeToSaveJcrSession(sessionSaveTimer.getTime()); batchStatistics.setIngestingTime(ingestTimer.getTime()); batchStatistics.setIndexingTime(indexTimer.getTime()); batchStatistics.setIngestNIndexTotalTime(totalTimer.getTime()); updateProcessTimer(docUUIDs.size(), ingestTimer, indexTimer, totalTimer); solrOptimizeTimer.start(); optimizeSolr(docUUIDs.size()); solrOptimizeTimer.stop(); batchStatistics.setTimeToSolrOptimize(solrOptimizeTimer.getTime()); return docUUIDs; } private void updateProcessTimer(int recordsProcessed, StopWatch ingest, StopWatch index, StopWatch total) { BulkIngestTimeManager timer = ProcessParameters.BULK_PROCESSOR_TIME_MANAGER; synchronized (timer) { timer.setRecordsCount(timer.getRecordsCount() + recordsProcessed); timer.setIngestingTimer(timer.getIngestingTimer() + ingest.getTime()); timer.setIndexingTimer(timer.getIndexingTimer() + index.getTime()); timer.setProcessTimer(timer.getProcessTimer() + total.getTime()); if (timer.getRecordsCount() >= ProcessParameters.BULK_PROCESSOR_TIMER_DISPLAY) { logger.debug( "----------------------------------------------------------------------------------------------------------------------"); logger.debug(timer.toString()); logger.debug( "----------------------------------------------------------------------------------------------------------------------"); timer.reset(); } } } private void optimizeSolr(long recordsProcessed) { docCount += recordsProcessed; logger.debug("BULK_INGEST_OPTIMIZE_SIZE=" + ProcessParameters.BULK_INGEST_OPTIMIZE_SIZE + ". Records processed till now=" + docCount); logger.info("Bulk ingest: Records processed in the bulk ingest " + docCount); if (docCount >= ProcessParameters.BULK_INGEST_OPTIMIZE_SIZE) { docCount = 0; try { logger.debug("Solr Optimization: START"); documentIndexer.optimizeSolr(false, false); logger.debug("Solr Optimization: END"); } catch (Exception e) { logger.warn("Solr Optimization Failed: ", e); } } } public Response buildResponse(Request request) { Response docStoreResponse = new Response(); docStoreResponse.setUser(request.getUser()); docStoreResponse.setOperation(request.getOperation()); docStoreResponse.setMessage("Documents ingested"); docStoreResponse.setStatus("Success"); docStoreResponse.setStatusMessage("Documents Ingested Successfully"); List<ResponseDocument> responseDocuments = new ArrayList<ResponseDocument>(); ResponseDocument linkedDocument = null; ResponseDocument responseDocument = null; ResponseDocument linkedInstanceDocument = null; ResponseDocument linkedInstanceItemDocument = null; ResponseDocument linkedInstanceSrHoldingDoc = null; // documents for (Iterator<RequestDocument> iterator = request.getRequestDocuments().iterator(); iterator.hasNext(); ) { RequestDocument docStoreDocument = iterator.next(); docStoreDocument.getContent().setContent(""); responseDocument = new ResponseDocument(); setResponseParameters(responseDocument, docStoreDocument); responseDocuments.add(responseDocument); if (docStoreDocument.getLinkedRequestDocuments() != null && docStoreDocument.getLinkedRequestDocuments().size() > 0 && request != null && request.getOperation() != null && !request.getOperation().equalsIgnoreCase("checkIn")) { List<ResponseDocument> linkResponseDos = new ArrayList<ResponseDocument>(); // linked instance documents for (Iterator<RequestDocument> linkIterator = docStoreDocument.getLinkedRequestDocuments() .iterator(); linkIterator.hasNext(); ) { RequestDocument linkedRequestDocument = linkIterator.next(); linkedRequestDocument.getContent().setContent(""); linkedDocument = new ResponseDocument(); setResponseParameters(linkedDocument, linkedRequestDocument); linkResponseDos.add(linkedDocument); List<ResponseDocument> linkInstanceDocs = new ArrayList<ResponseDocument>(); InstanceCollection instanceCollection = (InstanceCollection) linkedRequestDocument.getContent() .getContentObject(); for (Instance oleInstance : instanceCollection.getInstance()) { // holding from instance linkedInstanceDocument = new ResponseDocument(); setResponseParameters(linkedInstanceDocument, linkedRequestDocument); linkedInstanceDocument.setUuid(oleInstance.getOleHoldings().getHoldingsIdentifier()); linkedInstanceDocument.setType("holdings"); linkInstanceDocs.add(linkedInstanceDocument); //SourceHolding from Instance linkedInstanceSrHoldingDoc = new ResponseDocument(); setResponseParameters(linkedInstanceSrHoldingDoc, linkedRequestDocument); if (oleInstance.getSourceHoldings() != null && oleInstance.getSourceHoldings().getHoldingsIdentifier() != null) { linkedInstanceSrHoldingDoc.setUuid(oleInstance.getSourceHoldings().getHoldingsIdentifier()); linkedInstanceSrHoldingDoc.setType("sourceHoldings"); linkInstanceDocs.add(linkedInstanceSrHoldingDoc); } // item from instance for (Iterator<Item> itemIterator = oleInstance.getItems().getItem().iterator(); itemIterator .hasNext(); ) { Item oleItem = itemIterator.next(); linkedInstanceItemDocument = new ResponseDocument(); setResponseParameters(linkedInstanceItemDocument, linkedRequestDocument); linkedInstanceItemDocument.setUuid(oleItem.getItemIdentifier()); linkedInstanceItemDocument.setType("item"); linkInstanceDocs.add(linkedInstanceItemDocument); } } responseDocument.setLinkedInstanceDocuments(linkInstanceDocs); } responseDocument.setLinkedDocuments(linkResponseDos); } } docStoreResponse.setDocuments(responseDocuments); return docStoreResponse; } private void setResponseParameters(ResponseDocument responseDocument, RequestDocument docStoreDocument) { responseDocument.setId(docStoreDocument.getId()); responseDocument.setCategory(docStoreDocument.getCategory()); responseDocument.setType(docStoreDocument.getType()); responseDocument.setFormat(docStoreDocument.getFormat()); responseDocument.setContent(docStoreDocument.getContent()); responseDocument.setUuid(docStoreDocument.getUuid()); } public void setRepositoryManager(RepositoryManager repositoryManager) { this.repositoryManager = repositoryManager; } public DocumentIngester getDocumentIngester() { return documentIngester; } }
3e08c60e64aa9ee7952e248f30f7dc6e44a6d98e
8,801
java
Java
app/src/main/java/com/universl/hp/hithatawadinawadan/UserProfileActivity.java
rayanprasanna/talks-app
9c7682037759d647bc2a2abf02437f58a1d0d802
[ "MIT" ]
1
2020-02-04T02:44:15.000Z
2020-02-04T02:44:15.000Z
app/src/main/java/com/universl/hp/hithatawadinawadan/UserProfileActivity.java
rayanprasanna/talks-app
9c7682037759d647bc2a2abf02437f58a1d0d802
[ "MIT" ]
null
null
null
app/src/main/java/com/universl/hp/hithatawadinawadan/UserProfileActivity.java
rayanprasanna/talks-app
9c7682037759d647bc2a2abf02437f58a1d0d802
[ "MIT" ]
null
null
null
44.226131
128
0.558573
3,715
package com.universl.hp.hithatawadinawadan; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SearchView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.error.VolleyError; import com.android.volley.request.StringRequest; import com.android.volley.toolbox.Volley; import com.universl.hp.hithatawadinawadan.Adapter.FansQuotesAdapter; import com.universl.hp.hithatawadinawadan.Response.QuotesResponse; import com.universl.hp.hithatawadinawadan.Util.Constant; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class UserProfileActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{ private List<QuotesResponse> fansQuotesResponses,fansQuotesResponsesPhoto; private ArrayList<String> image_path; private FansQuotesAdapter quotesAdapter; private ProgressDialog progress; @Override protected void onPause() { super.onPause(); if ((progress != null) && progress.isShowing()) progress.dismiss(); progress = null; } @TargetApi(Build.VERSION_CODES.KITKAT) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_profile); fansQuotesResponses = new ArrayList<>(); fansQuotesResponsesPhoto = new ArrayList<>(); image_path = new ArrayList<>(); Objects.requireNonNull(getSupportActionBar()).setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); progress = new ProgressDialog(UserProfileActivity.this); ListView listView = findViewById(R.id.quotes_list); final SearchView searchView = findViewById(R.id.search); loadFansProduct(); Bundle bundle = getIntent().getBundleExtra("profile"); List<QuotesResponse> responses = (List<QuotesResponse>) bundle.getSerializable("quotes"); if (responses != null) { responses.size(); } quotesAdapter = new FansQuotesAdapter(UserProfileActivity.this, (List<QuotesResponse>) bundle.getSerializable("quotes"), (List<QuotesResponse>) bundle.getSerializable("favorite_quotes"),bundle.getStringArrayList("image_path")); listView.setAdapter(quotesAdapter); searchView.setOnQueryTextListener(this); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { searchView.setQuery(fansQuotesResponses.get(position).title,true); } }); } private void loadFansProduct(){ @SuppressLint("StaticFieldLeak") class Network extends AsyncTask<Void,Void,Void>{ @Override protected void onPreExecute() { super.onPreExecute(); progress.setTitle(getString(R.string.app_name)); progress.setMessage("Data is Downloading !"); progress.setProgressStyle(ProgressDialog.STYLE_SPINNER); progress.setIndeterminate(true); progress.show(); } @Override protected Void doInBackground(Void... voids) { StringRequest request = new StringRequest(Request.Method.GET, Constant.GET_QUOTES_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { try { final JSONArray fansProduct = new JSONArray(response); for (int i = 0;i < fansProduct.length(); i++){ JSONObject productObject = fansProduct.getJSONObject(i); if (productObject.getString("category"). equalsIgnoreCase("Fans Quotes")){ String category = productObject.getString("category"); String title = productObject.getString("title"); String date = productObject.getString("date"); String photo = productObject.getString("photo"); String user_name = productObject.getString("user_name"); String status = productObject.getString("status"); QuotesResponse quotes = new QuotesResponse( category,title,date,photo,user_name,status ); fansQuotesResponses.add(quotes); } } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(UserProfileActivity.this,error.getMessage(),Toast.LENGTH_LONG).show(); } }); Volley.newRequestQueue(UserProfileActivity.this).add(request); StringRequest stringRequest = new StringRequest(Request.Method.GET, Constant.GET_FAVORITE_QUOTES_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { try { final JSONArray product = new JSONArray(response); product.length(); for (int i = 0;i < product.length(); i++){ JSONObject productObject = product.getJSONObject(i); String user_id = productObject.getString("user_id"); String photo = productObject.getString("photo"); QuotesResponse quotes = new QuotesResponse(photo,user_id); fansQuotesResponsesPhoto.add(quotes); image_path.add(photo); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(UserProfileActivity.this,error.getMessage(),Toast.LENGTH_LONG).show(); } }); Volley.newRequestQueue(UserProfileActivity.this).add(stringRequest); return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); progress.dismiss(); } }new Network().execute(); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home){ Intent intent = new Intent(UserProfileActivity.this,MainActivity.class); startActivity(intent); finish(); } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { super.onBackPressed(); Intent intent = new Intent(UserProfileActivity.this,MainActivity.class); startActivity(intent); finish(); } @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { quotesAdapter.filter(newText); return false; } }
3e08c612fcd6ce3695f4c62e1436c59638ecc595
712
java
Java
src/test/java/org/osgl/inject/User.java
osglworks/java-di
43d0249beb5b726f44393aa4d9eab837525c64bf
[ "Apache-2.0" ]
51
2016-07-17T08:24:27.000Z
2022-03-06T17:00:53.000Z
src/test/java/org/osgl/inject/User.java
osglworks/java-di
43d0249beb5b726f44393aa4d9eab837525c64bf
[ "Apache-2.0" ]
59
2016-10-10T09:24:26.000Z
2020-06-27T02:55:07.000Z
src/test/java/org/osgl/inject/User.java
osglworks/java-di
43d0249beb5b726f44393aa4d9eab837525c64bf
[ "Apache-2.0" ]
15
2017-03-02T13:50:06.000Z
2019-12-27T11:10:08.000Z
28.48
75
0.707865
3,716
package org.osgl.inject; /*- * #%L * OSGL Genie * %% * Copyright (C) 2017 OSGL (Open Source General Library) * %% * 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. * #L% */ public class User { }
3e08c624a8e75a9ccba55b3704c9a5be571207f7
130
java
Java
examples-graphql/src/main/java/carnival/examples/AppBootGraphql.java
yingzhuo/carnival-examples
3df3a00ba363962dc812dd8d75a12d22219ce455
[ "Apache-2.0" ]
null
null
null
examples-graphql/src/main/java/carnival/examples/AppBootGraphql.java
yingzhuo/carnival-examples
3df3a00ba363962dc812dd8d75a12d22219ce455
[ "Apache-2.0" ]
null
null
null
examples-graphql/src/main/java/carnival/examples/AppBootGraphql.java
yingzhuo/carnival-examples
3df3a00ba363962dc812dd8d75a12d22219ce455
[ "Apache-2.0" ]
null
null
null
16.25
60
0.838462
3,717
package carnival.examples; import org.springframework.context.annotation.Configuration; @Configuration class AppBootGraphql { }