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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e1902c42c7fd33b3a6e39a586cac49b53e675f0 | 1,282 | java | Java | rs.etf.stud.botfights.tictactoe/java/rs/etf/stud/botfights/tictactoe/O.java | evox94/TicTacToeBotfights | b1acf4724f605b599ceaee5b63af33ff8afbe586 | [
"MIT"
] | null | null | null | rs.etf.stud.botfights.tictactoe/java/rs/etf/stud/botfights/tictactoe/O.java | evox94/TicTacToeBotfights | b1acf4724f605b599ceaee5b63af33ff8afbe586 | [
"MIT"
] | null | null | null | rs.etf.stud.botfights.tictactoe/java/rs/etf/stud/botfights/tictactoe/O.java | evox94/TicTacToeBotfights | b1acf4724f605b599ceaee5b63af33ff8afbe586 | [
"MIT"
] | null | null | null | 27.869565 | 104 | 0.695788 | 10,640 | package rs.etf.stud.botfights.tictactoe;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.scene.Node;
import javafx.scene.paint.Color;
import javafx.scene.shape.Arc;
import javafx.scene.shape.ArcType;
import javafx.scene.shape.Circle;
import javafx.util.Duration;
import java.util.Collection;
import java.util.List;
public class O implements MyCustomAnimatedShape {
private Arc arc;
private Circle circle;
public O(double cx, double cy, double radius, int strokeWidth, Color strokeColor, Color fillColor) {
arc = new Arc(cx, cy, radius, radius, 0, 0);
arc.setStrokeWidth(strokeWidth);
arc.setStroke(strokeColor);
arc.setType(ArcType.OPEN);
arc.setFill(fillColor);
arc.setStartAngle(90);
}
@Override
public Collection<Node> getNodes() {
return List.of(arc);
}
@Override
public Animation getAnimation() {
Timeline timeline = new Timeline();
timeline.setCycleCount(1);
KeyValue kv = new KeyValue(arc.lengthProperty(), 360);
KeyFrame kf = new KeyFrame(Duration.millis(400), kv);
timeline.getKeyFrames().add(kf);
return timeline;
}
}
|
3e19030d81914fd9da2b5c36481193bcb798ef08 | 183 | java | Java | src/main/java/pl/touk/sputnik/connector/saas/json/Violation.java | dswiecki/sputnik | 5fa114309734b3e5d11dbeb10df3df9b009e988a | [
"Apache-2.0"
] | 179 | 2015-01-16T16:20:10.000Z | 2022-03-14T04:59:39.000Z | src/main/java/pl/touk/sputnik/connector/saas/json/Violation.java | dswiecki/sputnik | 5fa114309734b3e5d11dbeb10df3df9b009e988a | [
"Apache-2.0"
] | 181 | 2015-01-02T10:13:48.000Z | 2021-12-20T03:58:38.000Z | src/main/java/pl/touk/sputnik/connector/saas/json/Violation.java | dswiecki/sputnik | 5fa114309734b3e5d11dbeb10df3df9b009e988a | [
"Apache-2.0"
] | 76 | 2015-01-09T22:13:07.000Z | 2021-11-11T15:42:39.000Z | 16.636364 | 44 | 0.781421 | 10,641 | package pl.touk.sputnik.connector.saas.json;
import lombok.AllArgsConstructor;
@AllArgsConstructor
public class Violation {
private Integer line;
private String message;
}
|
3e19057a3c86a1301cfd928612909efca8504373 | 106 | java | Java | core/src/main/java/cn/yuanye1818/func4a/core/hero/AddHero.java | yuanye1818/afuncs | 4c39b2cd441136755eb1b12858f2480a3c7ec1a9 | [
"Apache-2.0"
] | null | null | null | core/src/main/java/cn/yuanye1818/func4a/core/hero/AddHero.java | yuanye1818/afuncs | 4c39b2cd441136755eb1b12858f2480a3c7ec1a9 | [
"Apache-2.0"
] | null | null | null | core/src/main/java/cn/yuanye1818/func4a/core/hero/AddHero.java | yuanye1818/afuncs | 4c39b2cd441136755eb1b12858f2480a3c7ec1a9 | [
"Apache-2.0"
] | null | null | null | 17.666667 | 39 | 0.754717 | 10,642 | package cn.yuanye1818.func4a.core.hero;
public interface AddHero {
public void addHero(Hero hero);
}
|
3e1906d4a199fee3c59ad656d9564acb4aa39543 | 25,891 | java | Java | android/src/main/java/com/igaworks/adbrixrm_flutter/AdbrixrmFlutterPlugin.java | jinukkr/adbrixrm_flutter | 44249a548e8df6afc31bc4203fccdbcd9ebd9ada | [
"MIT"
] | 3 | 2019-11-10T12:56:57.000Z | 2020-10-30T02:55:03.000Z | android/src/main/java/com/igaworks/adbrixrm_flutter/AdbrixrmFlutterPlugin.java | jinukkr/adbrixrm_flutter | 44249a548e8df6afc31bc4203fccdbcd9ebd9ada | [
"MIT"
] | 1 | 2021-06-14T10:12:42.000Z | 2021-06-14T10:14:13.000Z | android/src/main/java/com/igaworks/adbrixrm_flutter/AdbrixrmFlutterPlugin.java | jinukkr/adbrixrm_flutter | 44249a548e8df6afc31bc4203fccdbcd9ebd9ada | [
"MIT"
] | null | null | null | 31.345036 | 182 | 0.6111 | 10,643 | package com.igaworks.adbrixrm_flutter;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.igaworks.v2.core.AbxCommerce;
import com.igaworks.v2.core.AbxCommon;
import com.igaworks.v2.core.AbxGame;
import com.igaworks.v2.core.AdBrixRm;
import com.igaworks.v2.core.application.AbxActivityHelper;
import java.util.ArrayList;
import java.util.HashMap;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
/**
* AdbrixrmflutterPlugin
*/
public class AdbrixrmFlutterPlugin implements FlutterPlugin, ActivityAware, MethodCallHandler, AdBrixRm.DeferredDeeplinkListener, AdBrixRm.DeeplinkListener {
private String myDeferredDeeplink;
private String myDeeplink;
private Context context;
private Activity activity;
private MethodChannel channel;
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "adbrixrm_flutter");
channel.setMethodCallHandler(this);
context = flutterPluginBinding.getApplicationContext();
}
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
String method = call.method;
switch (method) {
case "sdkInit":
sdkInit(call);
break;
case "adbrixDeferredDeeplink":
adbrixDeferredDeeplink(myDeferredDeeplink, result);
break;
case "adbrixDeeplink":
adbrixDeeplink(myDeeplink, result);
break;
case "setEventUploadCountInterval":
setEventUploadCountInterval(call);
break;
case "setEventUploadTimeInterval":
setEventUploadTimeInterval(call);
break;
case "gdprForgetMe":
gdprForgetMe();
break;
case "setAge":
setAge(call);
break;
case "setGender":
setGender(call);
break;
case "setUserProperties":
setUserProperties(call);
break;
case "events":
events(call);
break;
case "login":
login(call);
break;
case "commonSignUp":
commonSignUp(call);
break;
case "appUpdate":
appUpdate(call);
break;
case "userInvite":
userInvite(call);
break;
case "useCredit":
useCredit(call);
break;
case "commonPurchase":
commonPurchase(call);
break;
case "gameTutorialComplete":
gameTutorialComplete(call);
break;
case "gameCharacterCreated":
gameCharacterCreated(call);
break;
case "gameStageCleared":
gameStageCleared(call);
break;
case "gameLevelAchieved":
gameLevelAchieved(call);
break;
case "commerceViewHome":
commerceViewHome();
break;
case "commerceProductView":
commerceProductView(call);
break;
case "commerceAddToWishList":
commerceAddToWishList(call);
break;
case "commerceShare":
commerceShare(call);
break;
case "commercePaymentInfoAdd":
commercePaymentInfoAdd(call);
break;
case "commerceCategoryView":
commerceCategoryView(call);
break;
case "commerceAddToCart":
commerceAddToCart(call);
break;
case "commerceReviewOrder":
commerceReviewOrder(call);
break;
case "commerceRefund":
commerceRefund(call);
break;
case "commerceSearch":
commerceSearch(call);
break;
case "commerceListView":
commerceListView(call);
break;
case "commerceCartView":
commerceCartView(call);
break;
case "logout":
logout();
break;
case "setKakaoId":
setKakaoId(call);
break;
case "setCiProperties":
setCiProperties(call);
break;
}
}
private void sdkInit(MethodCall call) {
String AppKey = call.argument("AppKey");
String SecretKey = call.argument("SecretKey");
AbxActivityHelper.initializeSdk(context, AppKey, SecretKey);
AdBrixRm.onResume(activity);
registerLifeCycle();
AdBrixRm.setDeferredDeeplinkListener(this);
AdBrixRm.setDeeplinkListener(this);
AdBrixRm.deeplinkEvent(activity);
}
public void registerLifeCycle() {
activity.getApplication().registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(@NonNull Activity activity) {
}
@Override
public void onActivityResumed(@NonNull Activity activity) {
AdBrixRm.onResume(activity);
AdBrixRm.deeplinkEvent(activity);
}
@Override
public void onActivityPaused(@NonNull Activity activity) {
AdBrixRm.onPause();
}
@Override
public void onActivityStopped(@NonNull Activity activity) {
}
@Override
public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {
}
@Override
public void onActivityDestroyed(@NonNull Activity activity) {
}
});
}
private void adbrixDeferredDeeplink(String deferredDeeplink, Result result) {
if (deferredDeeplink != null){
result.success(deferredDeeplink);
myDeferredDeeplink = null;
} else {
result.success(null);
}
}
private void adbrixDeeplink(String depplink, Result result) {
if (depplink != null) {
result.success(depplink);
myDeeplink = null;
} else {
result.success(null);
}
}
private void setEventUploadCountInterval(MethodCall call) {
String intervalCounter = call.arguments();
AdBrixRm.setEventUploadCountInterval(AdBrixRm.AdBrixEventUploadCountInterval.valueOf(intervalCounter));
}
private void setEventUploadTimeInterval(MethodCall call) {
String interTimer = call.arguments();
AdBrixRm.setEventUploadTimeInterval(AdBrixRm.AdBrixEventUploadTimeInterval.valueOf(interTimer));
}
private void gdprForgetMe() {
AdBrixRm.gdprForgetMe(context);
}
private void setAge(MethodCall call) {
int age = call.arguments();
AdBrixRm.setAge(age);
}
private void setGender(MethodCall call) {
String gender = call.arguments();
AdBrixRm.setGender(AdBrixRm.AbxGender.valueOf(gender));
}
private void setKakaoId(MethodCall call) {
String kakaoId = call.arguments();
AdBrixRm.setKakaoId(kakaoId);
}
private void setCiProperties(MethodCall call) {
HashMap<String, Object> properties = call.arguments();
AdBrixRm.CiProperties ciProperties = AdbrixUtility.makeCiProperties(properties);
AdBrixRm.saveCiProperties(ciProperties);
}
private void setUserProperties(MethodCall call) {
HashMap<String, Object> properties = call.arguments();
AdBrixRm.UserProperties userProperties = AdbrixUtility.makeUserProperties(properties);
AdBrixRm.saveUserProperties(userProperties);
}
private void events(MethodCall call) {
String eventName = call.argument("eventName");
HashMap<String, Object> attr = call.argument("attr");
if (attr != null) {
AdBrixRm.AttrModel eventAttr = AdbrixUtility.makeAttrModel(attr);
AdBrixRm.event(eventName, eventAttr);
} else {
AdBrixRm.event(eventName);
}
}
private void login(MethodCall call) {
String userId = call.argument("userId");
AdBrixRm.login(userId);
}
private void logout() {
AdBrixRm.logout();
}
private void commonSignUp(MethodCall call) {
Integer channel = call.argument("channel");
HashMap<String, Object> attr = call.argument("attr");
if (channel != null) {
if (attr != null) {
AdBrixRm.AttrModel eventAttr = AdbrixUtility.makeAttrModel(attr);
AdBrixRm.CommonProperties.SignUp signUpUserInfo = new AdBrixRm.CommonProperties.SignUp()
.setAttrModel(eventAttr);
AbxCommon.signUp(AdBrixRm.CommonSignUpChannel.getChannelByChannelCode(channel), signUpUserInfo);
} else {
AbxCommon.signUp(AdBrixRm.CommonSignUpChannel.getChannelByChannelCode(channel));
}
}
}
private void appUpdate(MethodCall call) {
String preVersion = call.argument("preVersion");
String currVersion = call.argument("currVersion");
HashMap<String, Object> attr = call.argument("attr");
if (attr != null) {
AdBrixRm.AttrModel eventAttr = AdbrixUtility.makeAttrModel(attr);
AdBrixRm.CommonProperties.AppUpdate updateInfo = new AdBrixRm.CommonProperties.AppUpdate()
.setPrevVersion(preVersion)
.setCurrVersion(currVersion)
.setAttrModel(eventAttr);
AbxCommon.appUpdate(updateInfo);
} else {
AdBrixRm.CommonProperties.AppUpdate updateInfo = new AdBrixRm.CommonProperties.AppUpdate()
.setPrevVersion(preVersion)
.setCurrVersion(currVersion);
AbxCommon.appUpdate(updateInfo);
}
}
private void userInvite(MethodCall call) {
Integer inviteChannel = call.argument("inviteChannel");
HashMap<String, Object> attr = call.argument("attr");
if (inviteChannel != null) {
if (attr != null) {
AdBrixRm.AttrModel eventAttr = AdbrixUtility.makeAttrModel(attr);
AdBrixRm.CommonProperties.Invite inviteInfo = new AdBrixRm.CommonProperties.Invite()
.setAttrModel(eventAttr);
AbxCommon.invite(AdBrixRm.CommonInviteChannel.getChannelByChannelCode(inviteChannel), inviteInfo);
} else {
AbxCommon.invite(AdBrixRm.CommonInviteChannel.getChannelByChannelCode(inviteChannel));
}
}
}
private void useCredit(MethodCall call) {
HashMap<String, Object> attr = call.argument("attr");
if (attr != null) {
AdBrixRm.AttrModel eventAttr = AdbrixUtility.makeAttrModel(attr);
AdBrixRm.CommonProperties.UseCredit useCreditInfo = new AdBrixRm.CommonProperties.UseCredit()
.setAttrModel(eventAttr);
AbxCommon.useCredit(useCreditInfo);
} else {
AbxCommon.useCredit();
}
}
private void gameTutorialComplete(MethodCall call) {
Boolean isSkip = call.argument("isSkip");
HashMap<String, Object> attr = call.argument("attr");
if (isSkip != null) {
if (attr != null) {
AdBrixRm.AttrModel eventAttr = AdbrixUtility.makeAttrModel(attr);
AdBrixRm.GameProperties.TutorialComplete gameProperties = new AdBrixRm.GameProperties.TutorialComplete()
.setIsSkip(isSkip)
.setAttrModel(eventAttr);
AbxGame.tutorialComplete(gameProperties);
} else {
AdBrixRm.GameProperties.TutorialComplete gameProperties = new AdBrixRm.GameProperties.TutorialComplete()
.setIsSkip(isSkip);
AbxGame.tutorialComplete(gameProperties);
}
}
}
private void gameCharacterCreated(MethodCall call) {
HashMap<String, Object> attr = call.argument("attr");
if (attr != null) {
AdBrixRm.AttrModel eventAttr = AdbrixUtility.makeAttrModel(attr);
AdBrixRm.GameProperties.CharacterCreated gameProperties = new AdBrixRm.GameProperties.CharacterCreated()
.setAttrModel(eventAttr);
AbxGame.characterCreated(gameProperties);
} else {
AbxGame.characterCreated();
}
}
private void gameStageCleared(MethodCall call) {
String stageName = call.argument("stageName");
HashMap<String, Object> attr = call.argument("attr");
if (stageName != null) {
if (attr != null) {
AdBrixRm.AttrModel eventAttr = AdbrixUtility.makeAttrModel(attr);
AdBrixRm.GameProperties.StageCleared gameProperties = new AdBrixRm.GameProperties.StageCleared()
.setStageName(stageName)
.setAttrModel(eventAttr);
AbxGame.stageCleared(gameProperties);
} else {
AdBrixRm.GameProperties.StageCleared gameProperties = new AdBrixRm.GameProperties.StageCleared()
.setStageName(stageName);
AbxGame.stageCleared(gameProperties);
}
}
}
private void gameLevelAchieved(MethodCall call) {
Integer levelAchieved = call.argument("levelAchieved");
HashMap<String, Object> attr = call.argument("attr");
if (levelAchieved != null) {
if (attr != null) {
AdBrixRm.AttrModel eventAttr = AdbrixUtility.makeAttrModel(attr);
AdBrixRm.GameProperties.LevelAchieved gameProperties = new AdBrixRm.GameProperties.LevelAchieved()
.setLevel(levelAchieved)
.setAttrModel(eventAttr);
AbxGame.levelAchieved(gameProperties);
} else {
AdBrixRm.GameProperties.LevelAchieved gameProperties = new AdBrixRm.GameProperties.LevelAchieved()
.setLevel(levelAchieved);
AbxGame.levelAchieved(gameProperties);
}
}
}
private void commerceViewHome() {
AbxCommerce.viewHome();
}
private void commerceProductView(MethodCall call) {
HashMap<String, Object> productModel = call.argument("productModel");
HashMap<String, Object> attr = call.argument("attr");
if (productModel != null) {
AdBrixRm.CommerceProductModel userProduct = AdbrixUtility.makeProductModel(productModel);
if (attr != null) {
AdBrixRm.AttrModel eventAttr = AdbrixUtility.makeAttrModel(attr);
AbxCommerce.productView(userProduct, eventAttr);
} else {
AbxCommerce.productView(userProduct);
}
}
}
private void commerceAddToWishList(MethodCall call) {
HashMap<String, Object> productModel = call.argument("productModel");
HashMap<String, Object> attr = call.argument("attr");
if (productModel != null) {
AdBrixRm.CommerceProductModel userProduct = AdbrixUtility.makeProductModel(productModel);
if (attr != null) {
AdBrixRm.AttrModel eventAttr = AdbrixUtility.makeAttrModel(attr);
AbxCommerce.addToWishList(userProduct, eventAttr);
} else {
AbxCommerce.addToWishList(userProduct);
}
}
}
private void commerceShare(MethodCall call) {
HashMap<String, Object> productModel = call.argument("productModel");
HashMap<String, Object> attr = call.argument("attr");
String sharingChannel = call.argument("sharingChannel");
if (productModel != null && sharingChannel != null) {
AdBrixRm.CommerceProductModel userProduct = AdbrixUtility.makeProductModel(productModel);
if (attr != null) {
AdBrixRm.AttrModel eventAttr = AdbrixUtility.makeAttrModel(attr);
AbxCommerce.share(AdBrixRm.CommerceSharingChannel.getChannelByChannelCode(sharingChannel), userProduct, eventAttr);
} else {
AbxCommerce.share(AdBrixRm.CommerceSharingChannel.getChannelByChannelCode(sharingChannel), userProduct);
}
}
}
private void commercePaymentInfoAdd(MethodCall call) {
HashMap<String, Object> attr = call.argument("attr");
if (attr != null) {
AdBrixRm.AttrModel eventAttr = AdbrixUtility.makeAttrModel(attr);
AbxCommerce.paymentInfoAdded(eventAttr);
} else {
AbxCommerce.paymentInfoAdded();
}
}
private void commonPurchase(MethodCall call) {
String orderId = call.argument("orderId");
ArrayList<HashMap<String, Object>> productList = call.argument("productList");
Double discount = call.argument("discount");
Double orderSale = call.argument("orderSale");
Double deliveryCharge = call.argument("deliveryCharge");
String paymentMethod = call.argument("paymentMethod");
HashMap<String, Object> attr = call.argument("attr");
if (productList != null && orderId != null && orderSale != null && discount != null && deliveryCharge != null && paymentMethod != null) {
ArrayList<AdBrixRm.CommerceProductModel> productModelList = AdbrixUtility.makeProductList(productList);
if (attr != null) {
AdBrixRm.AttrModel evetAttr = AdbrixUtility.makeAttrModel(attr);
AdBrixRm.CommonProperties.Purchase purchaseAttr = new AdBrixRm.CommonProperties.Purchase()
.setAttrModel(evetAttr);
AbxCommon.purchase(orderId, productModelList, orderSale, discount, deliveryCharge, AdBrixRm.CommercePaymentMethod.getMethodByMethodCode(paymentMethod), purchaseAttr);
} else {
AbxCommon.purchase(orderId, productModelList, orderSale, discount, deliveryCharge, AdBrixRm.CommercePaymentMethod.getMethodByMethodCode(paymentMethod));
}
}
}
private void commerceCategoryView(MethodCall call) {
ArrayList<String> categoryModel = call.argument("categoryModel");
ArrayList<HashMap<String, Object>> productList = call.argument("productList");
HashMap<String, Object> attr = call.argument("attr");
if (productList != null && categoryModel != null) {
ArrayList<AdBrixRm.CommerceProductModel> productModelList = AdbrixUtility.makeProductList(productList);
AdBrixRm.CommerceCategoriesModel categoriesModel = new AdBrixRm.CommerceCategoriesModel();
for (int i = 0, n = categoryModel.size(); i < n; i++) {
String categoryListName = categoryModel.get(i);
categoriesModel.setCategory(categoryListName);
}
if (attr != null) {
AdBrixRm.AttrModel evetAttr = AdbrixUtility.makeAttrModel(attr);
AbxCommerce.categoryView(categoriesModel, productModelList, evetAttr);
} else {
AbxCommerce.categoryView(categoriesModel, productModelList);
}
}
}
private void commerceAddToCart(MethodCall call) {
ArrayList<HashMap<String, Object>> productList = call.argument("productList");
HashMap<String, Object> attr = call.argument("attr");
if (productList != null) {
ArrayList<AdBrixRm.CommerceProductModel> productModelList = AdbrixUtility.makeProductList(productList);
if (attr != null) {
AdBrixRm.AttrModel evetAttr = AdbrixUtility.makeAttrModel(attr);
AbxCommerce.addToCart(productModelList, evetAttr);
} else {
AbxCommerce.addToCart(productModelList);
}
}
}
private void commerceReviewOrder(MethodCall call) {
String orderId = call.argument("orderId");
ArrayList<HashMap<String, Object>> productList = call.argument("productList");
Double discount = call.argument("discount");
Double deliveryCharge = call.argument("deliveryCharge");
HashMap<String, Object> attr = call.argument("attr");
if (productList != null && orderId != null && discount != null && deliveryCharge != null) {
ArrayList<AdBrixRm.CommerceProductModel> productModelList = AdbrixUtility.makeProductList(productList);
if (attr != null) {
AdBrixRm.AttrModel evetAttr = AdbrixUtility.makeAttrModel(attr);
AbxCommerce.reviewOrder(orderId, productModelList, discount, deliveryCharge, evetAttr);
} else {
AbxCommerce.reviewOrder(orderId, productModelList, discount, deliveryCharge);
}
}
}
private void commerceRefund(MethodCall call) {
String orderId = call.argument("orderId");
ArrayList<HashMap<String, Object>> productList = call.argument("productList");
Double penaltyCharge = call.argument("penaltyCharge");
HashMap<String, Object> attr = call.argument("attr");
if (productList != null && orderId != null && penaltyCharge != null) {
ArrayList<AdBrixRm.CommerceProductModel> productModelList = AdbrixUtility.makeProductList(productList);
if (attr != null) {
AdBrixRm.AttrModel evetAttr = AdbrixUtility.makeAttrModel(attr);
AbxCommerce.refund(orderId, productModelList, penaltyCharge, evetAttr);
} else {
AbxCommerce.refund(orderId, productModelList, penaltyCharge);
}
}
}
private void commerceSearch(MethodCall call) {
String keyword = call.argument("keyword");
ArrayList<HashMap<String, Object>> productList = call.argument("productList");
HashMap<String, Object> attr = call.argument("attr");
if (productList != null && keyword != null) {
ArrayList<AdBrixRm.CommerceProductModel> productModelList = AdbrixUtility.makeProductList(productList);
if (attr != null) {
AdBrixRm.AttrModel evetAttr = AdbrixUtility.makeAttrModel(attr);
AbxCommerce.search(keyword, productModelList, evetAttr);
} else {
AbxCommerce.search(keyword, productModelList);
}
}
}
private void commerceListView(MethodCall call) {
ArrayList<HashMap<String, Object>> productList = call.argument("productList");
HashMap<String, Object> attr = call.argument("attr");
if (productList != null) {
ArrayList<AdBrixRm.CommerceProductModel> productModelList = AdbrixUtility.makeProductList(productList);
if (attr != null) {
AdBrixRm.AttrModel evetAttr = AdbrixUtility.makeAttrModel(attr);
AbxCommerce.listView(productModelList, evetAttr);
} else {
AbxCommerce.listView(productModelList);
}
}
}
private void commerceCartView(MethodCall call) {
ArrayList<HashMap<String, Object>> productList = call.argument("productList");
HashMap<String, Object> attr = call.argument("attr");
if (productList != null) {
ArrayList<AdBrixRm.CommerceProductModel> productModelList = AdbrixUtility.makeProductList(productList);
if (attr != null) {
AdBrixRm.AttrModel evetAttr = AdbrixUtility.makeAttrModel(attr);
AbxCommerce.cartView(productModelList, evetAttr);
} else {
AbxCommerce.cartView(productModelList);
}
}
}
@Override
public void onReceiveDeferredDeeplink(String deeplink) {
if (deeplink != null) {
myDeferredDeeplink = deeplink;
}
}
@Override
public void onReceiveDeeplink(String deeplink) {
if (deeplink != null) {
myDeeplink = deeplink;
}
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
channel.setMethodCallHandler(null);
}
@Override
public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
channel.setMethodCallHandler(this);
activity = binding.getActivity();
}
@Override
public void onDetachedFromActivityForConfigChanges() {
}
@Override
public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {
}
@Override
public void onDetachedFromActivity() {
}
}
|
3e1908399ab12e7f70275c2a09616aefa37f62b3 | 3,252 | java | Java | pkix/src/main/java/org/bouncycastle/operator/jcajce/JceKTSKeyUnwrapper.java | matheus-eyng/bc-java | b35d626619a564db860e59e1cda353dec8d7a4fa | [
"MIT"
] | 1,604 | 2015-01-01T16:53:59.000Z | 2022-03-31T13:21:39.000Z | pkix/src/main/java/org/bouncycastle/operator/jcajce/JceKTSKeyUnwrapper.java | matheus-eyng/bc-java | b35d626619a564db860e59e1cda353dec8d7a4fa | [
"MIT"
] | 1,015 | 2015-01-08T08:15:43.000Z | 2022-03-31T11:05:41.000Z | pkix/src/main/java/org/bouncycastle/operator/jcajce/JceKTSKeyUnwrapper.java | matheus-eyng/bc-java | b35d626619a564db860e59e1cda353dec8d7a4fa | [
"MIT"
] | 885 | 2015-01-01T16:54:08.000Z | 2022-03-31T22:46:25.000Z | 39.180723 | 196 | 0.753075 | 10,644 | package org.bouncycastle.operator.jcajce;
import java.security.Key;
import java.security.PrivateKey;
import java.security.Provider;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import org.bouncycastle.asn1.cms.GenericHybridParameters;
import org.bouncycastle.asn1.cms.RsaKemParameters;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.crypto.util.DEROtherInfo;
import org.bouncycastle.jcajce.spec.KTSParameterSpec;
import org.bouncycastle.jcajce.util.DefaultJcaJceHelper;
import org.bouncycastle.jcajce.util.NamedJcaJceHelper;
import org.bouncycastle.jcajce.util.ProviderJcaJceHelper;
import org.bouncycastle.operator.AsymmetricKeyUnwrapper;
import org.bouncycastle.operator.GenericKey;
import org.bouncycastle.operator.OperatorException;
import org.bouncycastle.util.Arrays;
public class JceKTSKeyUnwrapper
extends AsymmetricKeyUnwrapper
{
private OperatorHelper helper = new OperatorHelper(new DefaultJcaJceHelper());
private Map extraMappings = new HashMap();
private PrivateKey privKey;
private byte[] partyUInfo;
private byte[] partyVInfo;
public JceKTSKeyUnwrapper(AlgorithmIdentifier algorithmIdentifier, PrivateKey privKey, byte[] partyUInfo, byte[] partyVInfo)
{
super(algorithmIdentifier);
this.privKey = privKey;
this.partyUInfo = Arrays.clone(partyUInfo);
this.partyVInfo = Arrays.clone(partyVInfo);
}
public JceKTSKeyUnwrapper setProvider(Provider provider)
{
this.helper = new OperatorHelper(new ProviderJcaJceHelper(provider));
return this;
}
public JceKTSKeyUnwrapper setProvider(String providerName)
{
this.helper = new OperatorHelper(new NamedJcaJceHelper(providerName));
return this;
}
public GenericKey generateUnwrappedKey(AlgorithmIdentifier encryptedKeyAlgorithm, byte[] encryptedKey)
throws OperatorException
{
GenericHybridParameters params = GenericHybridParameters.getInstance(this.getAlgorithmIdentifier().getParameters());
Cipher keyCipher = helper.createAsymmetricWrapper(this.getAlgorithmIdentifier().getAlgorithm(), extraMappings);
String symmetricWrappingAlg = helper.getWrappingAlgorithmName(params.getDem().getAlgorithm());
RsaKemParameters kemParameters = RsaKemParameters.getInstance(params.getKem().getParameters());
int keySizeInBits = kemParameters.getKeyLength().intValue() * 8;
Key sKey;
try
{
DEROtherInfo otherInfo = new DEROtherInfo.Builder(params.getDem(), partyUInfo, partyVInfo).build();
KTSParameterSpec ktsSpec = new KTSParameterSpec.Builder(symmetricWrappingAlg, keySizeInBits, otherInfo.getEncoded()).withKdfAlgorithm(kemParameters.getKeyDerivationFunction()).build();
keyCipher.init(Cipher.UNWRAP_MODE, privKey, ktsSpec);
sKey = keyCipher.unwrap(encryptedKey, helper.getKeyAlgorithmName(encryptedKeyAlgorithm.getAlgorithm()), Cipher.SECRET_KEY);
}
catch (Exception e)
{
throw new OperatorException("Unable to unwrap contents key: " + e.getMessage(), e);
}
return new JceGenericKey(encryptedKeyAlgorithm, sKey);
}
}
|
3e1908c4c45dfb1eb065c237a25ed61a7a8f8f23 | 18,602 | java | Java | hbase/src/main/java/org/apache/james/mailbox/hbase/HBaseUtils.java | philippeBenoit/james-mailbox | c204760aaff6a5a7a5715aa0868a3268a627a621 | [
"Apache-2.0"
] | 1 | 2016-11-29T04:05:28.000Z | 2016-11-29T04:05:28.000Z | hbase/src/main/java/org/apache/james/mailbox/hbase/HBaseUtils.java | philippeBenoit/james-mailbox | c204760aaff6a5a7a5715aa0868a3268a627a621 | [
"Apache-2.0"
] | null | null | null | hbase/src/main/java/org/apache/james/mailbox/hbase/HBaseUtils.java | philippeBenoit/james-mailbox | c204760aaff6a5a7a5715aa0868a3268a627a621 | [
"Apache-2.0"
] | null | null | null | 42.763218 | 126 | 0.629717 | 10,645 | /****************************************************************
* 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.james.mailbox.hbase;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.NavigableMap;
import java.util.UUID;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.james.mailbox.hbase.io.ChunkInputStream;
import org.apache.james.mailbox.hbase.mail.model.HBaseMailbox;
import org.apache.james.mailbox.hbase.mail.HBaseMessage;
import org.apache.james.mailbox.model.MailboxPath;
import org.apache.james.mailbox.store.mail.model.Mailbox;
import org.apache.james.mailbox.store.mail.model.Message;
import org.apache.james.mailbox.store.mail.model.Property;
import org.apache.james.mailbox.store.mail.model.impl.PropertyBuilder;
import org.apache.james.mailbox.store.user.model.Subscription;
import static org.apache.james.mailbox.hbase.FlagConvertor.*;
import static org.apache.james.mailbox.hbase.PropertyConvertor.*;
import static org.apache.james.mailbox.hbase.HBaseNames.*;
/**
* HBase utility classes for mailbox and message manipulation.
* @author ieugen
*/
public class HBaseUtils {
// TODO: swith to a bit wise implementation of flags.
/**
* Creates a Mailbox object from a HBase Result object.
* @param result a result of a HBase Get operation
* @return a Mailbox object
*/
public static Mailbox<UUID> mailboxFromResult(Result result) {
NavigableMap<byte[], byte[]> rawMailbox = result.getFamilyMap(MAILBOX_CF);
//TODO: should we test for null values?
MailboxPath path = new MailboxPath(Bytes.toString(rawMailbox.get(MAILBOX_NAMESPACE)),
Bytes.toString(rawMailbox.get(MAILBOX_USER)),
Bytes.toString(rawMailbox.get(MAILBOX_NAME)));
HBaseMailbox mailbox = new HBaseMailbox(path, Bytes.toLong(rawMailbox.get(MAILBOX_UIDVALIDITY)));
mailbox.setMailboxId(UUIDFromRowKey(result.getRow()));
mailbox.setHighestModSeq(Bytes.toLong(rawMailbox.get(MAILBOX_HIGHEST_MODSEQ)));
mailbox.setLastUid(Bytes.toLong(rawMailbox.get(MAILBOX_LASTUID)));
mailbox.setMessageCount(Bytes.toLong(rawMailbox.get(MAILBOX_MESSAGE_COUNT)));
return mailbox;
}
/**
* This returns the row key needed for HBase. Having the method here ensure
* we have a consistent way to generate the rowkey.
*
* Convenience method for generating a rowKey when you don't have a mailbox object.
* @param uuid
* @return rowkey byte array that can be used with HBase API
*/
public static byte[] mailboxRowKey(UUID uuid) {
byte[] rowKey = new byte[16];
int offset = Bytes.putLong(rowKey, 0, uuid.getMostSignificantBits());
Bytes.putLong(rowKey, offset, uuid.getLeastSignificantBits());
return rowKey;
}
/**
* Returns a UUID from the a byte array.
* @param rowkey
* @return UUID calculated from the byte array
*/
public static UUID UUIDFromRowKey(byte[] rowkey) {
return new UUID(Bytes.toLong(rowkey, 0), Bytes.toLong(rowkey, 8));
}
/**
* Transforms the mailbox into a Put operation.
* @return a Put object
*/
public static Put toPut(HBaseMailbox mailbox) {
Put put = new Put(mailboxRowKey(mailbox.getMailboxId()));
// we don't store null values and we don't restore them. it's a column based store.
if (mailbox.getName() != null) {
put.add(MAILBOX_CF, MAILBOX_NAME, Bytes.toBytes(mailbox.getName()));
}
if (mailbox.getUser() != null) {
put.add(MAILBOX_CF, MAILBOX_USER, Bytes.toBytes(mailbox.getUser()));
}
if (mailbox.getNamespace() != null) {
put.add(MAILBOX_CF, MAILBOX_NAMESPACE, Bytes.toBytes(mailbox.getNamespace()));
}
put.add(MAILBOX_CF, MAILBOX_LASTUID, Bytes.toBytes(mailbox.getLastUid()));
put.add(MAILBOX_CF, MAILBOX_UIDVALIDITY, Bytes.toBytes(mailbox.getUidValidity()));
put.add(MAILBOX_CF, MAILBOX_HIGHEST_MODSEQ, Bytes.toBytes(mailbox.getHighestModSeq()));
put.add(MAILBOX_CF, MAILBOX_MESSAGE_COUNT, Bytes.toBytes(mailbox.getMessageCount()));
return put;
}
/**
* Transforms only the metadata into a Put object. The rest of the message will
* be transfered using multiple Puts if size requires it.
* @param message
* @return a put that contains all metadata information.
*/
public static Put metadataToPut(Message<UUID> message) {
Put put = new Put(messageRowKey(message));
// we store the message uid and mailbox uid in the row key
// store the meta data
put.add(MESSAGES_META_CF, MESSAGE_MODSEQ, Bytes.toBytes(message.getModSeq()));
put.add(MESSAGES_META_CF, MESSAGE_INTERNALDATE, Bytes.toBytes(message.getInternalDate().getTime()));
put.add(MESSAGES_META_CF, MESSAGE_MEDIA_TYPE, Bytes.toBytes(message.getMediaType()));
put.add(MESSAGES_META_CF, MESSAGE_SUB_TYPE, Bytes.toBytes(message.getSubType()));
put.add(MESSAGES_META_CF, MESSAGE_CONTENT_OCTETS, Bytes.toBytes(message.getFullContentOctets()));
put.add(MESSAGES_META_CF, MESSAGE_BODY_OCTETS, Bytes.toBytes(message.getBodyOctets()));
if (message.getTextualLineCount() != null) {
put.add(MESSAGES_META_CF, MESSAGE_TEXT_LINE_COUNT, Bytes.toBytes(message.getTextualLineCount()));
}
// store system flags in meta and user flags in uflags to avoid name clashes
Flags flags = message.createFlags();
// system flags
if (flags.contains(Flag.ANSWERED)) {
put.add(MESSAGES_META_CF, FLAGS_ANSWERED, MARKER_PRESENT);
}
if (flags.contains(Flag.DELETED)) {
put.add(MESSAGES_META_CF, FLAGS_DELETED, MARKER_PRESENT);
}
if (flags.contains(Flag.DRAFT)) {
put.add(MESSAGES_META_CF, FLAGS_DRAFT, MARKER_PRESENT);
}
if (flags.contains(Flag.FLAGGED)) {
put.add(MESSAGES_META_CF, FLAGS_FLAGGED, MARKER_PRESENT);
}
if (flags.contains(Flag.RECENT)) {
put.add(MESSAGES_META_CF, FLAGS_RECENT, MARKER_PRESENT);
}
if (flags.contains(Flag.SEEN)) {
put.add(MESSAGES_META_CF, FLAGS_SEEN, MARKER_PRESENT);
}
if (flags.contains(Flag.USER)) {
put.add(MESSAGES_META_CF, FLAGS_USER, MARKER_PRESENT);
}
// user flags
for (String flag : flags.getUserFlags()) {
put.add(MESSAGES_META_CF, userFlagToBytes(flag), MARKER_PRESENT);
}
int propNumber = 0;
// add the properties
for (Property prop : message.getProperties()) {
put.add(MESSAGES_META_CF, getQualifier(propNumber++), getValue(prop));
}
return put;
}
/**
* Create a row key for a message in a mailbox. The current row key is mailboxID followed by messageID.
* Both values are fixed length so no separator is needed.
* Downside: we will be storing the same message multiple times, one time for each recipient.
* @param message message to get row key from
* @return rowkey byte array that can be used with HBase API
*/
public static byte[] messageRowKey(Message<UUID> message) {
return messageRowKey(message.getMailboxId(), message.getUid());
}
/**
* Utility method to build row keys from mailbox UUID and message uid.
* The message uid's are stored in reverse order by substracting the uid value
* from Long.MAX_VALUE.
* @param mailboxUid mailbox UUID
* @param uid message uid
* @return rowkey byte array that can be used with HBase API
*/
public static byte[] messageRowKey(UUID mailboxUid, long uid) {
/** message uid's are stored in reverse order so we will always have the most recent messages first*/
byte[] ba = Bytes.add(Bytes.toBytes(mailboxUid.getMostSignificantBits()),
Bytes.toBytes(mailboxUid.getLeastSignificantBits()),
Bytes.toBytes(Long.MAX_VALUE - uid));
//System.out.println(Bytes.toStringBinary(ba));
return ba;
}
/**
* Utility to build row keys from mailboxUID and a value. The value is added to
* the key without any other operations.
* @param mailboxUid mailbox UUID
* @param value
* @return rowkey byte array that can be used with HBase API
*/
public static byte[] customMessageRowKey(UUID mailboxUid, long value) {
return Bytes.add(Bytes.toBytes(mailboxUid.getMostSignificantBits()),
Bytes.toBytes(mailboxUid.getLeastSignificantBits()),
Bytes.toBytes(value));
}
/**
* Creates a HBaseMessage from a Result object. This method retrieves all information
* except for body and header related bytes. The message content will be loaded on demand
* through a specialised InputStream called {@link ChunkInputStream}.
* IMPORTANT: the method expects a single version of each cell. Use setMaxVersions(1).
* @param conf configuration object for HBase cluster
* @param result the result object containing message data
* @return a HBaseMessage instance with message metadata.
*/
public static Message<UUID> messageMetaFromResult(Configuration conf, Result result) {
HBaseMessage message = null;
Flags flags = new Flags();
List<Property> propList = new ArrayList<Property>();
KeyValue[] keys = result.raw();
String mediaType = null, subType = null;
Long modSeq = null, uid, bodyOctets = null, contentOctets = null, textualLineCount = null;
Date internalDate = null;
int i = 0;
/** it is VERY IMPORTANT that the byte arrays are kept ascending */
if (Bytes.equals(keys[i].getQualifier(), MESSAGE_BODY_OCTETS)) {
bodyOctets = Bytes.toLong(keys[i].getValue());
i++;
}
if (Bytes.equals(keys[i].getQualifier(), MESSAGE_CONTENT_OCTETS)) {
contentOctets = Bytes.toLong(keys[i].getValue());
i++;
}
if (Bytes.equals(keys[i].getQualifier(), MESSAGE_INTERNALDATE)) {
internalDate = new Date(Bytes.toLong(keys[i].getValue()));
i++;
}
// may be null so it will probably skip
if (Bytes.equals(keys[i].getQualifier(), MESSAGE_TEXT_LINE_COUNT)) {
textualLineCount = Bytes.toLong(keys[i].getValue());
i++;
}
if (Bytes.equals(keys[i].getQualifier(), MESSAGE_MODSEQ)) {
modSeq = Bytes.toLong(keys[i].getValue());
i++;
}
if (Bytes.equals(keys[i].getQualifier(), MESSAGE_MEDIA_TYPE)) {
mediaType = Bytes.toString(keys[i].getValue());
i++;
}
if (Bytes.equals(keys[i].getQualifier(), MESSAGE_SUB_TYPE)) {
subType = Bytes.toString(keys[i].getValue());
i++;
}
// only TEXT_LINE_COUNT can be missing if message is binary
if (i < 5) {
throw new RuntimeException("HBase message column names not sorted.");
}
while (i < keys.length) {
//get message properties
if (Bytes.startsWith(keys[i].getQualifier(), PREFIX_PROP_B)) {
propList.add(getProperty(keys[i].getValue()));
} else if (Bytes.startsWith(keys[i].getQualifier(), PREFIX_SFLAGS_B)) {
// get system flags, stored as qualifiers
if (Bytes.equals(MARKER_PRESENT, keys[i].getValue())) {
flags.add(systemFlagFromBytes(keys[i].getQualifier()));
}
} else if (Bytes.startsWith(keys[i].getQualifier(), PREFIX_UFLAGS_B)) {
// get user flags, stored as value qualifier
flags.add(userFlagFromBytes(keys[i].getQualifier()));
}
i++;
}
UUID uuid = UUIDFromRowKey(result.getRow());
uid = Long.MAX_VALUE - Bytes.toLong(result.getRow(), 16);
PropertyBuilder props = new PropertyBuilder(propList);
props.setMediaType(mediaType);
props.setSubType(subType);
message = new HBaseMessage(conf, uuid, internalDate, flags, contentOctets, (int) (contentOctets - bodyOctets), props);
message.setUid(uid);
message.setModSeq(modSeq);
message.setTextualLineCount(textualLineCount);
return message;
}
/**
* Creates a Put object from this subscription object
* @return Put object suitable for HBase persistence
*/
public static Put toPut(Subscription subscription) {
Put put = new Put(Bytes.toBytes(subscription.getUser()));
put.add(SUBSCRIPTION_CF, Bytes.toBytes(subscription.getMailbox()), MARKER_PRESENT);
return put;
}
/**
* Utility method to transform message flags into a put opperation.
* @param message
* @param flags
* @return a put object with
*/
public static Put flagsToPut(Message<UUID> message, Flags flags) {
Put put = new Put(messageRowKey(message));
//system flags
if (flags.contains(Flag.ANSWERED)) {
put.add(MESSAGES_META_CF, FLAGS_ANSWERED, MARKER_PRESENT);
} else {
put.add(MESSAGES_META_CF, FLAGS_ANSWERED, MARKER_MISSING);
}
if (flags.contains(Flag.DELETED)) {
put.add(MESSAGES_META_CF, FLAGS_DELETED, MARKER_PRESENT);
} else {
put.add(MESSAGES_META_CF, FLAGS_DELETED, MARKER_MISSING);
}
if (flags.contains(Flag.DRAFT)) {
put.add(MESSAGES_META_CF, FLAGS_DRAFT, MARKER_PRESENT);
} else {
put.add(MESSAGES_META_CF, FLAGS_DRAFT, MARKER_MISSING);
}
if (flags.contains(Flag.FLAGGED)) {
put.add(MESSAGES_META_CF, FLAGS_FLAGGED, MARKER_PRESENT);
} else {
put.add(MESSAGES_META_CF, FLAGS_FLAGGED, MARKER_MISSING);
}
if (flags.contains(Flag.RECENT)) {
put.add(MESSAGES_META_CF, FLAGS_RECENT, MARKER_PRESENT);
} else {
put.add(MESSAGES_META_CF, FLAGS_RECENT, MARKER_MISSING);
}
if (flags.contains(Flag.SEEN)) {
put.add(MESSAGES_META_CF, FLAGS_SEEN, MARKER_PRESENT);
} else {
put.add(MESSAGES_META_CF, FLAGS_SEEN, MARKER_MISSING);
}
if (flags.contains(Flag.USER)) {
put.add(MESSAGES_META_CF, FLAGS_USER, MARKER_PRESENT);
} else {
put.add(MESSAGES_META_CF, FLAGS_USER, MARKER_MISSING);
}
/**TODO: user flags are not deleted this way: store them all in a single column
* and replace that column full.
*/
// user flags
for (String flag : flags.getUserFlags()) {
put.add(MESSAGES_META_CF, userFlagToBytes(flag), MARKER_PRESENT);
}
return put;
}
public static Delete flagsToDelete(Message<UUID> message, Flags flags) {
Delete delete = new Delete(messageRowKey(message));
//we mark for delete flags that are not present (they will be Put'ed)
if (flags.contains(Flag.ANSWERED)) {
delete.deleteColumn(MESSAGES_META_CF, FLAGS_ANSWERED);
}
if (flags.contains(Flag.DELETED)) {
delete.deleteColumn(MESSAGES_META_CF, FLAGS_DELETED);
}
if (flags.contains(Flag.DRAFT)) {
delete.deleteColumn(MESSAGES_META_CF, FLAGS_DRAFT);
}
if (flags.contains(Flag.FLAGGED)) {
delete.deleteColumn(MESSAGES_META_CF, FLAGS_FLAGGED);
}
if (flags.contains(Flag.RECENT)) {
delete.deleteColumn(MESSAGES_META_CF, FLAGS_RECENT);
}
if (flags.contains(Flag.SEEN)) {
delete.deleteColumn(MESSAGES_META_CF, FLAGS_SEEN);
}
if (flags.contains(Flag.USER)) {
delete.deleteColumn(MESSAGES_META_CF, FLAGS_USER);
}
// we delete all user flags that where not in the new configuration
for (String flag : flags.getUserFlags()) {
delete.deleteColumn(MESSAGES_META_CF, userFlagToBytes(flag));
}
return delete;
}
/**
* Returns a String composed of all flags in the parameter.
* @param flags
* @return a string representation of all flags
*/
public static String flagsToString(Flags flags) {
StringBuilder b = new StringBuilder();
if (flags.contains(Flag.ANSWERED)) {
b.append("ANSWERED ");
}
if (flags.contains(Flag.DELETED)) {
b.append("DELETED ");
}
if (flags.contains(Flag.DRAFT)) {
b.append("DRAFT ");
}
if (flags.contains(Flag.FLAGGED)) {
b.append("FLAGGED ");
}
if (flags.contains(Flag.RECENT)) {
b.append("RECENT ");
}
if (flags.contains(Flag.SEEN)) {
b.append("SEEN ");
}
if (flags.contains(Flag.USER)) {
b.append("USER ");
}
for (String flag : flags.getUserFlags()) {
b.append(flag);
b.append(" ");
}
return b.toString();
}
}
|
3e1909a8f2fd0bf83b5900e3d24e125e3e69de10 | 189 | java | Java | Java OOP Advanced November 2017/e_Reflection/Exercises/p03_BarracksWarsAllRemainingProblems/contracts/CommandInterpreter.java | kr056/Softuni | de9a043ba6d938dfa3f20940f99322033cf8038b | [
"MIT"
] | null | null | null | Java OOP Advanced November 2017/e_Reflection/Exercises/p03_BarracksWarsAllRemainingProblems/contracts/CommandInterpreter.java | kr056/Softuni | de9a043ba6d938dfa3f20940f99322033cf8038b | [
"MIT"
] | 10 | 2020-09-05T17:16:49.000Z | 2022-03-08T23:12:53.000Z | Java OOP Advanced November 2017/e_Reflection/Exercises/p03_BarracksWarsAllRemainingProblems/contracts/CommandInterpreter.java | kr056/Softuni | de9a043ba6d938dfa3f20940f99322033cf8038b | [
"MIT"
] | null | null | null | 27 | 78 | 0.84127 | 10,646 | package e_Reflection.Exercises.p03_BarracksWarsAllRemainingProblems.contracts;
public interface CommandInterpreter {
Executable interpretCommand(String[] data, String commandName);
}
|
3e190a6aeb4bcefef1f1eb1486156a122399c6cf | 1,242 | java | Java | Javac2007/流程/comp/02MemberEnter/memberEnter.java | codefollower/Open-Source-Research | b9f2aed9d0f060b80be45f713c3d48fe91f247b2 | [
"Apache-2.0"
] | 184 | 2015-01-04T03:38:20.000Z | 2022-03-30T05:47:21.000Z | Javac2007/流程/comp/02MemberEnter/memberEnter.java | codefollower/Open-Source-Research | b9f2aed9d0f060b80be45f713c3d48fe91f247b2 | [
"Apache-2.0"
] | 1 | 2016-01-17T09:18:17.000Z | 2016-01-17T09:18:17.000Z | Javac2007/流程/comp/02MemberEnter/memberEnter.java | codefollower/Open-Source-Research | b9f2aed9d0f060b80be45f713c3d48fe91f247b2 | [
"Apache-2.0"
] | 101 | 2015-01-16T23:46:31.000Z | 2022-03-30T05:47:06.000Z | 35.485714 | 90 | 0.580515 | 10,647 | /** Visitor argument: the current environment
*/
protected Env<AttrContext> env;
/** Enter field and method definitions and process import
* clauses, catching any completion failure exceptions.
*/
protected void memberEnter(JCTree tree, Env<AttrContext> env) {
DEBUG.P(this,"memberEnter(2)");
DEBUG.P("tree.tag="+tree.myTreeTag());
DEBUG.P("先前Env="+this.env);
DEBUG.P("当前Env="+env);
Env<AttrContext> prevEnv = this.env;
try {
this.env = env;
tree.accept(this);
} catch (CompletionFailure ex) {
chk.completionError(tree.pos(), ex);
} finally {
this.env = prevEnv;
DEBUG.P(1,this,"memberEnter(2)");
}
}
/** Enter members from a list of trees.
*/
void memberEnter(List<? extends JCTree> trees, Env<AttrContext> env) {
DEBUG.P(this,"memberEnter(List<? extends JCTree> trees, Env<AttrContext> env)");
DEBUG.P("trees.size="+trees.size());
for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail) {
memberEnter(l.head, env);
}
DEBUG.P(0,this,"memberEnter(List<? extends JCTree> trees, Env<AttrContext> env)");
} |
3e190a81a11e1c03e28d1e223431f58e59ddefeb | 1,562 | java | Java | web-common/src/main/java/pl/edu/icm/unity/webui/common/attributes/image/ImageAttributeHandlerFactory.java | unity-idm/test-import | 246b06505afe193167daf894dabff8cc7ffd6787 | [
"BSD-3-Clause"
] | 20 | 2017-10-15T19:29:10.000Z | 2021-12-13T20:22:48.000Z | web-common/src/main/java/pl/edu/icm/unity/webui/common/attributes/image/ImageAttributeHandlerFactory.java | unity-idm/test-import | 246b06505afe193167daf894dabff8cc7ffd6787 | [
"BSD-3-Clause"
] | 19 | 2017-11-02T18:08:58.000Z | 2022-02-16T00:37:05.000Z | web-common/src/main/java/pl/edu/icm/unity/webui/common/attributes/image/ImageAttributeHandlerFactory.java | unity-idm/test-import | 246b06505afe193167daf894dabff8cc7ffd6787 | [
"BSD-3-Clause"
] | 8 | 2017-11-17T13:40:47.000Z | 2020-09-11T13:06:44.000Z | 30.038462 | 107 | 0.782971 | 10,648 | /*
* Copyright (c) 2018 Bixbit - Krzysztof Benedyczak All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.webui.common.attributes.image;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pl.edu.icm.unity.MessageSource;
import pl.edu.icm.unity.attr.UnityImage;
import pl.edu.icm.unity.engine.api.attributes.AttributeValueSyntax;
import pl.edu.icm.unity.stdext.attr.ImageAttributeSyntax;
import pl.edu.icm.unity.webui.common.attributes.AttributeSyntaxEditor;
import pl.edu.icm.unity.webui.common.attributes.WebAttributeHandler;
import pl.edu.icm.unity.webui.common.attributes.WebAttributeHandlerFactory;
/**
* Factory class to instantiate ImageAttributeHandler
*
* @author R. Ledzinski
*/
@Component
class ImageAttributeHandlerFactory implements WebAttributeHandlerFactory
{
private final MessageSource msg;
@Autowired
ImageAttributeHandlerFactory(MessageSource msg)
{
this.msg = msg;
}
@Override
public String getSupportedSyntaxId()
{
return ImageAttributeSyntax.ID;
}
@Override
public AttributeSyntaxEditor<UnityImage> getSyntaxEditorComponent(AttributeValueSyntax<?> initialValue)
{
return new BaseImageSyntaxEditor<>((ImageAttributeSyntax) initialValue, ImageAttributeSyntax::new, msg);
}
@Override
public WebAttributeHandler createInstance(AttributeValueSyntax<?> syntax)
{
return new UnityImageAttributeHandler(msg, (ImageAttributeSyntax) syntax);
}
}
|
3e190b2f96a382b799ee8d3669134887d2670f5a | 739 | java | Java | client/src/main/java/me/retrodaredevil/solarthing/config/options/RequestProgramOptionsBase.java | compscirunner/solarthing | 1a3c65fc04d329b5dd732112d565e217a0103ae4 | [
"MIT"
] | 1 | 2021-02-15T04:11:13.000Z | 2021-02-15T04:11:13.000Z | client/src/main/java/me/retrodaredevil/solarthing/config/options/RequestProgramOptionsBase.java | compscirunner/solarthing | 1a3c65fc04d329b5dd732112d565e217a0103ae4 | [
"MIT"
] | null | null | null | client/src/main/java/me/retrodaredevil/solarthing/config/options/RequestProgramOptionsBase.java | compscirunner/solarthing | 1a3c65fc04d329b5dd732112d565e217a0103ae4 | [
"MIT"
] | null | null | null | 28.423077 | 109 | 0.806495 | 10,649 | package me.retrodaredevil.solarthing.config.options;
import com.fasterxml.jackson.annotation.JsonProperty;
public abstract class RequestProgramOptionsBase extends PacketHandlingOptionBase implements AnalyticsOption {
@JsonProperty(AnalyticsOption.PROPERTY_NAME)
private boolean isAnalyticsEnabled = AnalyticsOption.DEFAULT_IS_ANALYTICS_ENABLED;
@JsonProperty("period")
private float periodSeconds = 5.0f;
@JsonProperty("minimum_wait")
private float minimumWaitSeconds = 1.0f;
@Override
public boolean isAnalyticsOptionEnabled() {
return isAnalyticsEnabled;
}
public long getPeriod() {
return Math.round(periodSeconds * 1000.0f);
}
public long getMinimumWait() {
return Math.round(minimumWaitSeconds * 1000.0f);
}
}
|
3e190b7bff8b53e1fe37e7163d31db6ac143cad4 | 7,180 | java | Java | si-onem2m-src/IITP_IoT_2_7/src/main/java/net/herit/iot/onem2m/resource/AllJoynMethodCall.java | uguraba/SI | 9e0f89a7413c351b2f739b1ee8ae2687c04d5ec1 | [
"BSD-2-Clause"
] | 47 | 2015-12-31T07:10:44.000Z | 2021-12-15T13:31:00.000Z | si-onem2m-src/IITP_IoT_2_7/src/main/java/net/herit/iot/onem2m/resource/AllJoynMethodCall.java | uguraba/SI | 9e0f89a7413c351b2f739b1ee8ae2687c04d5ec1 | [
"BSD-2-Clause"
] | 6 | 2016-01-27T03:30:46.000Z | 2020-11-24T11:48:26.000Z | si-onem2m-src/IITP_IoT_2_7/src/main/java/net/herit/iot/onem2m/resource/AllJoynMethodCall.java | uguraba/SI | 9e0f89a7413c351b2f739b1ee8ae2687c04d5ec1 | [
"BSD-2-Clause"
] | 31 | 2016-01-11T12:35:34.000Z | 2020-02-20T13:12:21.000Z | 29.547325 | 130 | 0.627855 | 10,650 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2016.10.07 at 09:56:03 AM KST
//
package net.herit.iot.onem2m.resource;
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.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import net.herit.iot.message.onem2m.OneM2mRequest.OPERATION;
import net.herit.iot.message.onem2m.OneM2mResponse.RESPONSE_STATUS;
import net.herit.iot.onem2m.core.util.OneM2MException;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <extension base="{http://www.onem2m.org/xml/protocols}flexContainerResource">
* <sequence>
* <element name="input" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="callStatus" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="output" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <choice minOccurs="0">
* <element name="childResource" type="{http://www.onem2m.org/xml/protocols}childResourceRef" maxOccurs="unbounded"/>
* <choice maxOccurs="unbounded" minOccurs="0">
* <element ref="{http://www.onem2m.org/xml/protocols}semanticDescriptor"/>
* <element ref="{http://www.onem2m.org/xml/protocols}subscription"/>
* </choice>
* </choice>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"input",
"callStatus",
"output",
"childResource",
"semanticDescriptorOrSubscription"
})
@XmlRootElement(name = Naming.ALLJOYNMETHODCALL_SN)
public class AllJoynMethodCall
extends FlexContainerResource
{
@XmlElement(name = Naming.INPUT_SN)
protected String input;
@XmlElement(name = Naming.CALLSTATUS_SN)
protected String callStatus;
@XmlElement(name = Naming.OUTPUT_SN)
protected String output;
@XmlElement(name = Naming.CHILDRESOURCE_SN)
protected List<ChildResourceRef> childResource;
@XmlElements({
@XmlElement(name = "semanticDescriptor", namespace = "http://www.onem2m.org/xml/protocols", type = SemanticDescriptor.class),
@XmlElement(name = "subscription", namespace = "http://www.onem2m.org/xml/protocols", type = Subscription.class)
})
protected List<RegularResource> semanticDescriptorOrSubscription;
/**
* Gets the value of the input property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInput() {
return input;
}
/**
* Sets the value of the input property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInput(String value) {
this.input = value;
}
/**
* Gets the value of the callStatus property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCallStatus() {
return callStatus;
}
/**
* Sets the value of the callStatus property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCallStatus(String value) {
this.callStatus = value;
}
/**
* Gets the value of the output property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOutput() {
return output;
}
/**
* Sets the value of the output property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOutput(String value) {
this.output = value;
}
/**
* Gets the value of the childResource 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 childResource property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getChildResource().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ChildResourceRef }
*
*
*/
public List<ChildResourceRef> getChildResource() {
// if (childResource == null) {
// childResource = new ArrayList<ChildResourceRef>();
// }
return this.childResource;
}
public void addChildResource(ChildResourceRef value) {
if (childResource == null) {
childResource = new ArrayList<ChildResourceRef>();
}
this.childResource.add(value);
}
/**
* Gets the value of the semanticDescriptorOrSubscription 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 semanticDescriptorOrSubscription property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSemanticDescriptorOrSubscription().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SemanticDescriptor }
* {@link Subscription }
*
*
*/
public List<RegularResource> getSemanticDescriptorOrSubscription() {
// if (semanticDescriptorOrSubscription == null) {
// semanticDescriptorOrSubscription = new ArrayList<RegularResource>();
// }
return this.semanticDescriptorOrSubscription;
}
public void addSemanticDescriptorOrSubscription(RegularResource value) {
if (semanticDescriptorOrSubscription == null) {
semanticDescriptorOrSubscription = new ArrayList<RegularResource>();
}
this.semanticDescriptorOrSubscription.add(value);
}
// added in CDT-2.7.0
public void validate(OPERATION operation) throws OneM2MException {
super.validate(operation);
if (operation.equals(OPERATION.UPDATE)) { // CREATE 요청에 대한 데이터 유효성 체크
if (this.input != null) {
throw new OneM2MException(RESPONSE_STATUS.INVALID_ARGUMENTS, "input is NP on UPDATE");
}
}
}
}
|
3e190bcb5a060f53c62f75f14370378809472a4f | 1,547 | java | Java | src/main/java/com/github/dexecutor/core/graph/LevelOrderTraversar.java | lizu18xz/dexecutor-core | 4db5cce0513007a3c495f4afffab8fbe07cf1a79 | [
"Apache-2.0"
] | 243 | 2016-09-15T07:04:16.000Z | 2022-03-28T08:05:03.000Z | src/main/java/com/github/dexecutor/core/graph/LevelOrderTraversar.java | ErShakirAnsari/dexecutor-core | f23c2e7008ad7ff72ca12005cc6e71573c79a3f8 | [
"Apache-2.0"
] | 29 | 2017-05-11T04:47:28.000Z | 2021-05-25T07:35:57.000Z | src/main/java/com/github/dexecutor/core/graph/LevelOrderTraversar.java | ErShakirAnsari/dexecutor-core | f23c2e7008ad7ff72ca12005cc6e71573c79a3f8 | [
"Apache-2.0"
] | 65 | 2016-09-16T18:28:26.000Z | 2022-03-28T08:28:43.000Z | 34.377778 | 83 | 0.698125 | 10,651 | /*
* 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.github.dexecutor.core.graph;
import java.util.List;
/**
* A Traversar which does level order traversal of the given graph
*
* @author Nadeem Mohammad
*
* @param <T>
* Type of Node/Task ID
* @param <R>
* Type of Node/Task result
*/
public class LevelOrderTraversar<T, R> extends BaseTraversar<T, R> {
@Override
public void traverse(final Dag<T, R> graph, final TraversarAction<T, R> action) {
List<List<List<Node<T, R>>>> levelOrderOfGraphs = traverseLevelOrder(graph);
int path = 0;
for (List<List<Node<T, R>>> levelOrderOfGraph : levelOrderOfGraphs) {
action.onNewPath(path);
traversePath(levelOrderOfGraph, action);
path++;
}
}
}
|
3e190be20564c92ad5eb0cfb377651c560c13da1 | 11,785 | java | Java | src/main/java/com/jcabi/github/Repos.java | zygm0nt/jcabi-github | 9250222a2c66ecb39e280319dd2744fc210845e2 | [
"BSD-3-Clause"
] | 3 | 2015-08-05T02:28:43.000Z | 2015-11-07T12:04:57.000Z | src/main/java/com/jcabi/github/Repos.java | zygm0nt/jcabi-github | 9250222a2c66ecb39e280319dd2744fc210845e2 | [
"BSD-3-Clause"
] | 18 | 2015-06-30T00:05:35.000Z | 2015-07-28T07:16:52.000Z | src/main/java/com/jcabi/github/Repos.java | cvrebert/typed-github | c0cdeb36d376159b74918a9c91fa8e6ffcbd54a2 | [
"BSD-3-Clause"
] | null | null | null | 33.765043 | 122 | 0.579515 | 10,652 | /**
* Copyright (c) 2013-2015, jcabi.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) 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. 3) Neither the name of the jcabi.com 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 com.jcabi.github;
import com.google.common.base.Optional;
import com.jcabi.aspects.Immutable;
import com.jcabi.aspects.Loggable;
import java.io.IOException;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
* Github Repo API.
*
* @author Yegor Bugayenko (nnheo@example.com)
* @version $Id: 3e190be20564c92ad5eb0cfb377651c560c13da1 $
* @since 0.5
* @see <a href="http://developer.github.com/v3/repos/">Repos API</a>
*/
@SuppressWarnings("PMD.TooManyMethods")
@Immutable
public interface Repos {
/**
* Get its owner.
* @return Github
*/
@NotNull(message = "github is never NULL")
Github github();
//byte[]
/**
* Create repository.
* @param settings Settings to use for creating the new repository
* @return Repository
* @throws IOException If there is any I/O problem
* @since 0.5
* @see <a href="http://developer.github.com/v3/repos/#create">Create Repository</a>
*/
@NotNull(message = "repository is never NULL")
Repo create(@NotNull(message = "new repo settings can't be NULL")
RepoCreate settings)
throws IOException;
/**
* Get repository by name.
* @param coords Repository name in "user/repo" format
* @return Repository
* @see <a href="http://developer.github.com/v3/repos/#get">Get Repository</a>
*/
@NotNull(message = "repository is never NULL")
Repo get(@NotNull(message = "coordinates can't be NULL")
Coordinates coords);
/**
* Remove repository by name.
*
* <p>Note: Deleting a repository requires admin access.
* If OAuth is used, the delete_repo scope is required.
*
* @param coords Repository name in "user/repo" format
* @throws IOException If there is any I/O problem
* @see <a href="http://developer.github.com/v3/repos/#delete-a-repository">Delete a Repository</a>
*/
void remove(@NotNull(message = "coordinates can't be NULL")
Coordinates coords) throws IOException;
/**
* Iterate all public repos, starting with the one you've seen already.
* @param identifier The integer ID of the last Repo that you’ve seen.
* @return Iterator of repo
* @see <a href="https://developer.github.com/v3/repos/#list-all-public-repositories">List all public repositories</a>
*/
@NotNull(message = "iterable is never NULL")
Iterable<Repo> iterate(
@NotNull(message = "identifier can't be NULL") String identifier
);
/**
* Settings to use when creating a new GitHub repository.
*
* @author Chris Rebert (dycjh@example.com)
* @version $Id: 3e190be20564c92ad5eb0cfb377651c560c13da1 $
* @since 0.24
* @see <a href="https://developer.github.com/v3/repos/#create">Create Repo API</a>
* @todo #1095:30m Add the ability to set the other parameters of
* the repo creation API (has_issues, has_wiki, has_downloads,
* team_id, gitignore_template, license_template).
*/
@SuppressWarnings("PMD.TooManyMethods")
@ToString
@Loggable(Loggable.DEBUG)
@EqualsAndHashCode(of = { "nam", "priv", "descr", "home", "init" })
final class RepoCreate implements JsonReadable {
/**
* Name of the new repo.
*/
private final transient String nam;
/**
* Privateness of the new repo.
*/
private final transient boolean priv;
/**
* Description of the new repo.
*/
private final transient String descr;
/**
* Homepage of the new repo.
*/
private final transient String home;
/**
* Auto-init the new repo?
*/
private final transient Optional<Boolean> init;
/**
* Public ctor.
* @param nme Name of the new repository. Cannot be empty.
* @param prvt Will the new repo be private?
* If not, then it will be public.
*/
public RepoCreate(final String nme, final boolean prvt) {
this(nme, prvt, "", "", Optional.<Boolean>absent());
}
/**
* Private ctor.
* @param nme Name of the new repo. Cannot be empty.
* @param prvt Will the new repo be private?
* If not, then it will be public.
* @param desc Description of the new repo
* @param page Homepage of the new repo
* @param auto Auto-init the new repo?
* @checkstyle ParameterNumberCheck (7 lines)
*/
private RepoCreate(
@NotNull(message = "name can't be NULL") final String nme,
final boolean prvt,
@NotNull(message = "description can't be NULL") final String desc,
@NotNull(message = "homepage can't be NULL") final String page,
@NotNull(message = "optional itself can't be NULL")
final Optional<Boolean> auto) {
if (nme.isEmpty()) {
throw new IllegalArgumentException("Name cannot be empty!");
}
this.nam = nme;
this.priv = prvt;
this.descr = desc;
this.home = page;
this.init = auto;
}
/**
* Name of the new repo.
* @return Name
*/
@NotNull(message = "name is never NULL")
public String name() {
return this.nam;
}
/**
* Will the new repo be private? If not, then it will be public.
* @return Is this repo private?
*/
public boolean isPrivate() {
return this.priv;
}
/**
* Description of the new repo.
* If it has no description, this is an empty string.
* @return Description
*/
@NotNull(message = "description is never NULL")
public String description() {
return this.descr;
}
/**
* Homepage of the new repo.
* If it has no homepage, this is an empty string.
* @return Homepage
*/
@NotNull(message = "homepage is never NULL")
public String homepage() {
return this.home;
}
/**
* Auto-init the new repo?
* If absent, the GitHub default will be used.
* @return Optional boolean
*/
@NotNull(message = "optional itself is never NULL")
public Optional<Boolean> autoInit() {
return this.init;
}
/**
* Returns a RepoCreate with the given name.
* The name cannot be empty.
* @param nme Name of the new repo
* @return RepoCreate
*/
@NotNull(message = "renamed settings is never NULL")
public RepoCreate withName(
@NotNull(message = "name can't be NULL") final String nme
) {
return new RepoCreate(
nme,
this.priv,
this.descr,
this.home,
this.init
);
}
/**
* Returns a RepoCreate with the given privacy.
* @param privacy Privateness of the new repo
* @return RepoCreate
*/
@NotNull(message = "new repo settings is never NULL")
public RepoCreate withPrivacy(final boolean privacy) {
return new RepoCreate(
this.nam,
privacy,
this.descr,
this.home,
this.init
);
}
/**
* Returns a RepoCreate with the given description.
* @param desc Description
* @return RepoCreate
*/
@NotNull(message = "adjusted settings is never NULL")
public RepoCreate withDescription(
@NotNull(message = "description can't be NULL") final String desc
) {
return new RepoCreate(
this.nam,
this.priv,
desc,
this.home,
this.init
);
}
/**
* Returns a RepoCreate with the given homepage.
* @param page Homepage URL
* @return RepoCreate
*/
@NotNull(message = "changed settings is never NULL")
public RepoCreate withHomepage(
@NotNull(message = "homepage can't be NULL") final String page
) {
return new RepoCreate(
this.nam,
this.priv,
this.descr,
page,
this.init
);
}
/**
* Returns a RepoCreate with the given auto-init enabledness.
* @param auto Auto-init the new repo?
* @return RepoCreate
*/
@NotNull(message = "modified settings is never NULL")
public RepoCreate withAutoInit(final Optional<Boolean> auto) {
return new RepoCreate(
this.nam,
this.priv,
this.descr,
this.home,
auto
);
}
/**
* Returns a RepoCreate with the given auto-init enabledness.
* @param auto Auto-init the new repo?
* @return RepoCreate
*/
@NotNull(message = "new settings is never NULL")
public RepoCreate withAutoInit(final boolean auto) {
return new RepoCreate(
this.nam,
this.priv,
this.descr,
this.home,
Optional.of(auto)
);
}
@Override
@NotNull(message = "JSON is never NULL")
public JsonObject json() {
JsonObjectBuilder builder = Json.createObjectBuilder()
.add("name", this.nam)
.add("description", this.descr)
.add("homepage", this.home)
.add("private", this.priv);
if (this.init.isPresent()) {
builder = builder.add("auto_init", this.init.get());
}
return builder.build();
}
}
}
|
3e190c6e8d0ac5fe122158b218ac3edfd332300c | 261 | java | Java | Aplicaciones/AgenciaViajesWT/src/acceso/IServiciosRegiones.java | alexander98in/Proyecto_AgenciaViajes | 3e061464fd3a1f605c3824ff0e9f465a8360029d | [
"MIT"
] | null | null | null | Aplicaciones/AgenciaViajesWT/src/acceso/IServiciosRegiones.java | alexander98in/Proyecto_AgenciaViajes | 3e061464fd3a1f605c3824ff0e9f465a8360029d | [
"MIT"
] | null | null | null | Aplicaciones/AgenciaViajesWT/src/acceso/IServiciosRegiones.java | alexander98in/Proyecto_AgenciaViajes | 3e061464fd3a1f605c3824ff0e9f465a8360029d | [
"MIT"
] | null | null | null | 18.642857 | 58 | 0.727969 | 10,653 | package acceso;
/**
*
* @author Alexander Inagan
*/
public interface IServiciosRegiones {
public String consultarRegiones();
public String consultarPaises(String nombre_region);
public String consultarCiudades(String nombre_ciudad);
}
|
3e190ca37fae27faea5988687088b863f1d683e0 | 7,681 | java | Java | src/test/java/uk/nhs/hee/trainee/details/api/PlacementResourceTest.java | Health-Education-England/tis-trainee-details | 60a82782dfd5a1a7b56e74a5d498446441771932 | [
"MIT"
] | null | null | null | src/test/java/uk/nhs/hee/trainee/details/api/PlacementResourceTest.java | Health-Education-England/tis-trainee-details | 60a82782dfd5a1a7b56e74a5d498446441771932 | [
"MIT"
] | 148 | 2020-03-24T13:55:45.000Z | 2022-03-28T06:05:27.000Z | src/test/java/uk/nhs/hee/trainee/details/api/PlacementResourceTest.java | Health-Education-England/tis-trainee-details | 60a82782dfd5a1a7b56e74a5d498446441771932 | [
"MIT"
] | null | null | null | 41.518919 | 100 | 0.748861 | 10,654 | /*
* The MIT License (MIT)
*
* Copyright 2021 Crown Copyright (Health Education England)
*
* 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 uk.nhs.hee.trainee.details.api;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.LocalDate;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mapstruct.factory.Mappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import uk.nhs.hee.trainee.details.dto.PlacementDto;
import uk.nhs.hee.trainee.details.dto.enumeration.Status;
import uk.nhs.hee.trainee.details.mapper.PlacementMapper;
import uk.nhs.hee.trainee.details.model.Placement;
import uk.nhs.hee.trainee.details.service.PlacementService;
@ContextConfiguration(classes = {PlacementMapper.class})
@ExtendWith(SpringExtension.class)
@WebMvcTest(PlacementResource.class)
class PlacementResourceTest {
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private ObjectMapper mapper;
private MockMvc mockMvc;
@MockBean
private PlacementService service;
@BeforeEach
void setUp() {
PlacementMapper mapper = Mappers.getMapper(PlacementMapper.class);
PlacementResource resource = new PlacementResource(service, mapper);
mockMvc = MockMvcBuilders.standaloneSetup(resource)
.setMessageConverters(jacksonMessageConverter)
.build();
}
@Test
void shouldReturnBadRequestWhenIdIsNull() throws Exception {
when(service.updatePlacementForTrainee("40", new Placement())).thenReturn(Optional.empty());
mockMvc.perform(patch("/api/placement/{traineeTisId}", 40)
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsBytes(new PlacementDto())))
.andExpect(status().isBadRequest());
}
@Test
void shouldReturnNotFoundStatusWhenTraineeNotFound() throws Exception {
when(service.updatePlacementForTrainee("40", new Placement())).thenReturn(Optional.empty());
PlacementDto dto = new PlacementDto();
dto.setTisId("tisIdValue");
mockMvc.perform(patch("/api/placement/{traineeTisId}", 40)
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsBytes(dto)))
.andExpect(status().isNotFound())
.andExpect(status().reason("Trainee not found."));
}
@Test
void shouldUpdatePlacementWhenTraineeFound() throws Exception {
LocalDate start = LocalDate.now();
LocalDate end = start.plusYears(1);
Placement placement = new Placement();
placement.setTisId("tisIdValue");
placement.setStartDate(start);
placement.setEndDate(end);
placement.setSite("siteValue");
placement.setSiteLocation("siteLocationValue");
placement.setGrade("gradeValue");
placement.setSpecialty("specialtyValue");
placement.setPlacementType("placementTypeValue");
placement.setStatus(Status.CURRENT);
when(service.updatePlacementForTrainee(eq("40"), any(Placement.class)))
.thenReturn(Optional.of(placement));
PlacementDto dto = new PlacementDto();
dto.setTisId("tisIdValue");
mockMvc.perform(patch("/api/placement/{traineeTisId}", 40)
.contentType(MediaType.APPLICATION_JSON)
.content(mapper.writeValueAsBytes(dto)))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.tisId").value(is("tisIdValue")))
.andExpect(jsonPath("$.startDate").value(is(start.toString())))
.andExpect(jsonPath("$.endDate").value(is(end.toString())))
.andExpect(jsonPath("$.site").value(is("siteValue")))
.andExpect(jsonPath("$.siteLocation").value(is("siteLocationValue")))
.andExpect(jsonPath("$.grade").value(is("gradeValue")))
.andExpect(jsonPath("$.specialty").value(is("specialtyValue")))
.andExpect(jsonPath("$.placementType").value(is("placementTypeValue")))
.andExpect(jsonPath("$.status").value(is("CURRENT")));
}
@Test
void shouldDeletePlacementWhenTraineeFound() throws Exception {
when(service
.deletePlacementForTrainee("40","1"))
.thenReturn(true);
MvcResult result = mockMvc.perform(
delete("/api/placement/{traineeTisId}/{placementTisId}", 40, 1)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
Boolean resultBoolean = Boolean.parseBoolean(result.getResponse().getContentAsString());
assertThat("Unexpected result.", resultBoolean, is(true));
}
@Test
void shouldNotDeletePlacementWhenTraineeOrPlacementNotFound() throws Exception {
when(service
.deletePlacementForTrainee("40", "1"))
.thenReturn(false);
mockMvc.perform(
delete("/api/placement/{traineeTisId}/{placementTisId}", 40, 1)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound());
}
@Test
void shouldThrowBadRequestWhenDeletePlacementException() throws Exception {
when(service
.deletePlacementForTrainee("triggersError", "1"))
.thenThrow(new IllegalArgumentException());
mockMvc.perform(
delete("/api/placement/{traineeTisId}/{placementTisId}", "triggersError", "1")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest());
}
}
|
3e190cff3b77c1e570eaeac3082539e200907893 | 902 | java | Java | java_spring_boot_swagger/src/main/java/com/example/appserv/ProjectAppServ.java | chemaar/app_skeleton | e53d67a16ae934a9f19b2c1571c94daf2c2b27ee | [
"Apache-2.0"
] | 1 | 2020-11-11T10:48:29.000Z | 2020-11-11T10:48:29.000Z | java_spring_boot_swagger/src/main/java/com/example/appserv/ProjectAppServ.java | chemaar/app_skeleton | e53d67a16ae934a9f19b2c1571c94daf2c2b27ee | [
"Apache-2.0"
] | null | null | null | java_spring_boot_swagger/src/main/java/com/example/appserv/ProjectAppServ.java | chemaar/app_skeleton | e53d67a16ae934a9f19b2c1571c94daf2c2b27ee | [
"Apache-2.0"
] | null | null | null | 20.044444 | 74 | 0.754989 | 10,655 | package com.example.appserv;
import java.util.Collections;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.example.dao.ProjectDAO;
import com.example.model.Project;
import com.example.model.Repository;
@Component
public class ProjectAppServ {
@Autowired
ProjectDAO projectDAO;
public ProjectAppServ() {
}
public ProjectAppServ(ProjectDAO projectDAO) {
this.projectDAO = projectDAO;
}
public List<Project> listProjects(){
return this.projectDAO.list();
}
public List<Repository> listRepositories(String projectId){
Project project = this.listProjects().stream()
.filter(p -> p.getId().equalsIgnoreCase(projectId)).findFirst().get();
List<Repository> repos = Collections.EMPTY_LIST;
if (project != null) {
repos = project.getRepositories();
}
return repos;
}
}
|
3e190d7657abd83ed5d493139911b181e0edcf21 | 228 | java | Java | src/main/java/com/hrms/dao/IRoleDao.java | jattySu/hrms | b69d7584a480bce0984537e2eb149d898acdf64a | [
"Apache-2.0"
] | 94 | 2015-09-29T08:21:00.000Z | 2022-03-04T14:14:47.000Z | src/main/java/com/hrms/dao/IRoleDao.java | jattySu/hrms | b69d7584a480bce0984537e2eb149d898acdf64a | [
"Apache-2.0"
] | 2 | 2018-01-11T03:18:52.000Z | 2020-02-11T07:38:26.000Z | src/main/java/com/hrms/dao/IRoleDao.java | dreajay/hrms | b69d7584a480bce0984537e2eb149d898acdf64a | [
"Apache-2.0"
] | 97 | 2015-04-03T09:24:44.000Z | 2022-03-02T14:57:06.000Z | 19 | 63 | 0.732456 | 10,656 | package com.hrms.dao;
import java.util.List;
import com.hrms.model.Role;
import com.hrms.model.User;
public interface IRoleDao extends IGenericDao<Role, Integer> {
public List<User> findUsers(Integer roleId);
}
|
3e190f93ad3bf9566121ce622155a1905fdb9a28 | 2,897 | java | Java | core/src/main/java/org/gate/gui/graph/editor/ShadowBorder.java | li-huipu/gate | c2ad6e1685becbcf9d60cd8f925555a7465f62e2 | [
"Apache-2.0"
] | 2 | 2020-03-28T09:22:32.000Z | 2020-07-21T02:38:19.000Z | core/src/main/java/org/gate/gui/graph/editor/ShadowBorder.java | li-huipu/gate | c2ad6e1685becbcf9d60cd8f925555a7465f62e2 | [
"Apache-2.0"
] | 2 | 2021-12-10T01:36:13.000Z | 2021-12-14T21:44:03.000Z | core/src/main/java/org/gate/gui/graph/editor/ShadowBorder.java | li-huipu/gate | c2ad6e1685becbcf9d60cd8f925555a7465f62e2 | [
"Apache-2.0"
] | 1 | 2020-05-01T03:34:04.000Z | 2020-05-01T03:34:04.000Z | 25.412281 | 79 | 0.6738 | 10,657 | /*
* 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.gate.gui.graph.editor;
/*
* Copyright (c) 2001-2005, Gaudenz Alder
*
* All rights reserved.
*
* This file is licensed under the JGraph software license, a deepCopy of which
* will have been provided to you in the file LICENSE at the root of your
* installation directory. If you are unable to locate this file please
* contact JGraph sales for another deepCopy.
*/
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Insets;
import java.io.Serializable;
import javax.swing.border.Border;
/**
* Border with a drop shadow.
*/
public class ShadowBorder implements Border, Serializable
{
/**
*
*/
private static final long serialVersionUID = 6854989457150641240L;
private Insets insets;
public static ShadowBorder sharedInstance = new ShadowBorder();
private ShadowBorder()
{
insets = new Insets(0, 0, 2, 2);
}
public Insets getBorderInsets(Component c)
{
return insets;
}
public boolean isBorderOpaque()
{
return false;
}
public void paintBorder(Component c, Graphics g, int x, int y, int w, int h)
{
// choose which colors we want to use
Color bg = c.getBackground();
if (c.getParent() != null)
{
bg = c.getParent().getBackground();
}
if (bg != null)
{
Color mid = bg.darker();
Color edge = average(mid, bg);
g.setColor(bg);
g.drawLine(0, h - 2, w, h - 2);
g.drawLine(0, h - 1, w, h - 1);
g.drawLine(w - 2, 0, w - 2, h);
g.drawLine(w - 1, 0, w - 1, h);
// draw the drop-shadow
g.setColor(mid);
g.drawLine(1, h - 2, w - 2, h - 2);
g.drawLine(w - 2, 1, w - 2, h - 2);
g.setColor(edge);
g.drawLine(2, h - 1, w - 2, h - 1);
g.drawLine(w - 1, 2, w - 1, h - 2);
}
}
private static Color average(Color c1, Color c2)
{
int red = c1.getRed() + (c2.getRed() - c1.getRed()) / 2;
int green = c1.getGreen() + (c2.getGreen() - c1.getGreen()) / 2;
int blue = c1.getBlue() + (c2.getBlue() - c1.getBlue()) / 2;
return new Color(red, green, blue);
}
public static ShadowBorder getSharedInstance()
{
return sharedInstance;
}
}
|
3e1910d91b638cb1b27c22e8d401a3e1ee3a31a4 | 9,568 | java | Java | src/algorithms/bst/BinaryTree.java | Ohohcakester/Any-Angle-Pathfinding | 7b196baf6b7e8e4892f640b8db82f6cc186867b0 | [
"Unlicense"
] | 125 | 2015-02-21T20:41:47.000Z | 2022-02-28T08:58:04.000Z | src/algorithms/bst/BinaryTree.java | Maxxxel/Any-Angle-Pathfinding | 7b196baf6b7e8e4892f640b8db82f6cc186867b0 | [
"Unlicense"
] | null | null | null | src/algorithms/bst/BinaryTree.java | Maxxxel/Any-Angle-Pathfinding | 7b196baf6b7e8e4892f640b8db82f6cc186867b0 | [
"Unlicense"
] | 26 | 2015-07-03T16:10:23.000Z | 2022-02-05T14:45:15.000Z | 27.181818 | 96 | 0.505644 | 10,658 | package algorithms.bst;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
/**
* Base class for a binary tree that stores type E objects.
* Node is a public class.
*/
public class BinaryTree<E> implements Iterable<E>{
// Data Field
/** The root of the binary tree */
protected Node<E> root;
private class TreeIterator<E> implements Iterator<E> {
private BinaryTree<E> tree;
private Node<E> current;
private Stack<Node<E>> nodeStack;
protected TreeIterator (BinaryTree<E> tree) {
this.tree = tree;
current = null;
nodeStack = new Stack<>();
}
@Override
public boolean hasNext() {
if (current == null)
return root != null;
if (current.right == null)
return !nodeStack.isEmpty();
return true;
}
@Override
public E next() {
if (current == null) {
if (root != null)
current = tree.root;
else
throw new IndexOutOfBoundsException();
// From start, go to far left.
goToFarLeft();
return current.data;
}
else {
if (current.right != null) {
// Has Right Child: go right, then go to far left, pushing lefts into stack.
current = current.right;
goToFarLeft();
return current.data;
}
else {
// Has no Right Child: pop from stack.
current = nodeStack.pop();
return current.data;
}
}
}
private void goToFarLeft() {
while(current.left != null) {
nodeStack.push(current);
current = current.left;
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
public TreeIterator<E> iterator() {
return new TreeIterator<E>(this);
}
/** Construct an empty BinaryTree */
public BinaryTree() {
root = null;
}
/**
* Construct a BinaryTree with a specified root.
* Should only be used by subclasses.
* @param root The node that is the root of the tree.
*/
protected BinaryTree(Node<E> root) {
this.root = root;
}
/**
* Constructs a new binary tree with data in its root,leftTree
* as its left subtree and rightTree as its right subtree.
*/
public BinaryTree(E data, BinaryTree<E> leftTree,
BinaryTree<E> rightTree) {
root = new Node<E>(data);
if (leftTree != null) {
root.left = leftTree.root;
} else {
root.left = null;
}
if (rightTree != null) {
root.right = rightTree.root;
} else {
root.right = null;
}
}
/**
* Return the left subtree.
* @return The left subtree or null if either the root or
* the left subtree is null
*/
public BinaryTree<E> getLeftSubtree() {
if (root != null && root.left != null) {
return new BinaryTree<E>(root.left);
} else {
return null;
}
}
/**
* Return the right sub-tree
* @return the right sub-tree or
* null if either the root or the
* right subtree is null.
*/
public BinaryTree<E> getRightSubtree() {
if (root != null && root.right != null) {
return new BinaryTree<E>(root.right);
} else {
return null;
}
}
/**
* Return the data field of the root
* @return the data field of the root
* or null if the root is null
*/
public E getData() {
if (root != null) {
return root.data;
} else {
return null;
}
}
/**
* Determine whether this tree is a leaf.
* @return true if the root has no children
*/
public boolean isLeaf() {
return (root == null || (root.left == null && root.right == null));
}
public int height() {
return height(root);
}
public int height(Node<E> r) {
if (r == null) return 0;
return 1 + Math.max(height(r.left), height(r.right));
}
public int size() {
return size(root);
}
public int size(Node<E> r) {
if (r == null) return 0;
return 1 + size(r.left) + size(r.right);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
preOrderTraverse(root, 1, sb);
return sb.toString();
}
/**
* Perform a preorder traversal.
* @param node The local root
* @param depth The depth
* @param sb The string buffer to save the output
*/
private void preOrderTraverse(Node<E> node, int depth,
StringBuilder sb) {
for (int i = 1; i < depth; i++) {
sb.append(" ");
}
if (node == null) {
sb.append("null\n");
} else {
sb.append(node.toString());
sb.append("\n");
preOrderTraverse(node.left, depth + 1, sb);
preOrderTraverse(node.right, depth + 1, sb);
}
}
/**
* Method to return the preorder traversal of the binary tree
* as a sequence of strings each separated by a space.
* @return A preorder traversal as a string
*/
public String preorderToString() {
StringBuilder stb = new StringBuilder();
preorderToString(stb, root);
return stb.toString();
}
private void preorderToString(StringBuilder stb, Node<E> root) {
stb.append(root);
if (root.left != null) {
stb.append(" ");
preorderToString(stb, root.left);
}
if (root.right != null) {
stb.append(" ");
preorderToString(stb, root.right);
}
}
/**
* Method to return the postorder traversal of the binary tree
* as a sequence of strings each separated by a space.
* @return A postorder traversal as a string
*/
public String postorderToString() {
StringBuilder stb = new StringBuilder();
postorderToString(stb, root);
return stb.toString();
}
private void postorderToString(StringBuilder stb, Node<E> root) {
if (root.left != null) {
postorderToString(stb, root.left);
stb.append(" ");
}
if (root.right != null) {
postorderToString(stb, root.right);
stb.append(" ");
}
stb.append(root);
}
/**
* A method to display the inorder traversal of a binary tree
* placeing a left parenthesis before each subtree and a right
* parenthesis after each subtree. For example the expression
* tree shown in Figure 6.12 would be represented as
* (((x) + (y)) * ((a) / (b))).
* @return An inorder string representation of the tree
*/
public String inorderToString() {
if (root == null) return "null";
StringBuilder stb = new StringBuilder();
inorderToString(stb, root);
return stb.toString();
}
private void inorderToString(StringBuilder stb, Node<E> root) {
if (root.left != null) {
stb.append("(");
inorderToString(stb, root.left);
stb.append(") ");
}
stb.append(root);
if (root.right != null) {
stb.append(" (");
inorderToString(stb, root.right);
stb.append(")");
}
}
public String levelorderToString() {
StringBuilder stb = new StringBuilder();
levelorderToString(stb, root);
return stb.toString();
}
private void levelorderToString(StringBuilder stb, Node<E> root) {
if (root == null) {
stb.append("An empty tree");
return;
}
Queue<Node<E>> q = new LinkedList<Node<E>>();
q.offer(root);
while (!q.isEmpty()) {
Node<E> curr = q.poll();
stb.append(curr);
stb.append(" ");
if (curr.left != null) {
q.offer(curr.left);
}
if (curr.right != null) {
q.offer(curr.right);
}
}
}
private void levelorderToStringPositions(StringBuilder stb, Node<E> root) {
if (root == null) {
stb.append("An empty tree");
return;
}
Queue<Node<E>> q = new LinkedList<Node<E>>();
Queue<String> strQueue = new LinkedList<>();
q.offer(root);
strQueue.offer("");
while (!q.isEmpty()) {
Node<E> curr = q.poll();
String currPath = strQueue.poll();
stb.append("(");
stb.append(curr);
stb.append(",");
stb.append(currPath);
stb.append(") ");
if (curr.left != null) {
q.offer(curr.left);
strQueue.offer(currPath + "L");
}
if (curr.right != null) {
q.offer(curr.right);
strQueue.offer(currPath + "R");
}
}
}
public boolean isEmpty() {
return root == null;
}
} |
3e1911d567e784faba656f16485275a2d9fb24c7 | 2,071 | java | Java | src/main/java/org/fhir/pojo/Ratio.java | gmai2006/fhir | 8613874a4a93a108c8520f8752155449464deb48 | [
"MIT"
] | 1 | 2018-02-09T05:43:07.000Z | 2018-02-09T05:43:07.000Z | src/main/java/org/fhir/pojo/Ratio.java | gmai2006/fhir | 8613874a4a93a108c8520f8752155449464deb48 | [
"MIT"
] | null | null | null | src/main/java/org/fhir/pojo/Ratio.java | gmai2006/fhir | 8613874a4a93a108c8520f8752155449464deb48 | [
"MIT"
] | null | null | null | 29.585714 | 110 | 0.697731 | 10,659 | /*
* #%L
* FHIR Implementation
* %%
* Copyright (C) 2018 DataScience 9 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.
* #L%
*/
/**
* This code is 100% AUTO generated. Please do not modify it DIRECTLY
* If you need new features or function or changes please update the templates
* then submit the template through our web interface.
*/
package org.fhir.pojo;
import com.google.gson.GsonBuilder;
import com.fasterxml.jackson.annotation.JsonInclude;
/**
* "A relationship of two Quantity values - expressed as a numerator and a denominator."
* generated on 07/14/2018
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Ratio extends Element {
/**
* Description: "The value of the numerator."
*/
protected Quantity numerator;
/**
* Description: "The value of the denominator."
*/
protected Quantity denominator;
public Ratio() {}
public void setNumerator( Quantity value) {
this.numerator = value;
}
public Quantity getNumerator() {
return this.numerator;
}
public void setDenominator( Quantity value) {
this.denominator = value;
}
public Quantity getDenominator() {
return this.denominator;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("[Ratio]:" + "\n");
if(this.numerator != null) builder.append("numerator" + "->" + this.numerator.toString() + "\n");
if(this.denominator != null) builder.append("denominator" + "->" + this.denominator.toString() + "\n"); ;
return builder.toString();
}
} |
3e19122976ca57148b720f8b63ed0dedeb7345de | 1,299 | java | Java | src/main/java/org/ga4gh/registry/annotation/openapi/ApiResponseNotFound.java | soumyadip007/ga4gh-registry | bf90cdbd875c5576943a7dff21ce321a106fbea5 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/ga4gh/registry/annotation/openapi/ApiResponseNotFound.java | soumyadip007/ga4gh-registry | bf90cdbd875c5576943a7dff21ce321a106fbea5 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/ga4gh/registry/annotation/openapi/ApiResponseNotFound.java | soumyadip007/ga4gh-registry | bf90cdbd875c5576943a7dff21ce321a106fbea5 | [
"Apache-2.0"
] | null | null | null | 35.108108 | 67 | 0.712086 | 10,660 | package org.ga4gh.registry.annotation.openapi;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.ga4gh.registry.example.Example;
import org.ga4gh.registry.model.RegistryError;
import org.ga4gh.registry.constant.HttpStatus;
import org.ga4gh.registry.constant.HttpStatusDescription;
import org.springframework.http.MediaType;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@ApiResponse(
responseCode = HttpStatus.NOT_FOUND,
description = HttpStatusDescription.NOT_FOUND,
content = {
@Content(
mediaType = MediaType.APPLICATION_JSON_UTF8_VALUE,
schema = @Schema(implementation = RegistryError.class),
examples = {
@ExampleObject(
name = "Not Found Error",
summary = "Not Found Error",
value = Example.NOT_FOUND_ERROR
)
}
)
}
)
public @interface ApiResponseNotFound {}
|
3e1912a14cb0819d24077171daf9410e63f721ba | 3,447 | java | Java | app/src/main/java/com/jidcoo/android/widgettest/custom/CustomViewStyleConfigurator.java | Jidcoo/CommentView | 26df8f9903d0dd664bc975945b17faba2b3fba73 | [
"Apache-2.0"
] | 42 | 2020-07-15T02:06:03.000Z | 2022-03-21T16:44:19.000Z | app/src/main/java/com/jidcoo/android/widgettest/custom/CustomViewStyleConfigurator.java | latemb/CommentView | 26df8f9903d0dd664bc975945b17faba2b3fba73 | [
"Apache-2.0"
] | 6 | 2020-07-16T08:36:05.000Z | 2021-12-15T02:10:41.000Z | app/src/main/java/com/jidcoo/android/widgettest/custom/CustomViewStyleConfigurator.java | latemb/CommentView | 26df8f9903d0dd664bc975945b17faba2b3fba73 | [
"Apache-2.0"
] | 9 | 2020-07-15T01:10:08.000Z | 2022-03-04T10:00:15.000Z | 42.036585 | 75 | 0.602263 | 10,661 | package com.jidcoo.android.widgettest.custom;
import android.content.Context;
import android.graphics.Typeface;
import com.jidcoo.android.widget.commentview.utils.ViewUtil;
import com.jidcoo.android.widget.commentview.view.ViewStyleConfigurator;
public class CustomViewStyleConfigurator extends ViewStyleConfigurator {
public CustomViewStyleConfigurator(Context context) {
/**
* 下拉刷新控件颜色
*/
refreshViewColor = "#D81B60";
//*********//回复加载更多控件样式//*************//
//Part1//
lmv_showText = "展开更多回复";
lmv_textSize = 14;
lmv_textColor = "#D81B60";
lmv_textStyle = Typeface.defaultFromStyle(Typeface.NORMAL);
//Part2//
lmv_loading_showText = "加载中";
lmv_loading_textSize = 14;
lmv_loading_textColor = "#666666";
lmv_loading_textStyle = Typeface.defaultFromStyle(Typeface.NORMAL);
lmv_loading_progressBarColor = "#666666";
lmv_loading_progressBarSize = ViewUtil.dpToPx(14, context);
//Part3//
lmv_adjustMargins = true;
lmv_adjustMarginsLeft = ViewUtil.dpToPx(52, context);//dp
lmv_adjustMarginsTop = ViewUtil.dpToPx(5, context);//dp
lmv_adjustMarginsRight = 0;//dp
lmv_adjustMarginsBottom = ViewUtil.dpToPx(5, context);//dp
//*********//回复加载更多控件样式//*************//
//*********//分割线总样式//*************//
dividerColor = "#00000000";
dividerHeight = ViewUtil.dpToPx(1, context);//dp
//*********//分割线总样式//*************//
//*********//回复Item最后一项的下划线//*************//
// isDrawChildDivider = false;
// c_divider_adjustMargins = true;
// c_divider_adjustMarginsLeft = ViewUtil.dpToPx(88, context);//dp
// c_divider_adjustMarginsTop = ViewUtil.dpToPx(5, context);//dp
// c_divider_adjustMarginsRight = 0;//dp
// c_divider_adjustMarginsBottom = ViewUtil.dpToPx(5, context);//dp
// //*********//回复Item最后一项的下划线//*************//
// //*********//评论Item的分割线//*************//
// f_divider_adjustMargins = false;
// f_divider_adjustMarginsLeft = 0;//dp
// f_divider_adjustMarginsTop = 0;//dp
// f_divider_adjustMarginsRight = 0;//dp
// f_divider_adjustMarginsBottom = 0;//dp
//*********//评论Item的分割线//*************//
//*********//底部上拉加载更多圆形ProgressBar的大小和颜色//*************//
lm_footerProgressBarSize = ViewUtil.dpToPx(20, context);//dp
lm_footerProgressBarColor = "#666666";
lm_footerProgressBar_adjustMargins = false;
lm_footerProgressBar_adjustMarginsLeft = 0;//dp
lm_footerProgressBar_adjustMarginsTop = 0;//dp
lm_footerProgressBar_adjustMarginsRight = 0;//dp
lm_footerProgressBar_adjustMarginsBottom = 0;//dp
//*********//底部上拉加载更多圆形ProgressBar的大小和颜色//*************//
//*********//底部上拉加载更多完成后的textView//*************//
//文本,颜色、大小、样式、边距
lm_footer_text = "到底了(⊙o⊙)!";
lm_footer_textColor = "#c3c8cb";
lm_footer_textSize = 14;
lm_footer_textStyle = Typeface.defaultFromStyle(Typeface.NORMAL);
lm_footer_text_adjustMargins = false;
lm_footer_text_adjustMarginsLeft = 0;//dp
lm_footer_text_adjustMarginsTop = 0;//dp
lm_footer_text_adjustMarginsRight = 0;//dp
lm_footer_text_adjustMarginsBottom = 0;//dp
//*********//底部上拉加载更多完成后的textView//*************//
}
}
|
3e1912c3a7350290e12d09fa177a2b26bc55eb9c | 2,306 | java | Java | salesdashboard/src/main/java/com/example/util/Util.java | hisamith/AFDemo | bb8cf63a574b13b84691ab2cc5dd87f96fb5f1b0 | [
"Apache-2.0"
] | null | null | null | salesdashboard/src/main/java/com/example/util/Util.java | hisamith/AFDemo | bb8cf63a574b13b84691ab2cc5dd87f96fb5f1b0 | [
"Apache-2.0"
] | null | null | null | salesdashboard/src/main/java/com/example/util/Util.java | hisamith/AFDemo | bb8cf63a574b13b84691ab2cc5dd87f96fb5f1b0 | [
"Apache-2.0"
] | null | null | null | 41.178571 | 111 | 0.635299 | 10,662 | package com.example.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.RegistryType;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
/**
* Created by samith on 3/4/16.
*/
public class Util {
private static Log log = LogFactory.getLog(Util.class);
private static String getResource(String resourcePath) throws Exception {
String propValue = null;
CarbonContext cCtx = CarbonContext.getThreadLocalCarbonContext();
Registry registry = (Registry) cCtx.getRegistry(RegistryType.SYSTEM_GOVERNANCE);
try{
if (registry.resourceExists(resourcePath)) {
Resource resource = registry.get(resourcePath);
if (resource.getContent() != null) {
if (resource.getContent() instanceof String) {
propValue = (String) resource.getContent();
} else if (resource.getContent() instanceof byte[]) {
propValue = new String((byte[]) resource.getContent());
}
}
} else {
log.warn("Resource does not exists in registry path : "+resourcePath);
}
}catch(RegistryException e) {
log.error("Error while getting resource: "+resourcePath , e);
throw new Exception("Error while getting resource: "+resourcePath,e);
}
return propValue;
}
public static String getExternalApiValue(String propName) throws Exception {
String resourcePath = "/dependencies/" +
ConfigUtil.getPropertyValue(Constants.CONFIG_APP_KEY) + "/" +
ConfigUtil.getPropertyValue(Constants.CONFIG_EXTERNAL_API_NAME) + "/" + propName;
return getResource(resourcePath);
}
public static String getResourceFromRegistry(String propName) throws Exception {
String resourcePath = "/dependencies/" +
ConfigUtil.getPropertyValue(Constants.CONFIG_APP_KEY) + "/" + propName;
return getResource(resourcePath);
}
}
|
3e191404594a1209f14765af67a302c1dc2a83cd | 972 | java | Java | _src/Chapter12/Claim/app/src/main/java/com/packtpub/claim/util/MultiOnClickListener.java | paullewallencom/android-978-1-7884-7505-1 | db4652ca46518f064be6bff30ff5f0b2cee39dbd | [
"Apache-2.0"
] | 16 | 2017-11-25T03:02:46.000Z | 2022-02-01T22:26:16.000Z | _src/Chapter12/Claim/app/src/main/java/com/packtpub/claim/util/MultiOnClickListener.java | paullewallencom/android-978-1-7884-7505-1 | db4652ca46518f064be6bff30ff5f0b2cee39dbd | [
"Apache-2.0"
] | null | null | null | _src/Chapter12/Claim/app/src/main/java/com/packtpub/claim/util/MultiOnClickListener.java | paullewallencom/android-978-1-7884-7505-1 | db4652ca46518f064be6bff30ff5f0b2cee39dbd | [
"Apache-2.0"
] | 10 | 2017-11-25T03:44:24.000Z | 2019-03-15T06:56:27.000Z | 26.27027 | 86 | 0.695473 | 10,663 | package com.packtpub.claim.util;
import android.view.View;
import java.util.List;
import java.util.Arrays;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Created by jason on 2017/11/07.
*/
public class MultiOnClickListener implements View.OnClickListener {
private final List<View.OnClickListener> listeners = new CopyOnWriteArrayList<>();
public MultiOnClickListener(final View.OnClickListener... listeners) {
this.listeners.addAll(Arrays.asList(listeners));
}
@Override
public void onClick(View v) {
for (final View.OnClickListener listener : listeners) {
listener.onClick(v);
}
}
public void addOnClickListener(final View.OnClickListener listener) {
if (listener == null) return;
listeners.add(listener);
}
public void removeOnClickListener(final View.OnClickListener listener) {
if (listener == null) return;
listeners.remove(listener);
}
} |
3e19144acad06c16b4d4bd31ec2f3b0849288266 | 1,268 | java | Java | admin-workflow/src/main/java/com/ibeetl/starter/workflow/event/TaskPauseEvent.java | ShaolinWang/admin | 1d1d79526d77428594e0052a4cd04b2ef5eca13b | [
"BSD-3-Clause"
] | null | null | null | admin-workflow/src/main/java/com/ibeetl/starter/workflow/event/TaskPauseEvent.java | ShaolinWang/admin | 1d1d79526d77428594e0052a4cd04b2ef5eca13b | [
"BSD-3-Clause"
] | null | null | null | admin-workflow/src/main/java/com/ibeetl/starter/workflow/event/TaskPauseEvent.java | ShaolinWang/admin | 1d1d79526d77428594e0052a4cd04b2ef5eca13b | [
"BSD-3-Clause"
] | null | null | null | 23.054545 | 102 | 0.720032 | 10,664 | package com.ibeetl.starter.workflow.event;
public class TaskPauseEvent {
String taskId;
String taskName;
String taskInsId;
String processKey;
String processName;
String processInsId;
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public String getTaskInsId() {
return taskInsId;
}
public void setTaskInsId(String taskInsId) {
this.taskInsId = taskInsId;
}
public String getProcessKey() {
return processKey;
}
public void setProcessKey(String processKey) {
this.processKey = processKey;
}
public String getProcessName() {
return processName;
}
public void setProcessName(String processName) {
this.processName = processName;
}
public String getProcessInsId() {
return processInsId;
}
public void setProcessInsId(String processInsId) {
this.processInsId = processInsId;
}
@Override
public String toString() {
return "TaskPauseEvent [taskId=" + taskId + ", taskName=" + taskName + ", taskInsId=" + taskInsId
+ ", processKey=" + processKey + ", processName=" + processName + ", processInsId=" + processInsId
+ "]";
}
}
|
3e1914655c3afca9594d3fd5e0c23de8401fcd80 | 31,245 | java | Java | src/main/java/com/cy/core/login/action/LoginAction.java | fanyoucai/cyserver | 9c4192b0ccaecda184315d1ac2f5d3a5da8f4f71 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/cy/core/login/action/LoginAction.java | fanyoucai/cyserver | 9c4192b0ccaecda184315d1ac2f5d3a5da8f4f71 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/cy/core/login/action/LoginAction.java | fanyoucai/cyserver | 9c4192b0ccaecda184315d1ac2f5d3a5da8f4f71 | [
"Apache-2.0"
] | null | null | null | 30.935644 | 124 | 0.646055 | 10,665 | package com.cy.core.login.action;
import java.awt.image.BufferedImage;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import com.cy.common.utils.CacheUtils;
import com.cy.core.log.util.LogUtils;
import com.cy.core.news.service.NewsService;
import com.cy.util.UserUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.beans.factory.annotation.Autowired;
import com.cy.base.action.AdminBaseAction;
import com.cy.base.entity.Message;
import com.cy.base.entity.Tree;
import com.cy.core.login.service.LoginService;
import com.cy.core.resource.entity.Resource;
import com.cy.core.resource.service.ResourceService;
import com.cy.core.role.entity.Role;
import com.cy.core.role.service.RoleService;
import com.cy.core.user.entity.User;
import com.cy.core.user.entity.UserRole;
import com.cy.core.user.service.UserService;
import com.cy.system.Global;
import com.cy.system.SecretUtil;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
@Namespace("/login")
@Action("loginAction")
public class LoginAction extends AdminBaseAction {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(LoginAction.class);
@Autowired
private Producer captchaProducer;
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private LoginService loginService;
@Autowired
private ResourceService resourceService;
@Autowired
private NewsService newsService;
private String userAccount;
private String userPassword;
private String userTelephone ;
private String validCode;
private String smscode;
private String date; //用户主机时间
private String agent; //用户操作系统与浏览器版本
private String userName; //用户姓名
private String userId; //用户ID
private boolean isValidateCodeLogin ;
/**
* 登录
*/
public void doNotNeedSessionAndSecurity_login() {
Message message = new Message();
try {
String code = (String) getRequest().getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
if (code == null) {
message.setMsg("请刷新当前页面");
message.setSuccess(false);
super.writeJson(message);
return;
}
if (isValidateCodeLogin(this.userAccount, false, false) && !code.equalsIgnoreCase(validCode) && !validCode.equals("1")) {
isValidateCodeLogin = isValidateCodeLogin(this.userAccount, true, false) ;
message.setMsg("验证码错误");
message.setObj(isValidateCodeLogin);
message.setSuccess(false);
} else {
/**
*获取用户时不区分系统,并且仅获取用户基本信息
* 更改人:Kent
* 更改时间:2016-07-25 12:11
*/
//User selectUser = userService.selectByUserAccount(this.userAccount);
//查询用户基本信息
User selectUser = userService.selectByUserAccountNoSys(this.userAccount);
if (selectUser != null) {
//设置用户角色信息
String roleIds = "";
String roleNames = "";
for (Role r : selectUser.getRoles()) {
roleIds += r.getRoleId() + ",";
roleNames += r.getRoleName() + ",";
}
if (selectUser.getRoles().size() > 0) {
roleIds = roleIds.substring(0, roleIds.length() - 1);
roleNames = roleNames.substring(0, roleNames.length() - 1);
}
selectUser.setRoleIds(roleIds);
selectUser.setRoleNames(roleNames);
List<Resource> menus = new ArrayList<Resource>();
List<Resource> grantTreeList = new ArrayList<Resource>();
// 校友会角色授权时使用该list
List<Resource> xgrantTreeList = new ArrayList<Resource>();
if (selectUser == null) {
isValidateCodeLogin = isValidateCodeLogin(this.userAccount, true, false) ;
message.setObj(isValidateCodeLogin);
message.setMsg("帐号错误");
message.setSuccess(false);
} else if (StringUtils.isBlank(selectUser.getIsFirstLogin()) || "0".equals(selectUser.getIsFirstLogin().trim())) {
message.init(false, "当前为首次登陆,请修改密码并绑定手机号", selectUser.getUserId(), "201");
} else if (StringUtils.isBlank(selectUser.getTelephone())) {
message.init(false, "绑定手机号不存在,请绑定手机号", selectUser.getUserId(), "201");
} else {
if (!selectUser.getUserPassword().equals(SecretUtil.encryptToSHA(this.userPassword))) {
isValidateCodeLogin = isValidateCodeLogin(this.userAccount, true, false) ;
message.setObj(isValidateCodeLogin);
message.setMsg("密码错误");
message.setSuccess(false);
} else {
String checkFlg = Global.login_smscode_check;
if (checkFlg.equals("1") && !validCode.equals("1")) {
message.setSuccess(true);
// 短信发送
loginService.sendSMSCodeForWebLogin(message, selectUser);
//loginService.sendSMSRemindForWebLogin(message, selectUser, this.agent);
} else {
//更新最后一次登陆时间
selectUser.setLastLoginTime((new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm")).format(new Date()));
userService.update(selectUser);
if (selectUser.getRoles().size() > 0) {
menus = resourceService.getMenuByRoles(selectUser.getRoles());
grantTreeList = resourceService.getResourcesByRoles(selectUser.getRoles());
//xgrantTreeList = grantTreeList;
}
List<Tree> treeList = Lists.newArrayList();
List<Tree> tree = Lists.newArrayList();
if (menus != null && menus.size() > 0) {
for (Resource resource : menus) {
if (resource.getType().equals("菜单")) {
Tree node = new Tree();
node.setId(resource.getId());
node.setPid(resource.getPid());
node.setText(resource.getMenuName());
node.setIconCls(resource.getIconCls());
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("url", resource.getUrl());
node.setAttributes(attributes);
treeList.add(node);
}
}
resourceService.parseTree(tree, treeList);
}
//getSession().put("xgrantTreeList", xgrantTreeList);
getSession().put("grantTreeList", grantTreeList);
getSession().put("menus", menus);
getSession().put("menuTree", tree);
getSession().put("user", selectUser);
message.setSuccess(true);
message.setReturnId("21");
HttpServletRequest request = ServletActionContext.getRequest();
LogUtils.saveLog(request,"登录");
// 登录成功,清楚错误登录计数器
isValidateCodeLogin = isValidateCodeLogin(this.userAccount, false, true) ;
}
// 用户拥有的角色
/*Role hasRole = null;
List<UserRole> hasRoles = selectUser.getUserRoles();
if (hasRoles.size() != 0) {
if (hasRoles.size() == 1) { // 只有一种角色,按原来的程序执行
hasRole = hasRoles.get(0).getRole();
if (hasRole.getSystemAdmin() == 1) {
selectUser.setRole(hasRole);
Map<String, Object> map = GetDictionaryInfo.dictionaryInfoMap;
@SuppressWarnings("unchecked")
List<Resource> allList = (List<Resource>) map.get("resources");
for (Resource resource : allList) {
// 后台菜单
if (resource.getType().equals("菜单") && resource.getFlag() == 0) {
menus.add(resource);
}
if (resource.getFlag() == 0) {
grantTreeList.add(resource);
} else {
xgrantTreeList.add(resource);
}
}
} else {
List<Role> roles2 = roleService.getMenu(hasRole.getRoleId());
// 拥有的菜单
for (Role role : roles2) {
List<Resource> resources = role.getList();
for (Resource resource : resources) {
if (resource.getType().equals("菜单")) {
menus.add(resource);
}
grantTreeList.add(resource);
}
}
}
} else {
List<Role> roles3 = roleService.getMenuByUserRole(hasRoles);
// 拥有的菜单
for (Role role : roles3) {
List<Resource> resources = role.getList();
for (Resource resource : resources) {
if (resource.getType().equals("菜单")) {
menus.add(resource);
}
grantTreeList.add(resource);
}
}
}
removeDuplicate(menus);
removeDuplicate(grantTreeList);
getSession().put("xgrantTreeList", xgrantTreeList);
getSession().put("grantTreeList", grantTreeList);
getSession().put("menus", menus);
getSession().put("user", selectUser);
message.setSuccess(true);
message.setReturnId("21");
}*/
}
}
} else {
isValidateCodeLogin = isValidateCodeLogin(this.userAccount, true, false) ;
message.init(false, "用户不存在!", isValidateCodeLogin);
}
}
} catch (Exception e) {
e.printStackTrace();
}
super.writeJson(message);
}
public void doNotNeedSessionAndSecurity_loginx() {
Message message = new Message();
String code = (String) getRequest().getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
if (code == null) {
message.setMsg("请刷新当前页面");
message.setSuccess(false);
super.writeJson(message);
return;
}
if (!code.equalsIgnoreCase(validCode)) {
message.setMsg("验证码错误");
message.setSuccess(false);
} else {
User selectUser = userService.selectByUserAccount(this.userAccount);
List<Resource> menus = new ArrayList<Resource>();
List<Resource> grantTreeList = new ArrayList<Resource>();
if (selectUser == null) {
message.setMsg("帐号错误");
message.setSuccess(false);
} else {
if (!selectUser.getUserPassword().equals(SecretUtil.encryptToSHA(this.userPassword))) {
message.setMsg("密码错误");
message.setSuccess(false);
} else {
// 用户拥有的角色
Role hasRole = null;
List<UserRole> hasRoles = selectUser.getUserRoles();
if (hasRoles.size() == 1) { // 只有一种角色,按原来的程序执行
hasRole = hasRoles.get(0).getRole();
if (hasRole.getSystemAdmin() == 1) {
//Map<String, Object> map = GetDictionaryInfo.dictionaryInfoMap;
@SuppressWarnings("unchecked")
List<Resource> allList = (List<Resource>) CacheUtils.get("resources");
for (Resource resource : allList) {
// 后台菜单
if (resource.getType().equals("菜单") && resource.getFlag() == 0) {
menus.add(resource);
}
if (resource.getFlag() == 0) {
grantTreeList.add(resource);
}
}
} else {
List<Role> roles2 = roleService.getMenu(hasRole.getRoleId());
// 拥有的菜单
for (Role role : roles2) {
List<Resource> resources = role.getList();
for (Resource resource : resources) {
if ("菜单".equals(resource.getType())) {
menus.add(resource);
}
grantTreeList.add(resource);
}
}
}
removeDuplicate(menus);
removeDuplicate(grantTreeList);
getSession().put("grantTreeList", grantTreeList);
getSession().put("menus", menus);
getSession().put("user", selectUser);
message.setSuccess(true);
HttpServletRequest request = ServletActionContext.getRequest();
LogUtils.saveLog(request,"登录");
}
}
}
}
super.writeJson(message);
}
/**
* 退出
*/
public void doNotNeedSessionAndSecurity_logout() {
Message message = new Message();
getSession().clear();
message.setSuccess(true);
super.writeJson(message);
}
/**
* 修改密码
*/
public void doNotNeedSecurity_updateCurrentPwd() {
Message message = new Message();
try {
String pwd = getRequest().getParameter("pwd");
User user = (User) getSession().get("user");
user.setUserPassword(SecretUtil.encryptToSHA(pwd));
userService.updatePassword(user);
message.setMsg("密码修改成功!");
message.setSuccess(true);
} catch (Exception e) {
logger.error(e, e);
message.setMsg("密码修改失败!");
message.setSuccess(false);
}
super.writeJson(message);
}
/**
* 发送短信验证码
*/
public void doNotNeedSessionAndSecurity_sendSmscode() {
Message message = new Message();
User selectUser = userService.selectByUserAccount(this.userAccount);
if (selectUser == null) {
message.setMsg("帐号错误");
message.setSuccess(false);
} else {
if (!selectUser.getUserPassword().equals(SecretUtil.encryptToSHA(this.userPassword))) {
message.setMsg("密码错误");
message.setSuccess(false);
} else {
message.setSuccess(true);
// 短信发送
loginService.sendSMSCodeForWebLogin(message, selectUser);
}
}
super.writeJson(message);
}
/**
* 获取短信验证码
* 2016-07-29
* QiPengfei
*/
public void doNotNeedSessionAndSecurity_getSmscode() {
Message message = new Message();
if(this.userTelephone != null){
if(isMobile(this.userTelephone)){
message.setSuccess(true);
message.setMsg("验证码发送成功");
// 短信发送
loginService.getSMSCodeByTelephone(message, this.userTelephone);
}else{
message.setMsg("手机号格式不对");
message.setSuccess(false);
}
}else{
message.setMsg("请输入手机号");
message.setSuccess(false);
}
super.writeJson(message);
}
/**
*手机号正则验证
* 2016-07-29
* QiPengfei
*/
public static boolean isMobile(String str) {
Pattern p = null;
Matcher m = null;
boolean b = false;
p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
m = p.matcher(str);
b = m.matches();
return b;
}
public void doNotNeedSessionAndSecurity_loginGo() {
Message message = new Message();
User selectUser = userService.selectByUserAccount(this.userAccount);
if (selectUser == null) {
message.setMsg("帐号错误");
message.setSuccess(false);
} else {
if (!selectUser.getUserPassword().equals(SecretUtil.encryptToSHA(this.userPassword))) {
message.setMsg("密码错误");
message.setSuccess(false);
} else {
//验证手机验证码的正确性
boolean checkRs = loginService.checkSMSCode(message, selectUser.getTelephone(), this.smscode);
if(checkRs){
//更新最后一次登陆时间
selectUser.setLastLoginTime((new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm")).format(new Date()));
userService.update(selectUser);
//设置用户角色信息
String roleIds="";
String roleNames="";
for(Role r : selectUser.getRoles()){
roleIds+=r.getRoleId()+",";
roleNames+=r.getRoleName()+",";
}
if(selectUser.getRoles().size()>0){
roleIds=roleIds.substring(0,roleIds.length()-1);
roleNames=roleNames.substring(0,roleNames.length()-1);
}
selectUser.setRoleIds(roleIds);
selectUser.setRoleNames(roleNames);
List<Resource> menus = new ArrayList<Resource>();
List<Resource> grantTreeList = new ArrayList<Resource>();
// 校友会角色授权时使用该list
List<Resource> xgrantTreeList = new ArrayList<Resource>();
if (selectUser.getRoles().size()>0){
menus = resourceService.getMenuByRoles(selectUser.getRoles());
grantTreeList = resourceService.getResourcesByRoles(selectUser.getRoles());
//xgrantTreeList = grantTreeList;
}
//getSession().put("xgrantTreeList", xgrantTreeList);
/*getSession().put("grantTreeList", grantTreeList);
getSession().put("menus", menus);
getSession().put("user", selectUser);
message.setSuccess(true);
message.setReturnId("21");*/
List<Tree> treeList = Lists.newArrayList();
List<Tree> tree = Lists.newArrayList();
if (menus != null && menus.size() > 0) {
for (Resource resource : menus) {
if (resource.getType().equals("菜单")) {
Tree node = new Tree();
node.setId(resource.getId());
node.setPid(resource.getPid());
node.setText(resource.getMenuName());
node.setIconCls(resource.getIconCls());
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("url", resource.getUrl());
node.setAttributes(attributes);
treeList.add(node);
}
}
resourceService.parseTree(tree, treeList);
}
getSession().put("grantTreeList", grantTreeList);
getSession().put("menus", menus);
getSession().put("menuTree",tree);
getSession().put("user", selectUser);
message.setSuccess(true);
message.setReturnId("21");
HttpServletRequest request = ServletActionContext.getRequest();
LogUtils.saveLog(request,"登录");
/*List<Resource> menus = new ArrayList<Resource>();
List<Resource> grantTreeList = new ArrayList<Resource>();
// 校友会角色授权时使用该list
List<Resource> xgrantTreeList = new ArrayList<Resource>();
// 用户拥有的角色
Role hasRole = selectUser.getRole();
if (hasRole != null) {
if (hasRole.getSystemAdmin() == 1) {
// Map<String, Object> map = GetDictionaryInfo.dictionaryInfoMap;
@SuppressWarnings("unchecked")
List<Resource> allList = (List<Resource>) CacheUtils.get("resources");
for (Resource resource : allList) {
// 后台菜单
if (resource.getType().equals("菜单") && resource.getFlag() == 0) {
menus.add(resource);
}
if (resource.getFlag() == 0) {
grantTreeList.add(resource);
}
}
} else {
List<Role> roles2 = roleService.getMenu(hasRole.getRoleId());
// 拥有的菜单
for (Role role : roles2) {
List<Resource> resources = role.getList();
for (Resource resource : resources) {
if ("菜单".equals(resource.getType())) {
menus.add(resource);
}
grantTreeList.add(resource);
}
}
}
getSession().put("grantTreeList", grantTreeList);
getSession().put("menus", menus);
getSession().put("user", selectUser);
message.setSuccess(true);
}*/
}else{
message.setSuccess(false);
}
}
}
super.writeJson(message);
}
/**
* 验证码
*/
public void doNotNeedSessionAndSecurity_captchaImage() {
try {
getResponse().setDateHeader("Expires", 0);
getResponse().setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
getResponse().addHeader("Cache-Control", "post-check=0, pre-check=0");
getResponse().setHeader("Pragma", "no-cache");
getResponse().setContentType("image/jpeg");
String capText = captchaProducer.createText();
getRequest().getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = getResponse().getOutputStream();
ImageIO.write(bi, "jpg", out);
out.flush();
out.close();
} catch (Exception e) {
logger.error(e, e);
}
}
/**
* 创建人:Kent
* 创建时间:2016-07-30
* 描述:初始化后台主菜单
*/
public void doNotNeedSecurity_initMainMenu(){
// 获取session中的菜单
@SuppressWarnings("unchecked")
List<Tree> trees = (List<Tree>) getSession().get("menuTree");
super.writeJson(trees);
}
/**
* 初始化后台菜单
*
* @throws Exception
*/
public void doNotNeedSecurity_initMenu() {
// 获取session中的菜单
@SuppressWarnings("unchecked")
List<Resource> menus = (List<Resource>) getSession().get("menus");
if (menus != null && menus.size() > 0) {
List<Tree> treeList = new ArrayList<Tree>();
List<Tree> tree = new ArrayList<Tree>();
for (Resource resource : menus) {
if (resource.getType().equals("菜单")) {
Tree node = new Tree();
node.setId(resource.getId());
node.setPid(resource.getPid());
node.setText(resource.getMenuName());
node.setIconCls(resource.getIconCls());
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("url", resource.getUrl());
node.setAttributes(attributes);
treeList.add(node);
}
}
resourceService.parseTree(tree, treeList);
super.writeJson(tree);
} else {
List<Tree> tree = new ArrayList<Tree>();
super.writeJson(tree);
}
}
public void doNotNeedSecurity_checkRealUser() {
String rskey = "rs";
String errorVal = "1";
Map<String,String> rs = new HashMap<String,String>(1);
User user = (User) getSession().get("user");
if(user == null){
rs.put(rskey, errorVal);
super.writeJson(rs);
return;
}
String sessionUserAccount = user.getUserAccount();
if(sessionUserAccount == null || sessionUserAccount.trim().length() <= 0
|| this.userAccount == null || this.userAccount.trim().length() <= 0){
rs.put(rskey, errorVal);
super.writeJson(rs);
return;
}
if(!sessionUserAccount.trim().equals(this.userAccount.trim())){
rs.put(rskey, errorVal);
super.writeJson(rs);
return;
}
rs.put(rskey, "0");
super.writeJson(rs);
}
public String getUserAccount() {
return userAccount;
}
public void setUserAccount(String userAccount) {
this.userAccount = userAccount;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getValidCode() {
return validCode;
}
public void setValidCode(String validCode) {
this.validCode = validCode;
}
public String getSmscode() {
return smscode;
}
public void setSmscode(String smscode) {
this.smscode = smscode;
}
public String getUserTelephone() {
return userTelephone;
}
public void setUserTelephone(String userTelephone) {
this.userTelephone = userTelephone;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAgent() {
return agent;
}
public void setAgent(String agent) {
this.agent = agent;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
/**
*
* @param list
* 通过resource中的ID比对,把重复项去除
*/
public void removeDuplicate(List<Resource> list){
for(int i = 0 ; i < list.size() - 1; i ++){
for(int j = list.size() - 1; j > i; j --){
if(list.get(j).getId()==list.get(i).getId()){
list.remove(j);
}
}
}
}
/**
* 绑定手机号并修改初始密码
*/
public void doNotNeedSessionAndSecurity_binding() {
Message message = new Message();
if(StringUtils.isBlank(this.userName)) {
message.init(false,"用户姓名不能为空",null,"101");
} else if(StringUtils.isBlank(this.userPassword)) {
message.init(false,"密码不能为空",null,"102");
} else if(StringUtils.isBlank(this.userTelephone)) {
message.init(false,"手机号不能为空",null,"102");
} else if(StringUtils.isBlank(this.smscode)) {
message.init(false,"验证码不能空",null,"103");
} else {
User selectUser = userService.selectByUserId(this.userId);
if (selectUser == null) {
message.setMsg("帐号错误");
message.setSuccess(false);
} else {
//验证手机验证码的正确性
boolean checkRs = loginService.checkSMSCode(message, this.userTelephone, this.smscode);
if (checkRs) {
Map<String,Object> map = Maps.newHashMap() ;
map.put("telephone",this.userTelephone) ;
map.put("userId",this.userId) ;
/*List<User> list = userService.queryUserList(map) ;
if(list != null && !list.isEmpty()) {
message.init(false,"该手机号已绑定用户,不能重复绑定",null,"104");
} else {*/
// 修改用户信息
selectUser.setUserName(this.userName);
selectUser.setTelephone(this.userTelephone);
selectUser.setUserPassword(SecretUtil.encryptToSHA(this.userPassword));
selectUser.setIsFirstLogin("1");
userService.update(selectUser);
message.setMsg("绑定成功,请重新登陆");
message.setSuccess(true);
//}
} else {
message.setMsg("验证码无效");
message.setSuccess(false);
}
/*if (!selectUser.getUserPassword().equals(SecretUtil.encryptToSHA(this.userPassword))) {
message.setMsg("密码错误");
message.setSuccess(false);
} else {
}*/
}
}
super.writeJson(message);
}
/**
* 通过手机号登录
*/
public void doNotNeedSessionAndSecurity_loginByTelephone() {
Message message = new Message();
if(StringUtils.isBlank(this.userTelephone)) {
message.init(false,"手机号不能为空",null,"102");
} else if(StringUtils.isBlank(this.smscode)) {
message.init(false,"验证码不能空",null,"103");
} else {
Map<String,Object> map = Maps.newHashMap() ;
map.put("telephone",this.userTelephone) ;
List<User> list = userService.queryUserList(map) ;
if(list != null && !list.isEmpty()) {
//验证手机验证码的正确性
boolean checkRs = loginService.checkSMSCode(message, this.userTelephone, this.smscode);
if (checkRs) {
if(list.size()==1) {
List<User> list2 =userService.queryChoiceUserList(map) ;
User selectUser = list2.get(0);
if (StringUtils.isBlank(selectUser.getIsFirstLogin()) || "0".equals(selectUser.getIsFirstLogin().trim())) {
message.init(false, "当前为首次登陆,请修改密码并绑定手机号", "firstLogin", "201");
} else {
//更新最后一次登陆时间
selectUser.setLastLoginTime((new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm")).format(new Date()));
userService.update(selectUser);
//设置用户角色信息
String roleIds = "";
String roleNames = "";
for (Role r : selectUser.getRoles()) {
roleIds += r.getRoleId() + ",";
roleNames += r.getRoleName() + ",";
}
if (selectUser.getRoles().size() > 0) {
roleIds = roleIds.substring(0, roleIds.length() - 1);
roleNames = roleNames.substring(0, roleNames.length() - 1);
}
selectUser.setRoleIds(roleIds);
selectUser.setRoleNames(roleNames);
List<Resource> menus = new ArrayList<Resource>();
List<Resource> grantTreeList = new ArrayList<Resource>();
// 校友会角色授权时使用该list
List<Resource> xgrantTreeList = new ArrayList<Resource>();
if (selectUser.getRoles().size() > 0) {
menus = resourceService.getMenuByRoles(selectUser.getRoles());
grantTreeList = resourceService.getResourcesByRoles(selectUser.getRoles());
//xgrantTreeList = grantTreeList;
}
//getSession().put("xgrantTreeList", xgrantTreeList);
/*getSession().put("grantTreeList", grantTreeList);
getSession().put("menus", menus);
getSession().put("user", selectUser);
message.setSuccess(true);
message.setReturnId("21");*/
List<Tree> treeList = Lists.newArrayList();
List<Tree> tree = Lists.newArrayList();
if (menus != null && menus.size() > 0) {
for (Resource resource : menus) {
if (resource.getType().equals("菜单")) {
Tree node = new Tree();
node.setId(resource.getId());
node.setPid(resource.getPid());
node.setText(resource.getMenuName());
node.setIconCls(resource.getIconCls());
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("url", resource.getUrl());
node.setAttributes(attributes);
treeList.add(node);
}
}
resourceService.parseTree(tree, treeList);
}
getSession().put("grantTreeList", grantTreeList);
getSession().put("menus", menus);
getSession().put("menuTree", tree);
getSession().put("user", selectUser);
message.setSuccess(true);
message.setReturnId("21");
}
}else{
super.writeJson(list);
}
} else {
message.setSuccess(false);
}
} else {
message.init(false ,"该手机号未绑定账号" ,null);
}
}
super.writeJson(message);
}
/**
* 通过手机号登录—选择要登录的账号
*/
public void doNotNeedSessionAndSecurity_loginByUserId() {
Message message = new Message();
Map<String,Object> map = Maps.newHashMap() ;
map.put("userId",this.userId) ;
List<User> list = userService.queryChoiceUserList(map) ;
if(list != null && !list.isEmpty()) {
User selectUser = list.get(0);
if (StringUtils.isBlank(selectUser.getIsFirstLogin()) || "0".equals(selectUser.getIsFirstLogin().trim())) {
message.init(false, "当前为首次登陆,请修改密码并绑定手机号", "firstLogin", "201");
} else {
//更新最后一次登陆时间
selectUser.setLastLoginTime((new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm")).format(new Date()));
userService.update(selectUser);
//设置用户角色信息
String roleIds = "";
String roleNames = "";
for (Role r : selectUser.getRoles()) {
roleIds += r.getRoleId() + ",";
roleNames += r.getRoleName() + ",";
}
if (selectUser.getRoles().size() > 0) {
roleIds = roleIds.substring(0, roleIds.length() - 1);
roleNames = roleNames.substring(0, roleNames.length() - 1);
}
selectUser.setRoleIds(roleIds);
selectUser.setRoleNames(roleNames);
List<Resource> menus = new ArrayList<Resource>();
List<Resource> grantTreeList = new ArrayList<Resource>();
// 校友会角色授权时使用该list
List<Resource> xgrantTreeList = new ArrayList<Resource>();
if (selectUser.getRoles().size() > 0) {
menus = resourceService.getMenuByRoles(selectUser.getRoles());
grantTreeList = resourceService.getResourcesByRoles(selectUser.getRoles());
//xgrantTreeList = grantTreeList;
}
List<Tree> treeList = Lists.newArrayList();
List<Tree> tree = Lists.newArrayList();
if (menus != null && menus.size() > 0) {
for (Resource resource : menus) {
if (resource.getType().equals("菜单")) {
Tree node = new Tree();
node.setId(resource.getId());
node.setPid(resource.getPid());
node.setText(resource.getMenuName());
node.setIconCls(resource.getIconCls());
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("url", resource.getUrl());
node.setAttributes(attributes);
treeList.add(node);
}
}
resourceService.parseTree(tree, treeList);
}
getSession().put("grantTreeList", grantTreeList);
getSession().put("menus", menus);
getSession().put("menuTree", tree);
getSession().put("user", selectUser);
message.setSuccess(true);
message.setReturnId("21");
}
}
super.writeJson(message);
}
public void doNotNeedSessionAndSecurity_msgNum(){
User user = UserUtils.getUser();
if(user != null && user.getDeptId() != 0){
Map<String, Object> map = loginService.toDoList(user);
super.writeJson(map);
}else{
super.writeJson(0);
}
}
public boolean isValidateCodeLogin() {
return isValidateCodeLogin;
}
public void setValidateCodeLogin(boolean validateCodeLogin) {
isValidateCodeLogin = validateCodeLogin;
}
/**
* 是否是验证码登录
* @param useruame 用户名
* @param isFail 计数加1
* @param clean 计数清零
* @return
*/
@SuppressWarnings("unchecked")
public static boolean isValidateCodeLogin(String useruame, boolean isFail, boolean clean){
Map<String, Integer> loginFailMap = (Map<String, Integer>)CacheUtils.get("loginFailMap");
if (loginFailMap==null){
loginFailMap = Maps.newHashMap();
CacheUtils.put("loginFailMap", loginFailMap);
}
Integer loginFailNum = loginFailMap.get(useruame);
if (loginFailNum==null){
loginFailNum = 0;
}
if (isFail){
loginFailNum++;
loginFailMap.put(useruame, loginFailNum);
}
if (clean){
loginFailMap.remove(useruame);
}
return loginFailNum >= 3;
}
}
|
3e1914ac294ea752614b93fab71a23fea859504f | 2,972 | java | Java | app/src/main/java/com/lvyangai/highopinion/activity/BaseChildFragment.java | LvYangai/HighOpinion | 21110c7c2360d442781460d216b1ed752bd3b00c | [
"Apache-2.0"
] | 3 | 2019-06-05T03:50:05.000Z | 2020-01-16T08:08:03.000Z | app/src/main/java/com/lvyangai/highopinion/activity/BaseChildFragment.java | LvYangai/HighOpinion | 21110c7c2360d442781460d216b1ed752bd3b00c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/lvyangai/highopinion/activity/BaseChildFragment.java | LvYangai/HighOpinion | 21110c7c2360d442781460d216b1ed752bd3b00c | [
"Apache-2.0"
] | 1 | 2019-06-09T10:38:36.000Z | 2019-06-09T10:38:36.000Z | 23.991935 | 102 | 0.566723 | 10,666 | package com.lvyangai.highopinion.activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* 作者:Created by 吕言盖 (LYG-Pro)
* 时间: 2019/5/8.
* 描述:
* lyhxr@example.com
*/
public abstract class BaseChildFragment extends BaseLazyFragment {
private static final String TAG = "BaseChildFragment";
@Override
protected View initView(LayoutInflater inflater, ViewGroup container) {
return null;
}
@Override
protected void initData() {
}
@Override
protected void dataProcess() {
}
@Override
protected void destroy() {
}
private boolean isVisible = true;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initData();
}
@Override
public void onDestroyView() {
super.onDestroyView();
destroy();
}
@Override
protected void onFirstUserVisible() {
if (getParentFragment() != null
&& (getParentFragment() instanceof BaseLazyFragment)
&& !((BaseLazyFragment) getParentFragment()).isUIVisible) {
if (!((BaseLazyFragment) getParentFragment()).isLazyIn) {
isVisible = true;
onVisible();
}
} else {
//为了解决三级嵌套,不支持更多级
if (getParentFragment() != null
&& getParentFragment().getParentFragment() != null
&& getParentFragment() instanceof BaseLazyFragment) {
if (((BaseLazyFragment) getParentFragment().getParentFragment()).isUIVisible
&& ((BaseLazyFragment) getParentFragment().getParentFragment()).isResumed()) {
isVisible = true;
onVisible();
}
} else {
isVisible = true;
onVisible();
}
}
}
/**
* 除第一外的布局可见时候
*/
public void onUserVisible() {
if (getParentFragment() != null
&& getParentFragment() instanceof BaseParentFragment
&& !((((BaseParentFragment) getParentFragment()).isUIVisible
&& getParentFragment().isResumed()))) {
if (!((BaseLazyFragment) getParentFragment()).isLazyIn) {
isVisible = true;
onVisible();
}
} else {
isVisible = true;
onVisible();
}
}
/**
* 除了第一次布局消失时
*/
protected void onUserInvisible() {
isVisible = false;
onInvisible();
}
private void onVisible() {
doSomeThingVisible();
}
protected abstract void doSomeThingVisible();
private void onInvisible() {
doSomeThingInvisible();
}
protected abstract void doSomeThingInvisible();
}
|
3e1914d454b5cd8b771378241dbf8c91f5581c32 | 214 | java | Java | libraunrar4j/src/main/java/ruby/blacktech/libraunrar4j/exception/RarException.java | rubydongle/libraunrar4j | 71eed0ac2a95d67d3e2960436610d5bbc2dc4e43 | [
"MIT"
] | null | null | null | libraunrar4j/src/main/java/ruby/blacktech/libraunrar4j/exception/RarException.java | rubydongle/libraunrar4j | 71eed0ac2a95d67d3e2960436610d5bbc2dc4e43 | [
"MIT"
] | null | null | null | libraunrar4j/src/main/java/ruby/blacktech/libraunrar4j/exception/RarException.java | rubydongle/libraunrar4j | 71eed0ac2a95d67d3e2960436610d5bbc2dc4e43 | [
"MIT"
] | null | null | null | 17.833333 | 47 | 0.654206 | 10,667 | package ruby.blacktech.libraunrar4j.exception;
public class RarException extends Exception {
public RarException(Throwable cause) {
super(cause);
}
public RarException() {
}
}
|
3e19157a01c841039c5d8567a3355155c18e09fc | 924 | java | Java | src/main/java/frc/robot/Constants.java | TitaniumTigers4829/SwerveBot_Math | 58995c46a994270751906f7371b4737b1178966a | [
"BSD-3-Clause"
] | null | null | null | src/main/java/frc/robot/Constants.java | TitaniumTigers4829/SwerveBot_Math | 58995c46a994270751906f7371b4737b1178966a | [
"BSD-3-Clause"
] | null | null | null | src/main/java/frc/robot/Constants.java | TitaniumTigers4829/SwerveBot_Math | 58995c46a994270751906f7371b4737b1178966a | [
"BSD-3-Clause"
] | null | null | null | 31.862069 | 74 | 0.689394 | 10,668 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot;
/** Add your docs here. */
public class Constants {
public static class SwerveConstants{
public static int frontLeftDriveMotorID = 13; // FX
public static int frontLeftTurnMotorID = 12; // SRX
public static int frontRightDriveMotorID = 02;
public static int frontRightTurnMotorID = 03;
public static int backLeftDriveMotorID = 14;
public static int backLeftTurnMotorID = 15;
public static int backRightDriveMotorID = 01;
public static int backRightTurnMotorID = 00;
}
public static class ControllerConstants{
public static int turnStrafeStickID = 2;
public static int rotateStickID = 1;
}
}
|
3e1915adfe0556eae1f7b3f3952cbada5c913da1 | 2,394 | java | Java | src/main/java/com/tabular/tabular/service/CustomerService.java | im-liang/tabular | 7b35c2dd41a06efc50d65ccacb9665171d4cf51e | [
"Apache-1.1"
] | null | null | null | src/main/java/com/tabular/tabular/service/CustomerService.java | im-liang/tabular | 7b35c2dd41a06efc50d65ccacb9665171d4cf51e | [
"Apache-1.1"
] | null | null | null | src/main/java/com/tabular/tabular/service/CustomerService.java | im-liang/tabular | 7b35c2dd41a06efc50d65ccacb9665171d4cf51e | [
"Apache-1.1"
] | null | null | null | 33.71831 | 96 | 0.716374 | 10,669 | package com.tabular.tabular.service;
import com.tabular.tabular.dao.CustomerDao;
import com.tabular.tabular.entity.Customer;
import com.tabular.tabular.exception.customer.NoSuchCustomerException;
import com.tabular.tabular.exception.user.NoSuchUserException;
import com.tabular.tabular.service.blueprint.CustomerServiceBlueprint;
import com.tabular.tabular.service.utility.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.UUID;
@Service
public class CustomerService implements CustomerServiceBlueprint {
private final CustomerDao customerDao;
private final UserService userService;
@Autowired
public CustomerService(UserService userService, CustomerDao customerDao) {
this.userService = userService;
this.customerDao = customerDao;
}
@Override
public long createCustomer(String name) {
String username = UUID.randomUUID().toString();
long userId = userService.createUserAsCustomer(username, "password");
customerDao.insertCustomer(userId, name);
return userId;
}
@Override
public long createCustomer(long customerId, String name) {
if(!userService.isUserExist(customerId)) {
throw new NoSuchUserException("user with " + customerId + "does not exist");
}
customerDao.insertCustomer(customerId, name);
return customerId;
}
@Override
public Customer queryCustomerById(long customerId) {
Customer customer = customerDao.queryCustomerById(customerId);
if(customer == null) {
throw new NoSuchCustomerException("customer with " + customerId + "does not exist");
}
return customer;
}
@Override
public List<Customer> queryCustomerByName(String name) {
return customerDao.queryCustomerByName(name);
}
@Override
public boolean modifyCustomerName(long customerId, String name) {
if(!isCustomerExist(customerId)) {
throw new NoSuchCustomerException("customer with " + customerId + "does not exist");
}
int result = customerDao.modifyCustomerName(customerId, name);
return result == 1;
}
private boolean isCustomerExist(long customerId) {
return customerDao.queryCustomerById(customerId) != null;
}
}
|
3e19176650ba326322ddc09c7734bfeb3088d2b4 | 6,659 | java | Java | inflater/src/main/java/xyz/truenight/dynamic/AttributeApplier.java | TrueNight/Dynamic | ca3a9cdb3e171e9f834715625b10aec1cc05e4c2 | [
"Apache-2.0"
] | 1 | 2019-05-24T08:02:40.000Z | 2019-05-24T08:02:40.000Z | inflater/src/main/java/xyz/truenight/dynamic/AttributeApplier.java | TrueNight/Dynamic | ca3a9cdb3e171e9f834715625b10aec1cc05e4c2 | [
"Apache-2.0"
] | null | null | null | inflater/src/main/java/xyz/truenight/dynamic/AttributeApplier.java | TrueNight/Dynamic | ca3a9cdb3e171e9f834715625b10aec1cc05e4c2 | [
"Apache-2.0"
] | 2 | 2021-05-27T18:56:17.000Z | 2021-08-10T20:28:57.000Z | 38.270115 | 147 | 0.66992 | 10,670 | /**
* Copyright (C) 2017 Mikhail Frolov
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 xyz.truenight.dynamic;
import android.content.Context;
import android.util.AttributeSet;
import android.view.InflateException;
import android.view.View;
import android.view.ViewGroup;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import xyz.truenight.dynamic.adapter.attr.TypedAttrAdapter;
import xyz.truenight.dynamic.adapter.attr.TypedAttrAdapters;
import xyz.truenight.dynamic.adapter.param.TypedParamAdapter;
import xyz.truenight.dynamic.adapter.param.TypedParamAdapters;
import xyz.truenight.utils.Utils;
public final class AttributeApplier {
private static final String TAG = AttributeApplier.class.getSimpleName();
public static final AttributeApplier DEFAULT = new AttributeApplier();
private List<TypedAttrAdapter> mTypedAttrAdapters;
private List<TypedParamAdapter> mTypedParamAdapters;
public AttributeApplier() {
mTypedAttrAdapters = new ArrayList<>(TypedAttrAdapters.DEFAULT);
mTypedParamAdapters = new ArrayList<>(TypedParamAdapters.DEFAULT);
}
public AttributeApplier(List<TypedAttrAdapter> typedAttrAdapters, List<TypedParamAdapter> typedParamAdapters) {
mTypedAttrAdapters = new ArrayList<>(typedAttrAdapters);
mTypedParamAdapters = new ArrayList<>(typedParamAdapters);
}
public void addAttrAdapter(TypedAttrAdapter adapter) {
mTypedAttrAdapters.add(0, adapter);
}
public void addParamAdapter(TypedParamAdapter adapter) {
mTypedParamAdapters.add(0, adapter);
}
@Override
public AttributeApplier clone() {
return new AttributeApplier(mTypedAttrAdapters, mTypedParamAdapters);
}
private List<TypedAttrAdapter> getTypedAdapters(View view) {
List<TypedAttrAdapter> adapters = new ArrayList<>();
for (TypedAttrAdapter typedAttrAdapter : mTypedAttrAdapters) {
if (typedAttrAdapter.isSuitable(view)) {
adapters.add(typedAttrAdapter);
}
}
return adapters;
}
public void applyAttrs(View view, AttributeSet attrs) {
// count is too expensive so catching it
int attributeCount = attrs.getAttributeCount();
// select adapters for this class
// may be cache adapters for specific class
List<TypedAttrAdapter> adapters = getTypedAdapters(view);
// http://schemas.android.com/apk/res/android
// http://schemas.android.com/apk/res-auto
for (int i = 0; i < attributeCount; i++) {
String name = attrs.getAttributeName(i);
String value = attrs.getAttributeValue(i);
// at start apply to base classes like View
// then go to concrete
name = getNameWithNamespace(attrs, name, value);
applyAttribute(adapters, view, name, value);
}
}
private String getNameWithNamespace(AttributeSet attrs, String name, String value) {
// todo add tools namespace support
// work around to detect namespace
return Utils.equal(value, attrs.getAttributeValue("http://schemas.android.com/apk/res/android", name)) ? "android:" + name : "app:" + name;
}
@SuppressWarnings("unchecked")
private boolean applyAttribute(List<TypedAttrAdapter> adapters, View view, String name, String value) {
for (TypedAttrAdapter adapter : adapters) {
if (adapter.apply(view, name, value)) {
return true;
}
}
return false;
}
public ViewGroup.LayoutParams generateLayoutParams(ViewGroup viewGroup, AttributeSet attrs) {
ViewGroup.LayoutParams params = generateDefaultLayoutParams(viewGroup);
// count is too expensive so catching it
int attributeCount = attrs.getAttributeCount();
List<TypedParamAdapter> adapters = getTypedParamAdapters(params);
boolean hasWidth = false;
boolean hasHeight = false;
for (int i = 0; i < attributeCount; i++) {
String name = attrs.getAttributeName(i);
String value = attrs.getAttributeValue(i);
name = getNameWithNamespace(attrs, name, value);
if (applyParam(adapters, viewGroup.getContext(), params, name, value)) {
if (Utils.equal(name, TypedParamAdapter.LAYOUT_HEIGHT)) {
hasHeight = true;
} else if (Utils.equal(name, TypedParamAdapter.LAYOUT_WIDTH)) {
hasWidth = true;
}
}
}
if (!hasHeight || !hasWidth) {
throw new InflateException("REQUIRED attribute layout_height OR layout_width in NOT set");
}
return params;
}
private boolean applyParam(List<TypedParamAdapter> adapters, Context context, ViewGroup.LayoutParams params, String name, String value) {
for (TypedParamAdapter adapter : adapters) {
if (adapter.apply(context, params, name, value)) {
return true;
}
}
return false;
}
private List<TypedParamAdapter> getTypedParamAdapters(ViewGroup.LayoutParams params) {
List<TypedParamAdapter> adapters = new ArrayList<>();
for (TypedParamAdapter typedAttrAdapter : mTypedParamAdapters) {
if (typedAttrAdapter.isSuitable(params)) {
adapters.add(typedAttrAdapter);
}
}
return adapters;
}
public static ViewGroup.LayoutParams generateDefaultLayoutParams(ViewGroup parent) {
try {
Method generate = ViewGroup.class.getDeclaredMethod("generateDefaultLayoutParams");
generate.setAccessible(true);
return (ViewGroup.LayoutParams) generate.invoke(parent);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
}
|
3e19186612fc5e1b4172908f97033cc7af276b3a | 352 | java | Java | src/main/java/com/zhongyp/advanced/pattern/factory/simplefactory/SimpleFactory.java | zhongyp/Demo | af547d924c108e4488bd916b52fa817103f4f783 | [
"MIT"
] | null | null | null | src/main/java/com/zhongyp/advanced/pattern/factory/simplefactory/SimpleFactory.java | zhongyp/Demo | af547d924c108e4488bd916b52fa817103f4f783 | [
"MIT"
] | 4 | 2020-03-04T21:51:17.000Z | 2021-12-09T20:03:24.000Z | src/main/java/com/zhongyp/advanced/pattern/factory/simplefactory/SimpleFactory.java | zhongyp/demo | af547d924c108e4488bd916b52fa817103f4f783 | [
"MIT"
] | null | null | null | 19.611111 | 59 | 0.597734 | 10,671 | package com.zhongyp.advanced.pattern.factory.simplefactory;
/**
* project: demo
* author: zhongyp
* date: 2018/3/27
* mail: nnheo@example.com
*/
public class SimpleFactory {
Mouse createMouse(String type){
if(type.equals("dell")){
return new DellMouse();
}else{
return new HpMouse();
}
}
}
|
3e1918bc4d192d7db2f512acc7c92badd71c2636 | 2,161 | java | Java | src/Examples/RandomlyGeneratedUniverse.java | andrewnyhus/neuLayout-Swing | 910b2310486507724aa022c3ec025e368ae1f6cd | [
"MIT"
] | null | null | null | src/Examples/RandomlyGeneratedUniverse.java | andrewnyhus/neuLayout-Swing | 910b2310486507724aa022c3ec025e368ae1f6cd | [
"MIT"
] | null | null | null | src/Examples/RandomlyGeneratedUniverse.java | andrewnyhus/neuLayout-Swing | 910b2310486507724aa022c3ec025e368ae1f6cd | [
"MIT"
] | null | null | null | 36.627119 | 88 | 0.718186 | 10,672 | /*
* The MIT License
*
* Copyright 2015 andrewnyhus.
*
* 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 Examples;
import java.awt.Color;
import java.awt.Dimension;
import neuLayout.Controller.UniverseController;
import neuLayout.SettingsSingleton;
import javax.swing.SwingUtilities;
/**
*
* @author andrewnyhus
*/
public class RandomlyGeneratedUniverse {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
SwingUtilities.invokeLater(() -> {
SettingsSingleton.getInstance().setShouldShowHUDMap(true);
SettingsSingleton.getInstance().setActorsShouldGenerateRandomly(true);
Dimension d = new Dimension(1000, 400);
UniverseController mainController = new UniverseController("", d,null);
SettingsSingleton.getInstance().setCameraScrollingSpeed(8);
Color transparentColor = new Color(255, 255, 255, 0);
SettingsSingleton.getInstance().setCenterOfViewActorColor(transparentColor);
});
}
}
|
3e1918e0a92c310c9520c9b9354c1e51b30d6939 | 380 | java | Java | requisition_ws/src/main/java/com/tq/utils/DateFormater.java | huahuajjh/mvn_requisition_ws | 31c8990ad1e12e141e797fb73983dd86ab27a310 | [
"Apache-2.0"
] | null | null | null | requisition_ws/src/main/java/com/tq/utils/DateFormater.java | huahuajjh/mvn_requisition_ws | 31c8990ad1e12e141e797fb73983dd86ab27a310 | [
"Apache-2.0"
] | null | null | null | requisition_ws/src/main/java/com/tq/utils/DateFormater.java | huahuajjh/mvn_requisition_ws | 31c8990ad1e12e141e797fb73983dd86ab27a310 | [
"Apache-2.0"
] | null | null | null | 21.111111 | 68 | 0.718421 | 10,673 | package com.tq.utils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormater
{
private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
public static Date parse(String date) {
try {
return df.parse(date); } catch (ParseException e) {
}
return null;
}
} |
3e191a41a77e0c38c7b02402615362b6c1a01f2a | 115 | java | Java | src/test/java/org/jlw/test/db/DefaultDatabaseDialectInitializer.java | jlwagner12/ulid | 110df8735ee8313ef51fcbd9bf3c03bed286dfb7 | [
"MIT"
] | null | null | null | src/test/java/org/jlw/test/db/DefaultDatabaseDialectInitializer.java | jlwagner12/ulid | 110df8735ee8313ef51fcbd9bf3c03bed286dfb7 | [
"MIT"
] | null | null | null | src/test/java/org/jlw/test/db/DefaultDatabaseDialectInitializer.java | jlwagner12/ulid | 110df8735ee8313ef51fcbd9bf3c03bed286dfb7 | [
"MIT"
] | null | null | null | 19.166667 | 84 | 0.86087 | 10,674 | package org.jlw.test.db;
public class DefaultDatabaseDialectInitializer implements DatabaseDialectInitializer
{
}
|
3e191aeac77e96cb7d384c3e65597fb5431e3ab3 | 1,810 | java | Java | src/test/ser/offheaplatency/MktDataDispatcher.java | TMCBonds/fast-serialization | 51eb57644e16bb0e410dc75a4d07725481828e36 | [
"Apache-2.0"
] | 1,370 | 2015-01-02T13:33:02.000Z | 2022-03-26T22:07:25.000Z | src/test/ser/offheaplatency/MktDataDispatcher.java | TMCBonds/fast-serialization | 51eb57644e16bb0e410dc75a4d07725481828e36 | [
"Apache-2.0"
] | 279 | 2015-01-01T18:51:47.000Z | 2022-03-16T06:22:55.000Z | src/test/ser/offheaplatency/MktDataDispatcher.java | TMCBonds/fast-serialization | 51eb57644e16bb0e410dc75a4d07725481828e36 | [
"Apache-2.0"
] | 257 | 2015-01-06T01:42:17.000Z | 2022-03-23T06:23:19.000Z | 26.617647 | 100 | 0.583978 | 10,675 | package ser.offheaplatency;
import java.util.*;
import java.util.concurrent.*;
public final class MktDataDispatcher implements Runnable{
private volatile boolean keepDispatching;
private final ExecutorService service;
private final MyFSTSerializer serializer;
private final MktDataListener listener;
private final AbstractQueue<MktDataEvent> eventQueue;
public MktDataDispatcher( int queueSize, MyFSTSerializer serializer, MktDataListener listener ){
this.serializer = serializer;
this.listener = listener;
this.eventQueue = new ArrayBlockingQueue<MktDataEvent>( queueSize );
this.service = Executors.newFixedThreadPool( 1 );
}
public final void start( ){
serializer.start( );
keepDispatching = true;
service.execute( this );
}
public final boolean enqueue( final MktDataEvent event ){
return eventQueue.offer( event );
}
@Override
public final void run( ){
while( keepDispatching ){
try{
MktDataEvent event = eventQueue.poll();
if( event == null ){
// Thread.yield();
continue;
}
if( serializer.toStore() ){
serializer.storeEvent( event );
}
listener.update( event );
}catch( Exception e ){
e.printStackTrace( );
}
}
}
protected final int getQueueSize( ){
return eventQueue.size( );
}
public final void stop(){
serializer.stop( );
keepDispatching = false;
service.shutdown();
}
public interface MktDataListener{
public boolean update( MktDataEvent event );
}
} |
3e191b883f93dfcc43820b0353f00416daf1c98e | 338 | java | Java | code/mqtt/org.eclipsescout.mqttclient.shared/src/org/eclipsescout/mqttclient/shared/services/ReadNotificationPermission.java | jmini/scoutbook | 6d5128efb73f2d59dbd827f5e1096ae1bf1bfc7e | [
"CC-BY-2.0"
] | null | null | null | code/mqtt/org.eclipsescout.mqttclient.shared/src/org/eclipsescout/mqttclient/shared/services/ReadNotificationPermission.java | jmini/scoutbook | 6d5128efb73f2d59dbd827f5e1096ae1bf1bfc7e | [
"CC-BY-2.0"
] | null | null | null | code/mqtt/org.eclipsescout.mqttclient.shared/src/org/eclipsescout/mqttclient/shared/services/ReadNotificationPermission.java | jmini/scoutbook | 6d5128efb73f2d59dbd827f5e1096ae1bf1bfc7e | [
"CC-BY-2.0"
] | null | null | null | 15.363636 | 65 | 0.710059 | 10,676 | /**
*
*/
package org.eclipsescout.mqttclient.shared.services;
import java.security.BasicPermission;
/**
* @author mzi
*/
public class ReadNotificationPermission extends BasicPermission {
private static final long serialVersionUID = 1L;
/**
*
*/
public ReadNotificationPermission() {
super("ReadNotification");
}
}
|
3e191d050c1d229ea4851f65c304699dc6018db9 | 8,093 | java | Java | runescape-client/src/main/java/class137.java | Samlof/runelite | e089ae19e5795da93ddf75b47b5ceb114913e013 | [
"BSD-2-Clause"
] | null | null | null | runescape-client/src/main/java/class137.java | Samlof/runelite | e089ae19e5795da93ddf75b47b5ceb114913e013 | [
"BSD-2-Clause"
] | null | null | null | runescape-client/src/main/java/class137.java | Samlof/runelite | e089ae19e5795da93ddf75b47b5ceb114913e013 | [
"BSD-2-Clause"
] | null | null | null | 34.292373 | 159 | 0.602249 | 10,677 | import net.runelite.mapping.Export;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("eg")
public class class137 {
@ObfuscatedName("u")
@Export("directions")
public static int[][] directions;
@ObfuscatedName("p")
@Export("distances")
public static int[][] distances;
@ObfuscatedName("g")
@Export("bufferX")
public static int[] bufferX;
@ObfuscatedName("h")
@Export("bufferY")
public static int[] bufferY;
static {
directions = new int[128][128]; // L: 6
distances = new int[128][128]; // L: 7
bufferX = new int[4096]; // L: 11
bufferY = new int[4096]; // L: 12
}
@ObfuscatedName("f")
@ObfuscatedSignature(
descriptor = "(III)I",
garbageValue = "-2142993463"
)
public static int method2654(int var0, int var1) {
return (var0 << 8) + var1; // L: 13
}
@ObfuscatedName("fc")
@ObfuscatedSignature(
descriptor = "(Lcd;II)V",
garbageValue = "391699616"
)
@Export("updateActorSequence")
static final void updateActorSequence(Actor var0, int var1) {
if (var0.field1255 >= Client.cycle) { // L: 3299
class26.method367(var0);
} else if (var0.field1268 >= Client.cycle) { // L: 3300
WorldMapData_1.method2990(var0);
} else {
class22.method330(var0); // L: 3301
}
if (var0.x < 128 || var0.y < 128 || var0.x >= 13184 || var0.y >= 13184) { // L: 3302
var0.sequence = -1; // L: 3303
var0.spotAnimation = -1; // L: 3304
var0.field1255 = 0; // L: 3305
var0.field1268 = 0; // L: 3306
var0.x = var0.pathX[0] * 128 + var0.field1258 * 64; // L: 3307
var0.y = var0.field1258 * 64 + var0.pathY[0] * 128; // L: 3308
var0.method2157(); // L: 3309
}
if (Varcs.localPlayer == var0 && (var0.x < 1536 || var0.y < 1536 || var0.x >= 11776 || var0.y >= 11776)) { // L: 3311 3312
var0.sequence = -1; // L: 3313
var0.spotAnimation = -1; // L: 3314
var0.field1255 = 0; // L: 3315
var0.field1268 = 0; // L: 3316
var0.x = var0.field1258 * 64 + var0.pathX[0] * 128; // L: 3317
var0.y = var0.field1258 * 64 + var0.pathY[0] * 128; // L: 3318
var0.method2157(); // L: 3319
}
int var5;
if (var0.field1262 != 0) { // L: 3323
if (var0.targetIndex != -1) { // L: 3324
Object var2 = null; // L: 3325
if (var0.targetIndex < 32768) { // L: 3326
var2 = Client.npcs[var0.targetIndex];
} else if (var0.targetIndex >= 32768) { // L: 3327
var2 = Client.players[var0.targetIndex - 32768];
}
if (var2 != null) { // L: 3328
int var3 = var0.x - ((Actor)var2).x; // L: 3329
int var4 = var0.y - ((Actor)var2).y; // L: 3330
if (var3 != 0 || var4 != 0) { // L: 3331
var0.orientation = (int)(Math.atan2((double)var3, (double)var4) * 325.949D) & 2047;
}
} else if (var0.false0) { // L: 3333
var0.targetIndex = -1; // L: 3334
var0.false0 = false; // L: 3335
}
}
if (var0.field1237 != -1 && (var0.pathLength == 0 || var0.field1267 > 0)) { // L: 3338
var0.orientation = var0.field1237; // L: 3339
var0.field1237 = -1; // L: 3340
}
var5 = var0.orientation - var0.rotation & 2047; // L: 3342
if (var5 == 0 && var0.false0) { // L: 3343
var0.targetIndex = -1; // L: 3344
var0.false0 = false; // L: 3345
}
if (var5 != 0) { // L: 3347
++var0.field1261; // L: 3348
boolean var8;
if (var5 > 1024) { // L: 3349
var0.rotation -= var0.field1262; // L: 3350
var8 = true; // L: 3351
if (var5 < var0.field1262 || var5 > 2048 - var0.field1262) { // L: 3352
var0.rotation = var0.orientation; // L: 3353
var8 = false; // L: 3354
}
if (var0.movementSequence == var0.idleSequence && (var0.field1261 > 25 || var8)) { // L: 3356
if (var0.turnLeftSequence != -1) { // L: 3357
var0.movementSequence = var0.turnLeftSequence;
} else {
var0.movementSequence = var0.walkSequence; // L: 3358
}
}
} else {
var0.rotation += var0.field1262; // L: 3362
var8 = true; // L: 3363
if (var5 < var0.field1262 || var5 > 2048 - var0.field1262) { // L: 3364
var0.rotation = var0.orientation; // L: 3365
var8 = false; // L: 3366
}
if (var0.movementSequence == var0.idleSequence && (var0.field1261 > 25 || var8)) { // L: 3368
if (var0.turnRightSequence != -1) { // L: 3369
var0.movementSequence = var0.turnRightSequence;
} else {
var0.movementSequence = var0.walkSequence; // L: 3370
}
}
}
var0.rotation &= 2047; // L: 3374
} else {
var0.field1261 = 0; // L: 3376
}
}
var0.isWalking = false; // L: 3379
SequenceDefinition var7;
if (var0.movementSequence != -1) { // L: 3380
var7 = class225.SequenceDefinition_get(var0.movementSequence); // L: 3381
if (var7 != null && var7.frameIds != null) { // L: 3382
++var0.movementFrameCycle; // L: 3383
if (var0.movementFrame < var7.frameIds.length && var0.movementFrameCycle > var7.frameLengths[var0.movementFrame]) { // L: 3384
var0.movementFrameCycle = 1; // L: 3385
++var0.movementFrame; // L: 3386
class232.method4364(var7, var0.movementFrame, var0.x, var0.y); // L: 3387
}
if (var0.movementFrame >= var7.frameIds.length) { // L: 3389
var0.movementFrameCycle = 0; // L: 3390
var0.movementFrame = 0; // L: 3391
class232.method4364(var7, var0.movementFrame, var0.x, var0.y); // L: 3392
}
} else {
var0.movementSequence = -1; // L: 3395
}
}
if (var0.spotAnimation != -1 && Client.cycle >= var0.field1249) { // L: 3397
if (var0.spotAnimationFrame < 0) { // L: 3398
var0.spotAnimationFrame = 0;
}
var5 = Varps.SpotAnimationDefinition_get(var0.spotAnimation).sequence; // L: 3399
if (var5 != -1) { // L: 3400
SequenceDefinition var6 = class225.SequenceDefinition_get(var5); // L: 3401
if (var6 != null && var6.frameIds != null) { // L: 3402
++var0.spotAnimationFrameCycle; // L: 3403
if (var0.spotAnimationFrame < var6.frameIds.length && var0.spotAnimationFrameCycle > var6.frameLengths[var0.spotAnimationFrame]) { // L: 3404
var0.spotAnimationFrameCycle = 1; // L: 3405
++var0.spotAnimationFrame; // L: 3406
class232.method4364(var6, var0.spotAnimationFrame, var0.x, var0.y); // L: 3407
}
if (var0.spotAnimationFrame >= var6.frameIds.length && (var0.spotAnimationFrame < 0 || var0.spotAnimationFrame >= var6.frameIds.length)) { // L: 3409 3410
var0.spotAnimation = -1;
}
} else {
var0.spotAnimation = -1; // L: 3413
}
} else {
var0.spotAnimation = -1; // L: 3415
}
}
if (var0.sequence != -1 && var0.sequenceDelay <= 1) { // L: 3417
var7 = class225.SequenceDefinition_get(var0.sequence); // L: 3418
if (var7.field3722 == 1 && var0.field1224 > 0 && var0.field1255 <= Client.cycle && var0.field1268 < Client.cycle) { // L: 3419 3420
var0.sequenceDelay = 1; // L: 3421
return; // L: 3448
}
}
if (var0.sequence != -1 && var0.sequenceDelay == 0) { // L: 3426
var7 = class225.SequenceDefinition_get(var0.sequence); // L: 3427
if (var7 != null && var7.frameIds != null) { // L: 3428
++var0.sequenceFrameCycle; // L: 3429
if (var0.sequenceFrame < var7.frameIds.length && var0.sequenceFrameCycle > var7.frameLengths[var0.sequenceFrame]) { // L: 3430
var0.sequenceFrameCycle = 1; // L: 3431
++var0.sequenceFrame; // L: 3432
class232.method4364(var7, var0.sequenceFrame, var0.x, var0.y); // L: 3433
}
if (var0.sequenceFrame >= var7.frameIds.length) { // L: 3435
var0.sequenceFrame -= var7.frameCount; // L: 3436
++var0.field1245; // L: 3437
if (var0.field1245 >= var7.field3721) { // L: 3438
var0.sequence = -1;
} else if (var0.sequenceFrame >= 0 && var0.sequenceFrame < var7.frameIds.length) { // L: 3439
class232.method4364(var7, var0.sequenceFrame, var0.x, var0.y); // L: 3440
} else {
var0.sequence = -1;
}
}
var0.isWalking = var7.field3712; // L: 3442
} else {
var0.sequence = -1; // L: 3444
}
}
if (var0.sequenceDelay > 0) { // L: 3446
--var0.sequenceDelay;
}
}
}
|
3e191ead451ebefdc8e174375b71521f91dce3e5 | 840 | java | Java | algs4/ch01/section2exer/FlipsMax.java | sennhvi/algorithms | 5b8f45343b9f2f367e03eeaa4e685857f0866c27 | [
"MIT"
] | null | null | null | algs4/ch01/section2exer/FlipsMax.java | sennhvi/algorithms | 5b8f45343b9f2f367e03eeaa4e685857f0866c27 | [
"MIT"
] | null | null | null | algs4/ch01/section2exer/FlipsMax.java | sennhvi/algorithms | 5b8f45343b9f2f367e03eeaa4e685857f0866c27 | [
"MIT"
] | null | null | null | 30 | 56 | 0.55119 | 10,678 | /**
* Created by sennhviwang
* Time: 12:18 AM on 5/28/15
* Not trying to handle Exceptions.
* Objects as return value and args.
*/
public class FlipsMax {
// Objects as return value, return the bigger one.
public static Counter max(Counter x, Counter y) {
if (x.tally() > y.tally()) return x;
else return y;
}
public static void main(String[] args) {
int T = Integer.parseInt(args[0]);
Counter heads = new Counter("heads");
Counter tails = new Counter("tails");
for (int t = 0; t < T; t++)
if (StdRandom.bernoulli(0.5))
heads.increment();
else tails.increment();
if (heads.tally() == tails.tally())
StdOut.println("Tie");
else StdOut.println(max(heads, tails) + "wins");
}
}
|
3e191ec4dec400b89a94a3096ca7013e8dab5ea8 | 308 | java | Java | src/main/java/InfrastructureManager/Modules/NetworkStructure/GlobalVarAccessNetworkModule.java | EdgeLab-FHDO/Edge-Diagnostic-Platform | 49f1d55f57678c62d3af1f5c307b25e41856f14c | [
"MIT"
] | 1 | 2020-08-05T23:30:00.000Z | 2020-08-05T23:30:00.000Z | src/main/java/InfrastructureManager/Modules/NetworkStructure/GlobalVarAccessNetworkModule.java | EdgeLab-FHDO/Edge-Diagnostic-Platform | 49f1d55f57678c62d3af1f5c307b25e41856f14c | [
"MIT"
] | 90 | 2020-07-26T08:22:44.000Z | 2021-04-30T14:29:51.000Z | src/main/java/InfrastructureManager/Modules/NetworkStructure/GlobalVarAccessNetworkModule.java | EdgeLab-FHDO/Edge-Diagnostic-Platform | 49f1d55f57678c62d3af1f5c307b25e41856f14c | [
"MIT"
] | 2 | 2020-11-23T17:22:04.000Z | 2021-04-17T17:27:03.000Z | 38.5 | 103 | 0.850649 | 10,679 | package InfrastructureManager.Modules.NetworkStructure;
import InfrastructureManager.ModuleManagement.ImmutablePlatformModule;
interface GlobalVarAccessNetworkModule extends ImmutablePlatformModule {
String getSharedResource(); //TODO: This is an example of a String shared resource, change the type
}
|
3e191f5bafb094657049618c3655f39221cd857b | 931 | java | Java | src/main/java/io/github/theriverelder/steelcraft/data/HeatSources.java | TheRiverElder/SteelCarft | 682957416c6dd5474f0737224b968a4692b75a01 | [
"MIT"
] | null | null | null | src/main/java/io/github/theriverelder/steelcraft/data/HeatSources.java | TheRiverElder/SteelCarft | 682957416c6dd5474f0737224b968a4692b75a01 | [
"MIT"
] | null | null | null | src/main/java/io/github/theriverelder/steelcraft/data/HeatSources.java | TheRiverElder/SteelCarft | 682957416c6dd5474f0737224b968a4692b75a01 | [
"MIT"
] | null | null | null | 31.033333 | 71 | 0.703545 | 10,680 | package io.github.theriverelder.steelcraft.data;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import java.util.HashMap;
import java.util.Map;
public class HeatSources {
private static Map<Block, Float> TEMPERATURE_MAP = new HashMap<>();
static {
TEMPERATURE_MAP.put(Blocks.LAVA_CAULDRON, 1400f);
TEMPERATURE_MAP.put(Blocks.LAVA, 1500f);
TEMPERATURE_MAP.put(Blocks.FIRE, 1000f);
TEMPERATURE_MAP.put(Blocks.SOUL_FIRE, 700f);
TEMPERATURE_MAP.put(Blocks.WATER, 5f);
TEMPERATURE_MAP.put(Blocks.WATER_CAULDRON, 15f);
TEMPERATURE_MAP.put(Blocks.ICE, -10f);
TEMPERATURE_MAP.put(Blocks.PACKED_ICE, -20f);
TEMPERATURE_MAP.put(Blocks.BLUE_ICE, -30f);
TEMPERATURE_MAP.put(Blocks.FROSTED_ICE, -10f);
}
public static float temperatureOf(Block block) {
return TEMPERATURE_MAP.getOrDefault(block, 20.0f);
}
}
|
3e19206d1127e54361dc6fb9da6acc020fac9f6c | 1,152 | java | Java | src/main/java/info/blockchain/api/FindBlockWithTimestamp.java | ElHassanBaghrar/Projet-BITCOIN | 99bc60f5d8c12bd993a94f1bcb6efb04e455e5bd | [
"Apache-2.0"
] | null | null | null | src/main/java/info/blockchain/api/FindBlockWithTimestamp.java | ElHassanBaghrar/Projet-BITCOIN | 99bc60f5d8c12bd993a94f1bcb6efb04e455e5bd | [
"Apache-2.0"
] | null | null | null | src/main/java/info/blockchain/api/FindBlockWithTimestamp.java | ElHassanBaghrar/Projet-BITCOIN | 99bc60f5d8c12bd993a94f1bcb6efb04e455e5bd | [
"Apache-2.0"
] | null | null | null | 24.510638 | 75 | 0.619792 | 10,681 | package info.blockchain.api;
import info.blockchain.api.blockexplorer.BlockExplorer;
import info.blockchain.api.blockexplorer.entity.*;
import org.apache.commons.lang3.time.StopWatch;
import java.util.List;
public class FindBlockWithTimestamp {
public static void main(String[] args) throws Exception, APIException {
BlockExplorer blockExplorer = new BlockExplorer();
List<SimpleBlock> SB = blockExplorer.getBlocks(1578006000);
/*
for (int i = 0; i < SB.size(); i++) {
SB.get(i).getHash();
System.out.println(SB.get(i).getHash());
}
*/
LatestBlock latestBlock = blockExplorer.getLatestBlock();
long latestBlockHeight = latestBlock.getHeight();
System.out.println(latestBlockHeight);
// Janvier 2020 : 610 682 à 615 424
// Fev 2020 : 615 424 à 619 578
// Mars 2020 :619 578 à 623 823
// Avril 2020 : 623 823 à 628 331
// Mai 2020 : 628 331 à 632 533
// Juin 2020 : 632 533 à 637 078
// Juillet 2020 : 637 078 à 641 662
// Aout - 17 Aout 2020 : 641 662 à 644 062
}
}
|
3e1920a88620adcbd08264972dadd684c7f4f99b | 3,702 | java | Java | CRY/library/api/fermat-cry-api/src/main/java/com/bitdubai/fermat_cry_api/layer/crypto_vault/CryptoVaultManager.java | nattyco/fermatold | 2b43a5504ecaba747b8d54676b93c98d378ba5d6 | [
"MIT"
] | null | null | null | CRY/library/api/fermat-cry-api/src/main/java/com/bitdubai/fermat_cry_api/layer/crypto_vault/CryptoVaultManager.java | nattyco/fermatold | 2b43a5504ecaba747b8d54676b93c98d378ba5d6 | [
"MIT"
] | null | null | null | CRY/library/api/fermat-cry-api/src/main/java/com/bitdubai/fermat_cry_api/layer/crypto_vault/CryptoVaultManager.java | nattyco/fermatold | 2b43a5504ecaba747b8d54676b93c98d378ba5d6 | [
"MIT"
] | 1 | 2021-08-15T20:32:35.000Z | 2021-08-15T20:32:35.000Z | 49.36 | 270 | 0.795516 | 10,682 | package com.bitdubai.fermat_cry_api.layer.crypto_vault;
import com.bitdubai.fermat_api.layer.all_definition.money.CryptoAddress;
import com.bitdubai.fermat_api.layer.all_definition.transaction_transference_protocol.TransactionSender;
import com.bitdubai.fermat_api.layer.all_definition.transaction_transference_protocol.crypto_transactions.CryptoStatus;
import com.bitdubai.fermat_api.layer.all_definition.transaction_transference_protocol.crypto_transactions.CryptoTransaction;
import com.bitdubai.fermat_cry_api.layer.crypto_vault.exceptions.CouldNotGetCryptoStatusException;
import com.bitdubai.fermat_cry_api.layer.crypto_vault.exceptions.CouldNotSendMoneyException;
import com.bitdubai.fermat_cry_api.layer.crypto_vault.exceptions.CryptoTransactionAlreadySentException;
import com.bitdubai.fermat_cry_api.layer.crypto_vault.exceptions.InsufficientCryptoFundsException;
import com.bitdubai.fermat_cry_api.layer.crypto_vault.exceptions.InvalidSendToAddressException;
import com.bitdubai.fermat_cry_api.layer.crypto_vault.exceptions.VaultNotConnectedToNetworkException;
import java.util.List;
import java.util.UUID;
/**
* Created by rodrigo on 11/06/15.
*/
public interface CryptoVaultManager extends TransactionSender<CryptoTransaction> {
public void connectToBitcoin() throws VaultNotConnectedToNetworkException;
public void disconnectFromBitcoin();
public CryptoAddress getAddress();
public List<CryptoAddress> getAddresses(int amount);
/**
* Send bitcoins to the specified address. The Address must be a valid address in the network beeing used
* and we must have enought funds to send this money
* @param walletPublicKey
* @param FermatTrId internal transaction Id - used to validate that it was not send previously.
* @param addressTo the valid address we are sending to
* @param satoshis the amount in long of satoshis
* @return the transaction Hash of the new created transaction in the vault.
* @throws InsufficientCryptoFundsException
* @throws InvalidSendToAddressException
* @throws CouldNotSendMoneyException
*/
public String sendBitcoins (String walletPublicKey, UUID FermatTrId, CryptoAddress addressTo, long satoshis) throws InsufficientCryptoFundsException, InvalidSendToAddressException, CouldNotSendMoneyException, CryptoTransactionAlreadySentException;
/**
* Send bitcoins to the specified address. The Address must be a valid address in the network beeing used
* and we must have enought funds to send this money. It allows including an Op_return output value.
* @param walletPublicKey
* @param FermatTrId
* @param addressTo
* @param satoshis
* @param op_Return
* @return
* @throws InsufficientCryptoFundsException
* @throws InvalidSendToAddressException
* @throws CouldNotSendMoneyException
* @throws CryptoTransactionAlreadySentException
*/
public String sendBitcoins (String walletPublicKey, UUID FermatTrId, CryptoAddress addressTo, long satoshis, String op_Return) throws InsufficientCryptoFundsException, InvalidSendToAddressException, CouldNotSendMoneyException, CryptoTransactionAlreadySentException;
/**
* Validates if the passes CryptoAddress is valid in the current network or not.
* @param addressTo
* @return true if is valid and we can use it, or false if not.
*/
public boolean isValidAddress(CryptoAddress addressTo);
/**
* returns the CryptoStatus of the passed transaction.
* @param txHash
* @return
* @throws CouldNotGetCryptoStatusException
*/
CryptoStatus getCryptoStatus(String txHash) throws CouldNotGetCryptoStatusException;
}
|
3e19218993dfc8f3555cad5d03a2b3fd8b40fdad | 829 | java | Java | wicked-forms/wicked-forms-wicket6/src/main/java/de/adesso/wickedforms/wicket6/components/Submittable.java | MarekChroszcz/wicked-forms | c7e53472f30b7d03b4778011eb4ce645a8c021f2 | [
"Apache-2.0"
] | 4 | 2015-03-08T13:22:49.000Z | 2017-11-29T11:01:32.000Z | wicked-forms/wicked-forms-wicket6/src/main/java/de/adesso/wickedforms/wicket6/components/Submittable.java | MarekChroszcz/wicked-forms | c7e53472f30b7d03b4778011eb4ce645a8c021f2 | [
"Apache-2.0"
] | 11 | 2017-11-29T11:09:22.000Z | 2017-11-30T07:13:15.000Z | wicked-forms/wicked-forms-wicket6/src/main/java/de/adesso/wickedforms/wicket6/components/Submittable.java | MarekChroszcz/wicked-forms | c7e53472f30b7d03b4778011eb4ce645a8c021f2 | [
"Apache-2.0"
] | 1 | 2015-08-12T08:48:00.000Z | 2015-08-12T08:48:00.000Z | 34.541667 | 77 | 0.737033 | 10,683 | /**
* Copyright 2013 Wicked Forms (https://github.com/thombergs/wicked-forms)
*
* 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.adesso.wickedforms.wicket6.components;
import de.adesso.wickedforms.model.Form;
public interface Submittable {
void onSubmit(final Form submittedData);
}
|
3e1921b299ff8d6e538fd898e73241dfe26af436 | 685 | java | Java | aquarius-common/src/main/java/com/nepxion/aquarius/common/exception/AquariusException.java | zhongzunfa/Aquarius | 44f8446d9ec3f2d7f7a0e741edab0a6c209817af | [
"Apache-2.0"
] | 410 | 2017-11-11T12:22:41.000Z | 2022-03-26T14:25:13.000Z | aquarius-common/src/main/java/com/nepxion/aquarius/common/exception/AquariusException.java | zhongzunfa/Aquarius | 44f8446d9ec3f2d7f7a0e741edab0a6c209817af | [
"Apache-2.0"
] | 5 | 2018-02-02T06:13:26.000Z | 2021-06-23T06:50:43.000Z | aquarius-common/src/main/java/com/nepxion/aquarius/common/exception/AquariusException.java | zhongzunfa/Aquarius | 44f8446d9ec3f2d7f7a0e741edab0a6c209817af | [
"Apache-2.0"
] | 156 | 2017-11-11T12:22:45.000Z | 2021-12-31T08:54:36.000Z | 22.833333 | 70 | 0.668613 | 10,684 | package com.nepxion.aquarius.common.exception;
/**
* <p>Title: Nepxion Aquarius</p>
* <p>Description: Nepxion Aquarius</p>
* <p>Copyright: Copyright (c) 2017-2050</p>
* <p>Company: Nepxion</p>
* @author Haojun Ren
* @version 1.0
*/
public class AquariusException extends RuntimeException {
private static final long serialVersionUID = 7895884193269203187L;
public AquariusException() {
super();
}
public AquariusException(String message) {
super(message);
}
public AquariusException(String message, Throwable cause) {
super(message, cause);
}
public AquariusException(Throwable cause) {
super(cause);
}
} |
3e1922aeea34668a2eb816518844990ceb5ebaff | 1,988 | java | Java | spring/src/test/java/org/axonframework/spring/messaging/ApplicationContextEventPublisherTest.java | viogate/AxonFramework | 92755c0eafc4535be21cd33b043bacb2a19e7514 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2018-06-07T15:07:26.000Z | 2018-06-07T15:07:26.000Z | spring/src/test/java/org/axonframework/spring/messaging/ApplicationContextEventPublisherTest.java | viogate/AxonFramework | 92755c0eafc4535be21cd33b043bacb2a19e7514 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | spring/src/test/java/org/axonframework/spring/messaging/ApplicationContextEventPublisherTest.java | viogate/AxonFramework | 92755c0eafc4535be21cd33b043bacb2a19e7514 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-07-13T01:53:43.000Z | 2019-07-13T01:53:43.000Z | 28 | 81 | 0.726358 | 10,685 | package org.axonframework.spring.messaging;
import org.axonframework.eventhandling.EventBus;
import org.axonframework.eventhandling.SimpleEventBus;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.PayloadApplicationEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.ArrayList;
import java.util.List;
import static org.axonframework.eventhandling.GenericEventMessage.asEventMessage;
import static org.junit.Assert.assertEquals;
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class ApplicationContextEventPublisherTest {
@Autowired
private ListenerBean listenerBean;
@Autowired
private EventBus eventBus;
@Test
public void testEventsForwardedToListenerBean() {
eventBus.publish(asEventMessage("test"));
assertEquals("test", listenerBean.getEvents().get(0));
}
@Configuration
public static class Context {
@Bean
public ListenerBean listenerBean() {
return new ListenerBean();
}
@Bean
public EventBus eventBus() {
return new SimpleEventBus();
}
@Bean
public ApplicationContextEventPublisher publisher(EventBus eventBus) {
return new ApplicationContextEventPublisher(eventBus);
}
}
public static class ListenerBean {
private List<Object> events = new ArrayList<>();
@EventListener
public void handle(PayloadApplicationEvent<String> event) {
events.add(event.getPayload());
}
public List<Object> getEvents() {
return events;
}
}
}
|
3e19231ffcab416cb70f29ed4787b7fbdc1d70dd | 881 | java | Java | src/net/wac/main/main.java | NoahEriksson3/WantACookie | d1a78ff8aa25109e3b8264ebf19bae54bf0b74e9 | [
"Apache-2.0"
] | null | null | null | src/net/wac/main/main.java | NoahEriksson3/WantACookie | d1a78ff8aa25109e3b8264ebf19bae54bf0b74e9 | [
"Apache-2.0"
] | null | null | null | src/net/wac/main/main.java | NoahEriksson3/WantACookie | d1a78ff8aa25109e3b8264ebf19bae54bf0b74e9 | [
"Apache-2.0"
] | null | null | null | 20.488372 | 65 | 0.575482 | 10,686 | package net.wac.main;
import net.wac.dependencies.print_func;
public class main {
private static String class_name = "main";
public static void main(String[] args) {
System.out.println("Want a cookie?");
System.out.println("Start of class\n" + "Name: " + class_name);
print_func p = new print_func();
p.print(" _ _ \r\n"
+ " | \\ | |\r\n"
+ " | \\| |\r\n"
+ " | . ` |\r\n"
+ " | |\\ |\r\n"
+ " |_| \\_|\r\n"
+ "");
p.print("© 2021 by Noah Eriksson");
p.print("Note to user: THIS is an alpha build of WantACookie");
p.print("This product is not for resale");
p.print("Please consult user manual if needed.");
}
}
/*
_ _
| \ | |
| \| |
| . ` |
| |\ |
|_| \_|
© 2021 by Noah Eriksson
Note to user: THIS is a alpha build of Project Peach Vibe
This product is not for resale
Please consult user manual if needed.
*/ |
3e1924385655580f52df2893d66b88c721981fd5 | 4,373 | java | Java | src/main/java/biz/a7software/slimmyinvoice/data/Fingerprint.java | a7-software/slim-my-invoice | 064c2e76b28f8489e43600e7762884852690cd42 | [
"Apache-2.0"
] | 2 | 2015-05-29T14:48:58.000Z | 2020-12-21T02:52:18.000Z | src/main/java/biz/a7software/slimmyinvoice/data/Fingerprint.java | a7-software/slim-my-invoice | 064c2e76b28f8489e43600e7762884852690cd42 | [
"Apache-2.0"
] | null | null | null | src/main/java/biz/a7software/slimmyinvoice/data/Fingerprint.java | a7-software/slim-my-invoice | 064c2e76b28f8489e43600e7762884852690cd42 | [
"Apache-2.0"
] | 4 | 2017-11-06T08:33:14.000Z | 2019-04-04T17:40:02.000Z | 33.638462 | 103 | 0.556597 | 10,687 | package biz.a7software.slimmyinvoice.data;
import biz.a7software.slimmyinvoice.helper.DbHandler;
import biz.a7software.slimmyinvoice.helper.FormatHandler;
import biz.a7software.slimmyinvoice.helper.HtmlParser;
import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The Fingerprint class describes a signature of an invoice.
* It also extracts the VAT number of the supplier from the invoice.
*/
@DatabaseTable(tableName = "fingerprint")
public class Fingerprint {
@DatabaseField(generatedId = true)
private Integer id;
@DatabaseField
private int numberOfLines;
@DatabaseField(dataType = DataType.SERIALIZABLE)
private String[] lines;
@DatabaseField
private String brutOcr;
@DatabaseField
private String vat;
public Fingerprint() {
// required for ORMLite
}
public Fingerprint(String ocrResult) {
brutOcr = ocrResult;
lines = ocrResult.split("\n");
numberOfLines = lines.length;
vat = extractVatNumberFromPlainText(ocrResult);
}
private String extractVatNumberFromPlainText(String ocrResult) {
String ocrWithoutSapce = ocrResult.replaceAll("\\s+", "").toLowerCase();
Pattern pattern = Pattern.compile("(be)?[0|1]?[0-9]{3}\\p{Punct}?[0-9]{3}\\p{Punct}?[0-9]{3}");
Matcher matcher = pattern.matcher(ocrWithoutSapce);
List<String> validVATs = new ArrayList<String>();
while (matcher.find()) {
String vat = FormatHandler.getInstance().formatInputVat(matcher.group());
if (FormatHandler.getInstance().isValidVAT(vat)) {
validVATs.add(vat);
}
}
// Remove the VAT number of the user (that must also appear on the invoice)
validVATs.remove(DbHandler.getInstance().getUser());
if (validVATs.size() == 0) {
return null;
} else { // validVATs.size() > 1
// Remove wrong VAT numbers
return filterList(validVATs, ocrResult);
}
}
private String filterList(List<String> validVATs, String ocrResult) {
double bestScore = 0.0;
int bestIndex = 0;
int listSize = validVATs.size();
for (int i = 0; i < listSize; i++) {
Supplier supplier = HtmlParser.getInstance().retrieveSupplierFromVATNum(validVATs.get(i));
if (supplier != null) {
List<String> keywords = new ArrayList<String>();
if (supplier.getName() != null) {
String[] names = supplier.getName().toLowerCase().split("\\s+");
for (int j = 0; j < names.length; j++) {
keywords.add(names[j]);
}
}
Address address = supplier.getAddress();
if (address != null) {
if (address.getStreet() != null)
keywords.add(address.getStreet());
if (address.getNumber() != null)
keywords.add(address.getNumber());
if (address.getCity() != null)
keywords.add(address.getCity());
if (address.getZip() != null)
keywords.add(address.getZip());
}
ocrResult = ocrResult.toLowerCase();
int matches = 0;
for (int k = 0; k < keywords.size(); k++) {
if (ocrResult.contains(keywords.get(k).toLowerCase())) {
matches++;
}
}
if (keywords.size() > 0) {
double score = matches / (double) keywords.size();
if (score > bestScore) {
bestScore = score;
bestIndex = i;
}
}
}
}
return validVATs.get(bestIndex);
}
public int getNumberOfLines() {
return numberOfLines;
}
public String[] getLines() {
return lines;
}
public String getBrutOcr() {
return brutOcr;
}
public String getVat() {
return vat;
}
} |
3e1924ae56f0976f2fe352fb4f03d61a6249bcf6 | 5,409 | java | Java | _src/Chapter10/gateway/src/main/java/com/mycompany/myapp/web/rest/ProductOrderResource.java | paullewallencom/java-978-1-8388-2498-3 | c90f97669742802a2893e8ac83effd3fb8da5232 | [
"Apache-2.0"
] | 107 | 2018-03-25T04:45:19.000Z | 2022-01-05T11:47:37.000Z | _src/Chapter10/gateway/src/main/java/com/mycompany/myapp/web/rest/ProductOrderResource.java | paullewallencom/java-978-1-8388-2498-3 | c90f97669742802a2893e8ac83effd3fb8da5232 | [
"Apache-2.0"
] | 20 | 2020-01-09T19:22:41.000Z | 2022-03-17T22:24:46.000Z | _src/Chapter10/gateway/src/main/java/com/mycompany/myapp/web/rest/ProductOrderResource.java | paullewallencom/java-978-1-8388-2498-3 | c90f97669742802a2893e8ac83effd3fb8da5232 | [
"Apache-2.0"
] | 62 | 2018-03-20T10:45:07.000Z | 2022-02-18T04:01:33.000Z | 42.257813 | 166 | 0.718987 | 10,688 | package com.mycompany.myapp.web.rest;
import com.codahale.metrics.annotation.Timed;
import com.mycompany.myapp.domain.ProductOrder;
import com.mycompany.myapp.service.ProductOrderService;
import com.mycompany.myapp.web.rest.errors.BadRequestAlertException;
import com.mycompany.myapp.web.rest.util.HeaderUtil;
import com.mycompany.myapp.web.rest.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
/**
* REST controller for managing ProductOrder.
*/
@RestController
@RequestMapping("/api")
public class ProductOrderResource {
private final Logger log = LoggerFactory.getLogger(ProductOrderResource.class);
private static final String ENTITY_NAME = "productOrder";
private final ProductOrderService productOrderService;
public ProductOrderResource(ProductOrderService productOrderService) {
this.productOrderService = productOrderService;
}
/**
* POST /product-orders : Create a new productOrder.
*
* @param productOrder the productOrder to create
* @return the ResponseEntity with status 201 (Created) and with body the new productOrder, or with status 400 (Bad Request) if the productOrder has already an ID
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PostMapping("/product-orders")
@Timed
public ResponseEntity<ProductOrder> createProductOrder(@Valid @RequestBody ProductOrder productOrder) throws URISyntaxException {
log.debug("REST request to save ProductOrder : {}", productOrder);
if (productOrder.getId() != null) {
throw new BadRequestAlertException("A new productOrder cannot already have an ID", ENTITY_NAME, "idexists");
}
ProductOrder result = productOrderService.save(productOrder);
return ResponseEntity.created(new URI("/api/product-orders/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* PUT /product-orders : Updates an existing productOrder.
*
* @param productOrder the productOrder to update
* @return the ResponseEntity with status 200 (OK) and with body the updated productOrder,
* or with status 400 (Bad Request) if the productOrder is not valid,
* or with status 500 (Internal Server Error) if the productOrder couldn't be updated
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PutMapping("/product-orders")
@Timed
public ResponseEntity<ProductOrder> updateProductOrder(@Valid @RequestBody ProductOrder productOrder) throws URISyntaxException {
log.debug("REST request to update ProductOrder : {}", productOrder);
if (productOrder.getId() == null) {
return createProductOrder(productOrder);
}
ProductOrder result = productOrderService.save(productOrder);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, productOrder.getId().toString()))
.body(result);
}
/**
* GET /product-orders : get all the productOrders.
*
* @param pageable the pagination information
* @return the ResponseEntity with status 200 (OK) and the list of productOrders in body
*/
@GetMapping("/product-orders")
@Timed
public ResponseEntity<List<ProductOrder>> getAllProductOrders(Pageable pageable) {
log.debug("REST request to get a page of ProductOrders");
Page<ProductOrder> page = productOrderService.findAll(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/product-orders");
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
/**
* GET /product-orders/:id : get the "id" productOrder.
*
* @param id the id of the productOrder to retrieve
* @return the ResponseEntity with status 200 (OK) and with body the productOrder, or with status 404 (Not Found)
*/
@GetMapping("/product-orders/{id}")
@Timed
public ResponseEntity<ProductOrder> getProductOrder(@PathVariable Long id) {
log.debug("REST request to get ProductOrder : {}", id);
ProductOrder productOrder = productOrderService.findOne(id);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(productOrder));
}
/**
* DELETE /product-orders/:id : delete the "id" productOrder.
*
* @param id the id of the productOrder to delete
* @return the ResponseEntity with status 200 (OK)
*/
@DeleteMapping("/product-orders/{id}")
@Timed
public ResponseEntity<Void> deleteProductOrder(@PathVariable Long id) {
log.debug("REST request to delete ProductOrder : {}", id);
productOrderService.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}
}
|
3e1925646af889f8941ab353012ccaf03c5bfd01 | 110 | java | Java | core/src/main/java/com/bounteous/core/models/datatypeproperties/CfxTagField.java | Bounteous-Inc/aem-contentfragment-extras | ffa77b88d335536b85223a6d4e67d9cbfe5ba09e | [
"Apache-2.0"
] | 10 | 2020-09-28T14:37:55.000Z | 2022-03-23T08:52:12.000Z | core/src/main/java/com/bounteous/core/models/datatypeproperties/CfxTagField.java | Bounteous-Inc/aem-contentfragment-extras | ffa77b88d335536b85223a6d4e67d9cbfe5ba09e | [
"Apache-2.0"
] | 1 | 2022-02-16T13:31:35.000Z | 2022-02-16T13:31:35.000Z | core/src/main/java/com/bounteous/core/models/datatypeproperties/CfxTagField.java | isabella232/aem-cf-extras | ffa77b88d335536b85223a6d4e67d9cbfe5ba09e | [
"Apache-2.0"
] | 1 | 2022-02-16T10:31:24.000Z | 2022-02-16T10:31:24.000Z | 22 | 53 | 0.845455 | 10,689 | package com.bounteous.core.models.datatypeproperties;
public interface CfxTagField extends CfxModelField {
}
|
3e1926ce282144b3d941f3bfa5561da7c05a82a7 | 2,338 | java | Java | src/main/java/jtrade/io/BarTickFileReader.java | redame/jtrade | 369d64e608267241078d0dd28ffb175fcf02a549 | [
"Apache-2.0"
] | 4 | 2016-07-12T15:42:40.000Z | 2016-11-24T20:25:13.000Z | src/main/java/jtrade/io/BarTickFileReader.java | gaoxiaojun/jtrade | 369d64e608267241078d0dd28ffb175fcf02a549 | [
"Apache-2.0"
] | null | null | null | src/main/java/jtrade/io/BarTickFileReader.java | gaoxiaojun/jtrade | 369d64e608267241078d0dd28ffb175fcf02a549 | [
"Apache-2.0"
] | 6 | 2015-05-27T15:17:19.000Z | 2019-09-05T01:55:55.000Z | 24.354167 | 92 | 0.65355 | 10,690 | package jtrade.io;
import java.io.File;
import java.io.IOException;
import java.util.NavigableMap;
import java.util.TreeMap;
import jtrade.marketfeed.Bar;
import jtrade.marketfeed.Tick;
import jtrade.util.Util;
import org.joda.time.DateTime;
import org.joda.time.Duration;
public class BarTickFileReader implements BarReader {
TickReader reader;
int barSizeMillis;
Duration barSize;
Bar currBar;
Bar prevBar;
public BarTickFileReader(File file, int barSizeSeconds) throws IOException {
reader = MarketDataIO.createTickReader(file, true);
barSizeMillis = barSizeSeconds * 1000;
barSize = new Duration(barSizeMillis);
}
@Override
public Bar readBar() throws IOException {
Tick tick = null;
double open = 0.0, high = 0.0, low = 0.0, close = 0.0, wap = 0.0;
int trades = 0;
long volume = 0;
while ((tick = reader.readTick()) != null) {
long now = tick.getDateTime().getMillis();
double tickPrice = tick.getPrice();
int tickVol = tick.getLastSize();
boolean complete = false;
if (currBar == null) {
currBar = new Bar(barSize, tick.getSymbol(), new DateTime(now - (now % barSizeMillis)));
} else if (currBar.getDateTime().getMillis() + barSizeMillis <= now) {
prevBar = currBar;
currBar = new Bar(barSize, tick.getSymbol(), new DateTime(now - (now % barSizeMillis)));
complete = true;
}
if (open == 0.0) {
open = tickPrice;
high = tickPrice;
low = tickPrice;
} else {
if (tickPrice > high) {
high = tickPrice;
}
if (tickPrice < low) {
low = tickPrice;
}
}
close = tickPrice;
wap = Util.round((wap * volume + tickPrice * tickVol) / (volume + tickVol), 2);
volume += tickVol;
trades++;
currBar.setValues(open, high, low, close, wap, volume, trades);
if (complete) {
return prevBar;
}
}
if (currBar != null && currBar.isComplete()) {
return currBar;
}
return null;
}
@Override
public NavigableMap<DateTime, Bar> readBars() throws IOException {
try {
NavigableMap<DateTime, Bar> bars = new TreeMap<DateTime, Bar>();
Bar bar = null;
while ((bar = readBar()) != null) {
bars.put(bar.getDateTime(), bar);
}
return bars;
} finally {
try {
close();
} catch (IOException e) {
}
}
}
@Override
public void close() throws IOException {
reader.close();
}
}
|
3e19272ab72aaa507421932f885798253c7cbe2e | 5,773 | java | Java | concourse-driver-java/src/test/java/com/cinchapi/concourse/util/TimestampsTest.java | vinooganesh/concourse | e29a04aa650eb8763e7fd40705d8d915d754f471 | [
"ECL-2.0",
"Apache-2.0",
"MIT"
] | 371 | 2015-01-07T05:05:59.000Z | 2022-03-01T13:36:32.000Z | concourse-driver-java/src/test/java/com/cinchapi/concourse/util/TimestampsTest.java | vinooganesh/concourse | e29a04aa650eb8763e7fd40705d8d915d754f471 | [
"ECL-2.0",
"Apache-2.0",
"MIT"
] | 158 | 2015-01-03T11:39:23.000Z | 2022-03-05T19:19:25.000Z | concourse-driver-java/src/test/java/com/cinchapi/concourse/util/TimestampsTest.java | vinooganesh/concourse | e29a04aa650eb8763e7fd40705d8d915d754f471 | [
"ECL-2.0",
"Apache-2.0",
"MIT"
] | 370 | 2015-01-07T15:58:50.000Z | 2021-01-13T09:56:29.000Z | 41.235714 | 135 | 0.646111 | 10,691 | /*
* Copyright (c) 2013-2021 Cinchapi 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.cinchapi.concourse.util;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
import com.cinchapi.concourse.Timestamp;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
/**
* Unit tests for {@link com.cinchapi.concourse.util.Timestamps}.
*
* @author knd
*/
public class TimestampsTest {
@Test
public void testFindNearestSuccessorForTimestampWithStartTimestampLessThanFirstTimestampInChronology() {
Set<Timestamp> timestamps = new LinkedHashSet<Timestamp>();
timestamps.add(Timestamp.fromMicros(1000L));
for (int i = 0; i < Random.getScaleCount(); i++) {
long increment = 0;
while (increment == 0) {
increment = Math.abs(Random.getScaleCount());
}
timestamps.add(Timestamp.fromMicros(
Iterables.getLast(timestamps).getMicros() + increment));
}
Timestamp startTimestamp = Timestamp.epoch();
Assert.assertEquals(0, Timestamps
.findNearestSuccessorForTimestamp(timestamps, startTimestamp));
}
@Test
public void testFindNearestSuccessorForTimestampWithStartTimestampGreaterThanLastTimestampInChronology() {
Set<Timestamp> timestamps = new LinkedHashSet<Timestamp>();
timestamps.add(Timestamp.fromMicros(1000L));
for (int i = 0; i < Random.getScaleCount(); i++) {
long increment = 0;
while (increment == 0) {
increment = Math.abs(Random.getScaleCount());
}
timestamps.add(Timestamp.fromMicros(
Iterables.getLast(timestamps).getMicros() + increment));
}
Timestamp startTimestamp = Timestamp
.fromMicros(Iterables.getLast(timestamps).getMicros() + 1000L);
Assert.assertEquals(timestamps.size(), Timestamps
.findNearestSuccessorForTimestamp(timestamps, startTimestamp));
}
@Test
public void testFindNearestSuccessorForTimestampWithStartTimestampEqualToATimestampInChronology() {
Set<Timestamp> timestamps = new LinkedHashSet<Timestamp>();
timestamps.add(Timestamp.fromMicros(1000L));
for (int i = 0; i < Random.getScaleCount(); i++) {
long increment = 0;
while (increment == 0) {
increment = Math.abs(Random.getScaleCount());
}
timestamps.add(Timestamp.fromMicros(
Iterables.getLast(timestamps).getMicros() + increment));
}
Timestamp startTimestamp = Timestamp
.fromMicros(Iterables.getFirst(timestamps, null).getMicros());
Assert.assertEquals(0, Timestamps
.findNearestSuccessorForTimestamp(timestamps, startTimestamp));
startTimestamp = Timestamp.fromMicros(
Iterables.get(timestamps, timestamps.size() / 2).getMicros());
Assert.assertEquals(timestamps.size() / 2, Timestamps
.findNearestSuccessorForTimestamp(timestamps, startTimestamp));
startTimestamp = Timestamp
.fromMicros(Iterables.getLast(timestamps).getMicros());
Assert.assertEquals(timestamps.size() - 1, Timestamps
.findNearestSuccessorForTimestamp(timestamps, startTimestamp));
}
@Test
public void testFindNearestSuccessorForTimestampWithStartTimestampGreaterThanFirstTimestampAndLessThanLastTimestampInChronology() {
Set<Timestamp> timestamps = new LinkedHashSet<Timestamp>();
timestamps.add(Timestamp.fromMicros(1000L));
for (int i = 0; i < Random.getScaleCount(); i++) {
long increment = 0;
while (increment == 0) {
increment = Math.abs(Random.getScaleCount()) + 100L;
}
timestamps.add(Timestamp.fromMicros(
Iterables.getLast(timestamps).getMicros() + increment));
}
Timestamp abitrary = Iterables.get(timestamps, timestamps.size() / 3);
Timestamp abitrarySuccessor = Iterables.get(timestamps,
timestamps.size() / 3 + 1);
Timestamp startTimestamp = Timestamp.fromMicros(
(abitrary.getMicros() + abitrarySuccessor.getMicros()) / 2);
Assert.assertEquals(timestamps.size() / 3 + 1, Timestamps
.findNearestSuccessorForTimestamp(timestamps, startTimestamp));
}
@Test
public void testTimestampComparableInChronologicalOrder() {
List<Timestamp> timestamps = Lists.newArrayList();
for (int i = 0; i < 10; ++i) {
timestamps.add(Timestamp.now());
Random.tinySleep();
}
java.util.Collections.shuffle(timestamps);
Set<Timestamp> sorted = Sets.newTreeSet(timestamps);
Timestamp previous = null;
for (Timestamp timestamp : sorted) {
if(previous != null) {
Assert.assertTrue(
previous.getInstant().isBefore(timestamp.getInstant()));
}
previous = timestamp;
}
}
}
|
3e1929246400a3225ee3ab822823eed80c620d87 | 1,698 | java | Java | openjdk/jdk/test/java/nio/channels/Selector/CloseInvalidatesKeys.java | liumapp/compiling-jvm | 962f37e281f4d9ec03486d9380c43b7260790eaa | [
"Apache-2.0"
] | 2 | 2017-02-05T10:25:47.000Z | 2017-02-07T00:55:29.000Z | test/jdk/java/nio/channels/Selector/CloseInvalidatesKeys.java | desiyonan/OpenJDK8 | 74d4f56b6312c303642e053e5d428b44cc8326c5 | [
"MIT"
] | null | null | null | test/jdk/java/nio/channels/Selector/CloseInvalidatesKeys.java | desiyonan/OpenJDK8 | 74d4f56b6312c303642e053e5d428b44cc8326c5 | [
"MIT"
] | 1 | 2020-11-04T07:02:06.000Z | 2020-11-04T07:02:06.000Z | 34.653061 | 79 | 0.686101 | 10,692 | /*
* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; 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.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4783178
* @summary Ensure that closing a selector invalidates its keys
*/
import java.nio.channels.*;
public class CloseInvalidatesKeys {
public static void main (String [] args) throws Exception {
DatagramChannel ch = DatagramChannel.open();
try {
ch.configureBlocking(false);
Selector sel = Selector.open();
SelectionKey key = ch.register(sel, SelectionKey.OP_WRITE);
sel.close();
if (key.isValid())
throw new Exception("Key valid after selector closed");
} finally {
ch.close();
}
}
}
|
3e19292f4a9c9173e00c572155387952cd968234 | 611 | java | Java | ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/project/projectteam/transactional/PendingPartnerNotificationService.java | danielholdsworth/innovation-funding-service | 39748ba4f574c29f3d09adde7af60ca85ffeec06 | [
"MIT"
] | null | null | null | ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/project/projectteam/transactional/PendingPartnerNotificationService.java | danielholdsworth/innovation-funding-service | 39748ba4f574c29f3d09adde7af60ca85ffeec06 | [
"MIT"
] | null | null | null | ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/project/projectteam/transactional/PendingPartnerNotificationService.java | danielholdsworth/innovation-funding-service | 39748ba4f574c29f3d09adde7af60ca85ffeec06 | [
"MIT"
] | null | null | null | 47 | 120 | 0.842881 | 10,693 | package org.innovateuk.ifs.project.projectteam.transactional;
import org.innovateuk.ifs.commons.security.NotSecured;
import org.innovateuk.ifs.organisation.domain.Organisation;
import org.innovateuk.ifs.project.core.domain.PartnerOrganisation;
import org.innovateuk.ifs.project.core.domain.Project;
import org.springframework.security.access.prepost.PreAuthorize;
public interface PendingPartnerNotificationService {
@NotSecured(value = "This Service is to be used within other secured services", mustBeSecuredByOtherServices = true)
void sendNotifications(PartnerOrganisation partnerOrganisation);
} |
3e19296e9ad933adaffe3f3aa6ffe215a2e4aa75 | 1,317 | java | Java | src/engine/racedetectionengine/goldilocks/GoldilocksState.java | umangm/rapid | f598aa26579108d6b021fe4560f3c4adb6e1b0b5 | [
"MIT"
] | 17 | 2018-08-02T01:40:30.000Z | 2022-03-31T11:32:06.000Z | src/engine/racedetectionengine/goldilocks/GoldilocksState.java | umangm/rapid | f598aa26579108d6b021fe4560f3c4adb6e1b0b5 | [
"MIT"
] | 1 | 2018-10-14T20:12:34.000Z | 2018-10-15T02:30:15.000Z | src/engine/racedetectionengine/goldilocks/GoldilocksState.java | umangm/rapid | f598aa26579108d6b021fe4560f3c4adb6e1b0b5 | [
"MIT"
] | 3 | 2020-11-18T12:53:39.000Z | 2021-11-21T15:38:29.000Z | 28.021277 | 79 | 0.738041 | 10,694 | package engine.racedetectionengine.goldilocks;
import java.util.HashMap;
import java.util.HashSet;
import engine.racedetectionengine.State;
import event.Lock;
import event.Thread;
import event.Variable;
public class GoldilocksState extends State {
// Data for the algorithm data
public HashMap<Variable, HashSet<Lock>> writeLockSet;
// public HashMap<Variable, HashSet<Thread>> writeThreadSet;
public HashMap<Lock, HashMap<Variable, HashSet<Lock>>> readLockSet;
// public HashMap<Thread, HashMap<Variable, HashSet<Thread>>> readThreadSet;
public HashMap<Thread, Lock> threadLocks;
public int verbosity;
public GoldilocksState(HashSet<Thread> tSet, int verbosity) {
this.verbosity = verbosity;
initData(tSet);
}
public void initData(HashSet<Thread> tSet) {
writeLockSet = new HashMap<Variable, HashSet<Lock>> ();
// writeThreadSet = new HashMap<Variable, HashSet<Thread>> ();
readLockSet = new HashMap<Lock, HashMap<Variable, HashSet<Lock>>> ();
// readThreadSet = new HashMap<Thread, HashMap<Variable, HashSet<Thread>>> ();
this.threadLocks = new HashMap<Thread, Lock> ();
for(Thread t: tSet){
Lock tLock = new Lock("ThreadLock-" + t.getName());
this.threadLocks.put(t, tLock);
}
}
@Override
public void printMemory() {
System.out.println("Dummy method called");
}
} |
3e1929f5abaea056202f70b66e4903945a9be2a4 | 4,342 | java | Java | wink-itests/wink-itest/wink-itest-params/src/test/java/org/apache/wink/itest/CookieParamTest.java | berezovskyi/apache-wink | bafd9208fa87e6433254282d452a7f6e768f1bbb | [
"Apache-2.0"
] | 11 | 2015-05-05T03:56:42.000Z | 2021-11-10T16:17:15.000Z | wink-itests/wink-itest/wink-itest-params/src/test/java/org/apache/wink/itest/CookieParamTest.java | AgreePro/wink | bafd9208fa87e6433254282d452a7f6e768f1bbb | [
"Apache-2.0"
] | 2 | 2015-10-23T21:55:46.000Z | 2016-03-09T23:15:02.000Z | wink-itests/wink-itest/wink-itest-params/src/test/java/org/apache/wink/itest/CookieParamTest.java | AgreePro/wink | bafd9208fa87e6433254282d452a7f6e768f1bbb | [
"Apache-2.0"
] | 16 | 2015-10-20T17:38:27.000Z | 2021-11-10T16:17:08.000Z | 39.117117 | 108 | 0.624597 | 10,695 | /*
* 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.wink.itest;
import java.io.IOException;
import java.util.Arrays;
import junit.framework.TestCase;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.wink.test.integration.ServerEnvironmentInfo;
/**
* Tests the use of cookie parameter.
*/
public class CookieParamTest extends TestCase {
protected HttpClient httpclient = new HttpClient();
private static String BASE_URI =
ServerEnvironmentInfo.getBaseURI() + "/params/cookiemonster";
static {
if(ServerEnvironmentInfo.isRestFilterUsed()) {
BASE_URI = ServerEnvironmentInfo.getBaseURI() + "/cookiemonster";
}
}
/**
* Tests that a cookie parameter is retrieved.
*/
public void testCookieParam() {
try {
PutMethod httpMethod = new PutMethod();
httpMethod.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
httpMethod.setURI(new URI(BASE_URI, false));
System.out.println("Request headers:");
System.out.println(Arrays.asList(httpMethod.getRequestHeaders()));
httpclient = new HttpClient();
try {
int result = httpclient.executeMethod(httpMethod);
System.out.println("Response status code: " + result);
System.out.println("Response body: ");
String responseBody = httpMethod.getResponseBodyAsString();
System.out.println(responseBody);
System.out.println("Response headers:");
System.out.println(Arrays.asList(httpMethod.getResponseHeaders()));
assertEquals(200, result);
assertEquals("swiped:" + 0, responseBody);
} catch (IOException ioe) {
ioe.printStackTrace();
fail(ioe.getMessage());
} finally {
httpMethod.releaseConnection();
}
System.out.println("---");
httpMethod = new PutMethod();
httpMethod.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
httpMethod.setURI(new URI(BASE_URI, false));
httpMethod.setRequestHeader("Cookie", "jar=1");
System.out.println("Request headers:");
System.out.println(Arrays.asList(httpMethod.getRequestHeaders()));
httpclient = new HttpClient();
try {
int result = httpclient.executeMethod(httpMethod);
System.out.println("Response status code: " + result);
System.out.println("Response body: ");
String responseBody = httpMethod.getResponseBodyAsString();
System.out.println(responseBody);
System.out.println("Response headers:");
System.out.println(Arrays.asList(httpMethod.getResponseHeaders()));
assertEquals(200, result);
assertEquals("swiped:" + 1, responseBody);
} catch (IOException ioe) {
ioe.printStackTrace();
fail(ioe.getMessage());
} finally {
httpMethod.releaseConnection();
}
} catch (URIException e) {
e.printStackTrace();
fail(e.getMessage());
}
}
}
|
3e1929f92017b75a85eea4bcbfe7c3d39e524f8f | 1,473 | java | Java | app/src/main/java/com/example/bookshop/Global/Filter.java | mamad2050/BookShop | 836ff958706367ed61e6da8a62a7a370878ee2b6 | [
"MIT"
] | null | null | null | app/src/main/java/com/example/bookshop/Global/Filter.java | mamad2050/BookShop | 836ff958706367ed61e6da8a62a7a370878ee2b6 | [
"MIT"
] | null | null | null | app/src/main/java/com/example/bookshop/Global/Filter.java | mamad2050/BookShop | 836ff958706367ed61e6da8a62a7a370878ee2b6 | [
"MIT"
] | null | null | null | 22.661538 | 91 | 0.630686 | 10,696 | package com.example.bookshop.Global;
import com.example.bookshop.Adapter.AllBookAdapter;
import com.example.bookshop.Model.Book;
import java.util.ArrayList;
import java.util.List;
public class Filter extends android.widget.Filter {
AllBookAdapter searchAdapter;
List<Book> data;
public Filter(AllBookAdapter searchAdapter, List<Book> data) {
this.searchAdapter = searchAdapter;
this.data = data;
}
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults filterResults = new FilterResults();
if (charSequence != null && charSequence.length()>0){
charSequence = charSequence.toString().toUpperCase();
List<Book> data_filer = new ArrayList<>();
for (int i=0 ; i<data.size() ; i++ ){
if (data.get(i).getName().toUpperCase().contains(charSequence)){
data_filer.add(data.get(i));
}
}
filterResults.count = data_filer.size();
filterResults.values = data_filer;
}else {
filterResults.count = data.size();
filterResults.values = data;
}
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
searchAdapter.data = (List<Book>)filterResults.values;
searchAdapter.notifyDataSetChanged();
}
}
|
3e192a4deb8e6706aabe3c28a3ad0fe2e49f9101 | 1,454 | java | Java | src/com/xmut/estore/test/ComputerDAOTest.java | DdragonXuzc/EStore2 | cf41a739d27e69ca9dd9f7b49a8ed29b7350c7b9 | [
"MIT"
] | 246 | 2018-01-20T06:11:39.000Z | 2022-03-21T01:52:46.000Z | src/com/xmut/estore/test/ComputerDAOTest.java | DdragonXuzc/EStore2 | cf41a739d27e69ca9dd9f7b49a8ed29b7350c7b9 | [
"MIT"
] | 3 | 2019-10-22T13:17:29.000Z | 2021-10-30T10:22:36.000Z | src/com/xmut/estore/test/ComputerDAOTest.java | DdragonXuzc/EStore2 | cf41a739d27e69ca9dd9f7b49a8ed29b7350c7b9 | [
"MIT"
] | 86 | 2018-01-22T07:04:30.000Z | 2022-03-07T19:20:43.000Z | 23.451613 | 70 | 0.735901 | 10,697 | package com.xmut.estore.test;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import com.xmut.estore.dao.ComputerDAO;
import com.xmut.estore.dao.impl.ComputerDAOImpl;
import com.xmut.estore.domain.Computer;
import com.xmut.estore.web.CriteriaComputer;
import com.xmut.estore.web.Page;
class ComputerDAOTest {
private ComputerDAO computerDAO = new ComputerDAOImpl();
@Test
void testGetComputer() {
Computer computer = computerDAO.getComputer(1);
System.out.println(computer);
}
@Test
void testGetPage() {
CriteriaComputer cc = new CriteriaComputer(0, Integer.MAX_VALUE, 3);
Page<Computer> page = computerDAO.getPage(cc);
System.out.println("pageNo: "+ page.getPageNo());
System.out.println("totalPageNumber: "+page.getTotalPageNumber());
System.out.println("list: "+page.getList());
System.out.println("prevPage: "+page.getPrevPage());
System.out.println("nextPage: "+page.getNextPage());
}
@Test
void testGetTotalComputerNumber() {
fail("Not yet implemented");
}
@Test
void testGetPageList() {
fail("Not yet implemented");
}
@Test
void testGetStoreNumber() {
int storeNumber = computerDAO.getStoreNumber(5);
System.out.println(storeNumber);
}
@Test
void testGetComputerImgUrl() {
String url = computerDAO.getComputerImgUrl(1);
System.out.println(url);
}
@Test
void testBatchUpdateStoreNumberAndSalesAmount() {
fail("Not yet implemented");
}
}
|
3e192a9d5a4908ad910d8a84461ed07d75a828f8 | 2,331 | java | Java | SW/CreaminoJavaInterface/src/creaminointerface/LabelController.java | ArcesUnibo/creamino | d4b5ae3e244e4687ec7cb32c57e1ed2aaffbda1c | [
"MIT"
] | 10 | 2018-09-05T13:38:45.000Z | 2021-06-29T10:02:03.000Z | SW/CreaminoJavaInterface/src/creaminointerface/LabelController.java | ArcesUnibo/creamino | d4b5ae3e244e4687ec7cb32c57e1ed2aaffbda1c | [
"MIT"
] | null | null | null | SW/CreaminoJavaInterface/src/creaminointerface/LabelController.java | ArcesUnibo/creamino | d4b5ae3e244e4687ec7cb32c57e1ed2aaffbda1c | [
"MIT"
] | 1 | 2019-08-20T20:17:28.000Z | 2019-08-20T20:17:28.000Z | 28.777778 | 80 | 0.706564 | 10,698 | /*
* The MIT License
*
* Copyright 2017 Alma Mater Studiorum - Università di Bologna.
*
* 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 creaminointerface;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
/**
* FXML Controller class
*
* @author Matteo Chiesi - University of Bologna
*/
public class LabelController extends AnchorPane implements Initializable {
public final String[] CHLabels = new String[64];
@FXML
public static Button ResetLabel;
@FXML
public Label CH1;
@FXML
public static List<TextField> LabelList;
public LabelController(){
}
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
}
@FXML
private void handleResetButton(ActionEvent event){
for(int i=0;i<64;i++){
CHLabels[i] = LabelList.get(i).getText();
}
}
public String[] getString(){
return CHLabels;
}
}
|
3e192b0d21998454bda9f95c335b707f0bd9b70a | 414 | java | Java | app/src/main/java/com/dtnguy/camerachathead/threadpool/MainThreadExecutor.java | dn00/camera-chat-head | 2b1a95600dd30e7952d08cfed354cec4dda44b9d | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/dtnguy/camerachathead/threadpool/MainThreadExecutor.java | dn00/camera-chat-head | 2b1a95600dd30e7952d08cfed354cec4dda44b9d | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/dtnguy/camerachathead/threadpool/MainThreadExecutor.java | dn00/camera-chat-head | 2b1a95600dd30e7952d08cfed354cec4dda44b9d | [
"Apache-2.0"
] | null | null | null | 20.7 | 72 | 0.7343 | 10,699 | package com.dtnguy.camerachathead.threadpool;
import android.os.Handler;
import android.os.Looper;
import java.util.concurrent.Executor;
/**
* Created by dtngu_000 on 1/18/2017.
*/
public class MainThreadExecutor implements Executor {
private final Handler handler = new Handler(Looper.getMainLooper());
@Override
public void execute(Runnable runnable) {
handler.post(runnable);
}
} |
3e192bfbb59b4cf0bd96b1de21c8798659cd3838 | 3,706 | java | Java | src/test/java/org/dependencytrack/policy/CpePolicyEvaluatorTest.java | S-Callier/dependency-track | 711e991fdff70139458565a638babf6391ab2d11 | [
"Apache-2.0"
] | 953 | 2018-06-18T20:22:00.000Z | 2022-03-31T14:27:27.000Z | src/test/java/org/dependencytrack/policy/CpePolicyEvaluatorTest.java | S-Callier/dependency-track | 711e991fdff70139458565a638babf6391ab2d11 | [
"Apache-2.0"
] | 1,154 | 2018-06-19T15:20:37.000Z | 2022-03-31T14:14:59.000Z | src/test/java/org/dependencytrack/policy/CpePolicyEvaluatorTest.java | S-Callier/dependency-track | 711e991fdff70139458565a638babf6391ab2d11 | [
"Apache-2.0"
] | 304 | 2018-07-04T18:39:16.000Z | 2022-03-28T10:53:54.000Z | 46.911392 | 165 | 0.726659 | 10,700 | /*
* This file is part of Dependency-Track.
*
* 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
* Copyright (c) Steve Springett. All Rights Reserved.
*/
package org.dependencytrack.policy;
import org.dependencytrack.PersistenceCapableTest;
import org.dependencytrack.model.Component;
import org.dependencytrack.model.Policy;
import org.dependencytrack.model.PolicyCondition;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
public class CpePolicyEvaluatorTest extends PersistenceCapableTest {
@Test
public void hasMatch() {
Policy policy = qm.createPolicy("Test Policy", Policy.Operator.ANY, Policy.ViolationState.INFO);
PolicyCondition condition = qm.createPolicyCondition(policy, PolicyCondition.Subject.CPE, PolicyCondition.Operator.MATCHES, "cpe:/a:acme:application:1.0.0");
Component component = new Component();
component.setCpe("cpe:/a:acme:application:1.0.0");
PolicyEvaluator evaluator = new CpePolicyEvaluator();
List<PolicyConditionViolation> violations = evaluator.evaluate(policy, component);
Assert.assertEquals(1, violations.size());
PolicyConditionViolation violation = violations.get(0);
Assert.assertEquals(component, violation.getComponent());
Assert.assertEquals(condition, violation.getPolicyCondition());
}
@Test
public void noMatch() {
Policy policy = qm.createPolicy("Test Policy", Policy.Operator.ANY, Policy.ViolationState.INFO);
qm.createPolicyCondition(policy, PolicyCondition.Subject.CPE, PolicyCondition.Operator.MATCHES, "cpe:/a:acme:application:1.0.0");
Component component = new Component();
component.setCpe("cpe:/a:acme:application:2.0.0");
PolicyEvaluator evaluator = new CpePolicyEvaluator();
List<PolicyConditionViolation> violations = evaluator.evaluate(policy, component);
Assert.assertEquals(0, violations.size());
}
@Test
public void wrongSubject() {
Policy policy = qm.createPolicy("Test Policy", Policy.Operator.ANY, Policy.ViolationState.INFO);
qm.createPolicyCondition(policy, PolicyCondition.Subject.COORDINATES, PolicyCondition.Operator.MATCHES, "cpe:/a:acme:application:1.0.0");
Component component = new Component();
component.setCpe("cpe:/a:acme:application:1.0.0");
PolicyEvaluator evaluator = new CpePolicyEvaluator();
List<PolicyConditionViolation> violations = evaluator.evaluate(policy, component);
Assert.assertEquals(0, violations.size());
}
@Test
public void wrongOperator() {
Policy policy = qm.createPolicy("Test Policy", Policy.Operator.ANY, Policy.ViolationState.INFO);
qm.createPolicyCondition(policy, PolicyCondition.Subject.CPE, PolicyCondition.Operator.IS, "cpe:/a:acme:application:1.0.0");
Component component = new Component();
component.setCpe("cpe:/a:acme:application:1.0.0");
PolicyEvaluator evaluator = new CpePolicyEvaluator();
List<PolicyConditionViolation> violations = evaluator.evaluate(policy, component);
Assert.assertEquals(0, violations.size());
}
}
|
3e192c68ebc87c71c7b4f157277598a744fcf223 | 2,631 | java | Java | app/src/main/java/com/example/schilling/smsweb/sms/sms/SMSBroadcastReceiver.java | MarcusSchilling/SMSToMail | 2573302067a9bac6f90fe539788cdf90af7ebcc2 | [
"MIT"
] | null | null | null | app/src/main/java/com/example/schilling/smsweb/sms/sms/SMSBroadcastReceiver.java | MarcusSchilling/SMSToMail | 2573302067a9bac6f90fe539788cdf90af7ebcc2 | [
"MIT"
] | 2 | 2018-12-28T23:46:37.000Z | 2018-12-28T23:51:15.000Z | app/src/main/java/com/example/schilling/smsweb/sms/sms/SMSBroadcastReceiver.java | MarcusSchilling/SMSToMail | 2573302067a9bac6f90fe539788cdf90af7ebcc2 | [
"MIT"
] | null | null | null | 34.618421 | 89 | 0.651843 | 10,701 | package com.example.schilling.smsweb.sms.sms;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Telephony;
import android.telephony.SmsMessage;
import android.util.Log;
import com.example.schilling.smsweb.sms.mail.BackgroundMail;
import com.example.schilling.smsweb.sms.mail.MailDataNotFoundException;
import java.util.ArrayList;
import java.util.List;
import javax.mail.MessagingException;
import static com.example.schilling.smsweb.sms.Constants.SMS_INTENT_EXTRA_FLAG;
public class SMSBroadcastReceiver extends BroadcastReceiver implements Runnable {
private List<Sms> messages = new ArrayList<>();
private Context context;
@Override
public void onReceive(Context context, Intent intent) {
if(intent.equals("android.intent.action.BOOT_COMPLETED")) {
Log.w("hi","Boot completed");
Intent receiverIntent = new Intent(context, SMSBroadcastReceiver.class);
context.startService(receiverIntent);
return;
}
Log.w("SMS", "SMS received");
SmsMessage[] msgs;
Bundle bundle = intent.getExtras();
if (Build.VERSION.SDK_INT >= 19) { //KITKAT
msgs = Telephony.Sms.Intents.getMessagesFromIntent(intent);
} else {
Object pdus[] = (Object[]) bundle.get(SMS_INTENT_EXTRA_FLAG);
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
}
for (SmsMessage msg : msgs) {
Log.i("SMS: ", msg.getMessageBody());
messages.add(new Sms.Builder(msg).built());
}
this.context = context;
Thread thread = new Thread(this);
thread.start();
}
@Override
public void run() {
BackgroundMail backgroundMail = new BackgroundMail(context);
List<Sms> smsWhichCouldntBeSendToMail = new ArrayList<>();
for (Sms message : messages) {
try {
backgroundMail.sendEmail(message);
message.set_alreadySendToEmail(true);
} catch (MessagingException | MailDataNotFoundException e) {
smsWhichCouldntBeSendToMail.add(message);
message.set_alreadySendToEmail(false);
}
}
SMSDBServiceImpl smsDBService = SMSDBServiceImpl.getSingleton(context, "sms_db");
smsDBService.insertNew(smsWhichCouldntBeSendToMail);
messages.clear();
}
}
|
3e192c6b3169b3193f83edc679129a2f0765c64b | 8,738 | java | Java | src/test/java/io/confluent/connect/jdbc/source/TimestampIncrementingTableQuerierTest.java | marionete-data/kafka-connect-jdbc | f4df7da16393f95c3cd82bf58e869e7cb700d18a | [
"Apache-2.0",
"MIT"
] | 863 | 2015-11-12T09:29:14.000Z | 2022-03-21T09:39:35.000Z | src/test/java/io/confluent/connect/jdbc/source/TimestampIncrementingTableQuerierTest.java | marionete-data/kafka-connect-jdbc | f4df7da16393f95c3cd82bf58e869e7cb700d18a | [
"Apache-2.0",
"MIT"
] | 1,046 | 2015-11-12T02:25:15.000Z | 2022-03-31T04:45:33.000Z | src/test/java/io/confluent/connect/jdbc/source/TimestampIncrementingTableQuerierTest.java | marionete-data/kafka-connect-jdbc | f4df7da16393f95c3cd82bf58e869e7cb700d18a | [
"Apache-2.0",
"MIT"
] | 926 | 2015-11-11T15:00:49.000Z | 2022-03-31T06:08:04.000Z | 34.266667 | 115 | 0.753491 | 10,702 | /**
* Copyright 2016 Confluent 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 io.confluent.connect.jdbc.source;
import io.confluent.connect.jdbc.dialect.DatabaseDialect;
import io.confluent.connect.jdbc.util.ExpressionBuilder;
import io.confluent.connect.jdbc.util.TableId;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.data.SchemaBuilder;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.annotation.Mock;
import org.powermock.api.easymock.annotation.MockNice;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.TimeZone;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.mock;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.powermock.api.easymock.PowerMock.expectLastCall;
import static org.powermock.api.easymock.PowerMock.mockStatic;
import static org.powermock.api.easymock.PowerMock.replay;
import static org.powermock.api.easymock.PowerMock.replayAll;
@RunWith(PowerMockRunner.class)
@PrepareForTest(SchemaMapping.class)
public class TimestampIncrementingTableQuerierTest {
private static final Timestamp INITIAL_TS = new Timestamp(71);
private static final long INITIAL_INC = 4761;
private static final List<String> TIMESTAMP_COLUMNS = Arrays.asList("ts1", "ts2");
private static final String INCREMENTING_COLUMN = "inc";
@Mock
private PreparedStatement stmt;
@Mock
private ResultSet resultSet;
@Mock
private Connection db;
@MockNice
private ExpressionBuilder expressionBuilder;
@Mock
private TimestampIncrementingCriteria criteria;
@Mock
private SchemaMapping schemaMapping;
private DatabaseDialect dialect;
@Before
public void setUp() {
dialect = mock(DatabaseDialect.class);
mockStatic(SchemaMapping.class);
}
private TimestampIncrementingTableQuerier querier(
TimestampIncrementingOffset initialOffset,
boolean timestampMode
) {
final String tableName = "table";
expect(dialect.parseTableIdentifier(tableName)).andReturn(new TableId("", "", tableName));
// Have to replay the dialect here since it's used to the table ID in the querier's constructor
replay(dialect);
return new TimestampIncrementingTableQuerier(
dialect,
TableQuerier.QueryMode.TABLE,
tableName,
"",
timestampMode ? TIMESTAMP_COLUMNS : null,
INCREMENTING_COLUMN,
initialOffset.toMap(),
10211197100L, // Timestamp delay
TimeZone.getTimeZone("UTC"),
""
);
}
private Schema schema() {
SchemaBuilder result =SchemaBuilder.struct();
result.field(INCREMENTING_COLUMN, Schema.INT64_SCHEMA);
TIMESTAMP_COLUMNS.forEach(
col -> result.field(col, org.apache.kafka.connect.data.Timestamp.builder().build())
);
return result.build();
}
private void expectNewQuery() throws Exception {
expect(dialect.createPreparedStatement(eq(db), anyObject())).andReturn(stmt);
expect(dialect.expressionBuilder()).andReturn(expressionBuilder);
expect(dialect.criteriaFor(anyObject(), anyObject())).andReturn(criteria);
dialect.validateSpecificColumnTypes(anyObject(), anyObject());
expectLastCall();
criteria.whereClause(expressionBuilder);
expectLastCall();
criteria.setQueryParameters(eq(stmt), anyObject());
expectLastCall();
expect(stmt.executeQuery()).andReturn(resultSet);
expect(resultSet.getMetaData()).andReturn(null);
expect(SchemaMapping.create(anyObject(), anyObject(), anyObject())).andReturn(schemaMapping);
}
@Test
public void testEmptyResultSet() throws Exception {
expectNewQuery();
TimestampIncrementingTableQuerier querier = querier(offset(INITIAL_TS, INITIAL_INC), false);
expect(resultSet.next()).andReturn(false);
replayAll();
querier.maybeStartQuery(db);
assertFalse(querier.next());
}
@Test
public void testTimestampAndIncrementingMode() throws Exception {
Timestamp firstNewTimestamp = new Timestamp(INITIAL_TS.getTime() + 1);
TimestampIncrementingOffset firstNewOffset = offset(firstNewTimestamp, INITIAL_INC + 1);
TimestampIncrementingOffset secondNewOffset = offset(new Timestamp(INITIAL_TS.getTime() + 2), INITIAL_INC + 2);
expectNewQuery();
TimestampIncrementingTableQuerier querier = querier(offset(INITIAL_TS, INITIAL_INC), false);
expectRecord(firstNewOffset);
expectRecord(firstNewOffset);
expectRecord(secondNewOffset);
expectRecord(secondNewOffset);
expect(resultSet.next()).andReturn(false);
replayAll();
querier.maybeStartQuery(db);
// We just commit timestamp offsets immediately in this mode since the incrementing column
// provides an additional layer of granularity; as long as there aren't two updates to the same
// row that take place with the same timestamp, no data loss should occur
assertNextRecord(querier, firstNewOffset);
assertNextRecord(querier, firstNewOffset);
assertNextRecord(querier, secondNewOffset);
assertNextRecord(querier, secondNewOffset);
assertFalse(querier.next());
}
@Test
public void testIncrementingMode() throws Exception {
TimestampIncrementingOffset firstNewOffset = offset(INITIAL_INC + 1);
TimestampIncrementingOffset secondNewOffset = offset(INITIAL_INC + 2);
expectNewQuery();
TimestampIncrementingTableQuerier querier = querier(offset(INITIAL_INC), true);
expectRecord(firstNewOffset);
expectRecord(firstNewOffset);
expectRecord(secondNewOffset);
expectRecord(secondNewOffset);
expect(resultSet.next()).andReturn(false);
replayAll();
querier.maybeStartQuery(db);
// We commit offsets immediately in this mode
assertNextRecord(querier, firstNewOffset);
assertNextRecord(querier, firstNewOffset);
assertNextRecord(querier, secondNewOffset);
assertNextRecord(querier, secondNewOffset);
assertFalse(querier.next());
}
@Test
public void testMultipleSingleRecordResultSets() throws Exception {
TimestampIncrementingOffset initialOffset = offset(INITIAL_TS, INITIAL_INC);
expectNewQuery();
expectNewQuery();
TimestampIncrementingTableQuerier querier = querier(initialOffset, true);
expectRecord(initialOffset);
expect(resultSet.next()).andReturn(false);
expectReset();
expectRecord(initialOffset);
expect(resultSet.next()).andReturn(false);
replayAll();
querier.maybeStartQuery(db);
assertNextRecord(querier, initialOffset);
assertFalse(querier.next());
querier.reset(0, true);
querier.maybeStartQuery(db);
assertNextRecord(querier, initialOffset);
assertFalse(querier.next());
}
private void assertNextRecord(
TimestampIncrementingTableQuerier querier, TimestampIncrementingOffset offset
) throws Exception {
assertTrue(querier.next());
assertEquals(offset.toMap(), querier.extractRecord().sourceOffset());
}
private void expectRecord(TimestampIncrementingOffset offset) throws Exception {
expect(schemaMapping.schema()).andReturn(schema()).times(2);
expect(resultSet.next()).andReturn(true);
expect(schemaMapping.fieldSetters()).andReturn(Collections.emptyList());
expect(criteria.extractValues(anyObject(), anyObject(), anyObject())).andReturn(offset);
}
private void expectReset() throws Exception {
resultSet.close();
expectLastCall();
stmt.close();
expectLastCall();
db.commit();
expectLastCall();
}
private static TimestampIncrementingOffset offset(Long inc) {
return new TimestampIncrementingOffset(null, inc);
}
private static TimestampIncrementingOffset offset(Timestamp ts, Long inc) {
return new TimestampIncrementingOffset(ts, inc);
}
}
|
3e192c97a4cda64bcee77d9424eff8b9c352938c | 4,167 | java | Java | src/main/java/seedu/track2gather/model/person/attributes/Period.java | jennibearduit/tp | 88efaeda789c6cde864ddd5368cbe4274cac1d4c | [
"MIT"
] | 1 | 2021-09-22T15:00:43.000Z | 2021-09-22T15:00:43.000Z | src/main/java/seedu/track2gather/model/person/attributes/Period.java | jennibearduit/tp | 88efaeda789c6cde864ddd5368cbe4274cac1d4c | [
"MIT"
] | 230 | 2021-09-17T16:59:17.000Z | 2021-11-08T14:38:04.000Z | src/main/java/seedu/track2gather/model/person/attributes/Period.java | jennibearduit/tp | 88efaeda789c6cde864ddd5368cbe4274cac1d4c | [
"MIT"
] | 6 | 2021-09-13T07:12:29.000Z | 2021-09-20T02:43:27.000Z | 31.80916 | 104 | 0.62347 | 10,703 | package seedu.track2gather.model.person.attributes;
import static java.util.Objects.requireNonNull;
import static seedu.track2gather.commons.util.AppUtil.checkArgument;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import javafx.util.Pair;
/**
* Represents a Person's period in the contacts list.
* Guarantees: immutable; is valid as declared in {@link #isValidPeriod(LocalDate, LocalDate)}
*/
public class Period extends Attribute<Pair<LocalDate, LocalDate>> {
public static final String MESSAGE_CONSTRAINTS =
"SHN periods should comprise of two dates in the ISO-8601 format (i.e. yyyy-MM-dd), "
+ "separated by a space. The start date should be keyed before the end date, "
+ "and must occur earlier than the end date by at least 1 day.";
public static final String MESSAGE_CONSTRAINTS_DATE =
"Dates should be in the ISO-8601 format (i.e. yyyy-MM-dd)";
public static final String MESSAGE_CONSTRAINTS_DATE_KEYWORDS =
"Date keywords should be in the ISO-8601 format (i.e. yyyy-MM-dd)";
/**
* Constructs a {@code Period}.
*
* @param periodPair A valid period pair.
*/
public Period(Pair<LocalDate, LocalDate> periodPair) {
super(periodPair);
requireNonNull(periodPair);
requireNonNull(super.value.getKey());
requireNonNull(super.value.getValue());
checkArgument(isValidPeriod(super.value.getKey(), super.value.getValue()), MESSAGE_CONSTRAINTS);
}
/**
* Constructs a {@code Period}.
*
* @param startDate A valid start date.
* @param endDate A valid end date.
*/
public Period(LocalDate startDate, LocalDate endDate) {
this(new Pair<>(startDate, endDate));
}
/**
* Constructs a {@code Period} from a String.
*
* @param period A valid string period.
*/
public Period(String period) {
this(LocalDate.parse(period.split(" => ", 2)[0]),
LocalDate.parse(period.split(" => ", 2)[1]));
}
/**
* Returns true if a given Period is a valid period.
*/
public static boolean isValidPeriod(LocalDate testStartDate, LocalDate testEndDate) {
requireNonNull(testStartDate);
requireNonNull(testEndDate);
return testEndDate.compareTo(testStartDate) > 0; // end date is after start date
}
/**
* Returns true if a given period in string form is a valid period.
*/
public static boolean isValidPeriodString(String period) {
requireNonNull(period);
String[] dates = period.split(" => ", 2);
if (dates.length != 2) {
return false;
}
try {
LocalDate testStartDate = LocalDate.parse(dates[0]);
LocalDate testEndDate = LocalDate.parse(dates[1]);
return isValidPeriod(testStartDate, testEndDate);
} catch (DateTimeParseException e) {
return false;
}
}
public LocalDate getStartDate() {
return value.getKey();
}
public LocalDate getEndDate() {
return value.getValue();
}
/**
* Returns true if a given period date is in the valid format.
*/
public static boolean isValidDate(String date) {
requireNonNull(date);
try {
LocalDate.parse(date);
} catch (DateTimeParseException e) {
return false;
}
return true;
}
/**
* Returns true if this period is completed by the given date.
*/
public boolean isCompletedBy(LocalDate dateToCompare) {
return getEndDate().isBefore(dateToCompare);
}
@Override
public String toString() {
return String.format("%s => %s", getStartDate(), getEndDate());
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Period // instanceof handles nulls
&& value.equals(((Period) other).value)); // state check
}
@Override
public int hashCode() {
return value.hashCode();
}
}
|
3e192fc2fe65cb9412412023fb7159f21f4dc21d | 913 | java | Java | happy-code-base/src/main/java/cool/happycoding/code/base/pojo/H.java | happy-coding-cool/happy-code | 80794294e522ad28730b69307357defeab34dc10 | [
"Apache-2.0"
] | 9 | 2020-12-27T18:00:37.000Z | 2022-01-07T04:07:30.000Z | happy-code-base/src/main/java/cool/happycoding/code/base/pojo/H.java | happy-coding-cool/happy-code | 80794294e522ad28730b69307357defeab34dc10 | [
"Apache-2.0"
] | 1 | 2021-04-06T03:50:20.000Z | 2021-04-16T10:10:39.000Z | happy-code-base/src/main/java/cool/happycoding/code/base/pojo/H.java | happy-coding-cool/happy-code | 80794294e522ad28730b69307357defeab34dc10 | [
"Apache-2.0"
] | null | null | null | 21.738095 | 80 | 0.617744 | 10,704 | package cool.happycoding.code.base.pojo;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ReflectUtil;
import java.io.Serializable;
/**
* description
*
* @author lanlanhappy 2020/12/06 3:14 下午
*/
public interface H extends Serializable {
/**
* 对象转换
* @param source
* @param tClass
* @param copyOptions
* @param <T>
* @return
*/
default <T> T copy(Object source, Class<T> tClass, CopyOptions copyOptions){
T target = ReflectUtil.newInstanceIfPossible(tClass);
BeanUtil.copyProperties(source, target, copyOptions);
return target;
}
/**
* 对象转换
* @param source
* @param clazz
* @param <D>
* @param <S>
* @return
*/
default <D, S> D copy(S source, Class<D> clazz) {
return copy(source, clazz, CopyOptions.create());
}
}
|
3e19300c96e86b196ae0bc29320b382342107558 | 714 | java | Java | src/main/java/com/gabro3/libs/botgram/model/ReplyKeyboardHide.java | leobarreiro/botgram | b7de0d72ec9122e324ef65c27e4a2be298b1c8ae | [
"Apache-2.0"
] | null | null | null | src/main/java/com/gabro3/libs/botgram/model/ReplyKeyboardHide.java | leobarreiro/botgram | b7de0d72ec9122e324ef65c27e4a2be298b1c8ae | [
"Apache-2.0"
] | null | null | null | src/main/java/com/gabro3/libs/botgram/model/ReplyKeyboardHide.java | leobarreiro/botgram | b7de0d72ec9122e324ef65c27e4a2be298b1c8ae | [
"Apache-2.0"
] | null | null | null | 20.4 | 55 | 0.738095 | 10,705 | package com.gabro3.libs.botgram.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ReplyKeyboardHide extends BasicKeyboard {
private static final long serialVersionUID = 3L;
@Expose
@SerializedName("hide_keyboard")
private boolean hideKeyboard;
@Expose
@SerializedName("selective")
private boolean selective;
public boolean isHideKeyboard() {
return hideKeyboard;
}
public void setHideKeyboard(boolean hideKeyboard) {
this.hideKeyboard = hideKeyboard;
}
public boolean isSelective() {
return selective;
}
public void setSelective(boolean selective) {
this.selective = selective;
}
}
|
3e193107f01d5abc9d3177e5da42e968187e3789 | 1,428 | java | Java | core/src/main/java/com/sequenceiq/cloudbreak/reactor/handler/orchestration/ExtendHostMetadataHandler.java | sequenceiq/cloudbreak | 583ec5c5fd6853672af19a0ecf515d85fe20ad28 | [
"Apache-2.0"
] | 146 | 2015-01-19T20:44:08.000Z | 2019-09-09T02:44:36.000Z | core/src/main/java/com/sequenceiq/cloudbreak/reactor/handler/orchestration/ExtendHostMetadataHandler.java | sequenceiq/cloudbreak | 583ec5c5fd6853672af19a0ecf515d85fe20ad28 | [
"Apache-2.0"
] | 1,528 | 2015-01-05T13:43:56.000Z | 2017-07-10T13:58:32.000Z | core/src/main/java/com/sequenceiq/cloudbreak/reactor/handler/orchestration/ExtendHostMetadataHandler.java | sequenceiq/cloudbreak | 583ec5c5fd6853672af19a0ecf515d85fe20ad28 | [
"Apache-2.0"
] | 79 | 2015-01-24T15:59:52.000Z | 2021-04-14T16:07:01.000Z | 34 | 113 | 0.760504 | 10,706 | package com.sequenceiq.cloudbreak.reactor.handler.orchestration;
import javax.inject.Inject;
import org.springframework.stereotype.Component;
import com.sequenceiq.cloudbreak.reactor.ClusterEventHandler;
import com.sequenceiq.cloudbreak.reactor.api.event.resource.ExtendHostMetadataRequest;
import com.sequenceiq.cloudbreak.reactor.api.event.resource.ExtendHostMetadataResult;
import com.sequenceiq.cloudbreak.service.stack.flow.HostMetadataSetup;
import reactor.bus.Event;
import reactor.bus.EventBus;
@Component
public class ExtendHostMetadataHandler implements ClusterEventHandler<ExtendHostMetadataRequest> {
@Inject
private EventBus eventBus;
@Inject
private HostMetadataSetup hostMetadataSetup;
@Override
public Class<ExtendHostMetadataRequest> type() {
return ExtendHostMetadataRequest.class;
}
@Override
public void accept(Event<ExtendHostMetadataRequest> event) {
ExtendHostMetadataRequest request = event.getData();
ExtendHostMetadataResult result;
try {
hostMetadataSetup.setupNewHostMetadata(request.getStackId(), request.getUpscaleCandidateAddresses());
result = new ExtendHostMetadataResult(request);
} catch (Exception e) {
result = new ExtendHostMetadataResult(e.getMessage(), e, request);
}
eventBus.notify(result.selector(), new Event(event.getHeaders(), result));
}
}
|
3e19325d6163e6b22147f6d100d28d025aea73ef | 10,791 | java | Java | core/src/main/java/org/projectnessie/cel/CEL.java | XN137/cel-java | 7e7a68d1dfb1e5d449487b9f5f0e8081b048c4f8 | [
"Apache-2.0"
] | null | null | null | core/src/main/java/org/projectnessie/cel/CEL.java | XN137/cel-java | 7e7a68d1dfb1e5d449487b9f5f0e8081b048c4f8 | [
"Apache-2.0"
] | 9 | 2022-03-21T14:04:30.000Z | 2022-03-31T07:25:53.000Z | core/src/main/java/org/projectnessie/cel/CEL.java | XN137/cel-java | 7e7a68d1dfb1e5d449487b9f5f0e8081b048c4f8 | [
"Apache-2.0"
] | null | null | null | 41.503846 | 100 | 0.724122 | 10,707 | /*
* Copyright (C) 2021 The Authors of CEL-Java
*
* 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.projectnessie.cel;
import static org.projectnessie.cel.common.Source.newInfoSource;
import static org.projectnessie.cel.interpreter.Activation.emptyActivation;
import static org.projectnessie.cel.interpreter.Activation.newPartialActivation;
import static org.projectnessie.cel.interpreter.AttributeFactory.newAttributeFactory;
import static org.projectnessie.cel.interpreter.AttributePattern.newAttributePattern;
import static org.projectnessie.cel.interpreter.AttributePattern.newPartialAttributeFactory;
import static org.projectnessie.cel.interpreter.Dispatcher.newDispatcher;
import static org.projectnessie.cel.interpreter.EvalState.newEvalState;
import static org.projectnessie.cel.interpreter.Interpreter.exhaustiveEval;
import static org.projectnessie.cel.interpreter.Interpreter.newInterpreter;
import static org.projectnessie.cel.interpreter.Interpreter.optimize;
import static org.projectnessie.cel.interpreter.Interpreter.trackState;
import static org.projectnessie.cel.parser.Unparser.unparse;
import com.google.api.expr.v1alpha1.CheckedExpr;
import com.google.api.expr.v1alpha1.Expr;
import com.google.api.expr.v1alpha1.ParsedExpr;
import com.google.api.expr.v1alpha1.Reference;
import com.google.api.expr.v1alpha1.SourceInfo;
import com.google.api.expr.v1alpha1.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.projectnessie.cel.interpreter.Activation;
import org.projectnessie.cel.interpreter.Activation.PartialActivation;
import org.projectnessie.cel.interpreter.AttributePattern;
import org.projectnessie.cel.interpreter.Coster;
import org.projectnessie.cel.interpreter.Coster.Cost;
import org.projectnessie.cel.interpreter.Dispatcher;
import org.projectnessie.cel.interpreter.InterpretableDecorator;
import org.projectnessie.cel.interpreter.Interpreter;
public final class CEL {
/**
* newProgram creates a program instance with an environment, an ast, and an optional list of
* ProgramOption values.
*
* <p>If the program cannot be configured the prog will be nil, with a non-nil error response.
*/
public static Program newProgram(Env e, Ast ast, ProgramOption... opts) {
// Build the dispatcher, interpreter, and default program value.
Dispatcher disp = newDispatcher();
// Ensure the default attribute factory is set after the adapter and provider are
// configured.
Prog p = new Prog(e, disp);
// Configure the program via the ProgramOption values.
for (ProgramOption opt : opts) {
if (opt == null) {
throw new NullPointerException("program options should be non-nil");
}
p = opt.apply(p);
if (p == null) {
throw new NullPointerException(
String.format("program option of type '%s' returned null", opt.getClass().getName()));
}
}
// Set the attribute factory after the options have been set.
if (p.evalOpts.contains(EvalOption.OptPartialEval)) {
p.attrFactory =
newPartialAttributeFactory(e.getContainer(), e.getTypeAdapter(), e.getTypeProvider());
} else {
p.attrFactory =
newAttributeFactory(e.getContainer(), e.getTypeAdapter(), e.getTypeProvider());
}
Interpreter interp =
newInterpreter(
disp, e.getContainer(), e.getTypeProvider(), e.getTypeAdapter(), p.attrFactory);
p.interpreter = interp;
// Translate the EvalOption flags into InterpretableDecorator instances.
List<InterpretableDecorator> decorators = new ArrayList<>(p.decorators);
// Enable constant folding first.
if (p.evalOpts.contains(EvalOption.OptOptimize)) {
decorators.add(optimize());
}
Prog pp = p;
// Enable exhaustive eval over state tracking since it offers a superset of features.
if (p.evalOpts.contains(EvalOption.OptExhaustiveEval)) {
// State tracking requires that each Eval() call operate on an isolated EvalState
// object; hence, the presence of the factory.
ProgFactory factory =
state -> {
List<InterpretableDecorator> decs = new ArrayList<>(decorators);
decs.add(exhaustiveEval(state));
Prog clone = new Prog(e, pp.evalOpts, pp.defaultVars, disp, interp, state);
return initInterpretable(clone, ast, decs);
};
return initProgGen(factory);
} else if (p.evalOpts.contains(EvalOption.OptTrackState)) {
// Enable state tracking last since it too requires the factory approach but is less
// featured than the ExhaustiveEval decorator.
ProgFactory factory =
state -> {
List<InterpretableDecorator> decs = new ArrayList<>(decorators);
decs.add(trackState(state));
Prog clone = new Prog(e, pp.evalOpts, pp.defaultVars, disp, interp, state);
return initInterpretable(clone, ast, decs);
};
return initProgGen(factory);
}
return initInterpretable(p, ast, decorators);
}
/**
* initProgGen tests the factory object by calling it once and returns a factory-based Program if
* the test is successful.
*/
private static Program initProgGen(ProgFactory factory) {
// Test the factory to make sure that configuration errors are spotted at config
factory.apply(newEvalState());
return new ProgGen(factory);
}
/**
* initIterpretable creates a checked or unchecked interpretable depending on whether the Ast has
* been run through the type-checker.
*/
private static Program initInterpretable(
Prog p, Ast ast, List<InterpretableDecorator> decorators) {
InterpretableDecorator[] decs = decorators.toArray(new InterpretableDecorator[0]);
// Unchecked programs do not contain type and reference information and may be
// slower to execute than their checked counterparts.
if (!ast.isChecked()) {
p.interpretable = p.interpreter.newUncheckedInterpretable(ast.getExpr(), decs);
return p;
}
// When the AST has been checked it contains metadata that can be used to speed up program
// execution.
CheckedExpr checked = astToCheckedExpr(ast);
p.interpretable = p.interpreter.newInterpretable(checked, decs);
return p;
}
/** CheckedExprToAst converts a checked expression proto message to an Ast. */
public static Ast checkedExprToAst(CheckedExpr checkedExpr) {
Map<Long, Reference> refMap = checkedExpr.getReferenceMapMap();
Map<Long, Type> typeMap = checkedExpr.getTypeMapMap();
return new Ast(
checkedExpr.getExpr(),
checkedExpr.getSourceInfo(),
newInfoSource(checkedExpr.getSourceInfo()),
refMap,
typeMap);
}
/**
* AstToCheckedExpr converts an Ast to an protobuf CheckedExpr value.
*
* <p>If the Ast.IsChecked() returns false, this conversion method will return an error.
*/
public static CheckedExpr astToCheckedExpr(Ast a) {
if (!a.isChecked()) {
throw new IllegalArgumentException("cannot convert unchecked ast");
}
return CheckedExpr.newBuilder()
.setExpr(a.getExpr())
.setSourceInfo(a.getSourceInfo())
.putAllReferenceMap(a.refMap)
.putAllTypeMap(a.typeMap)
.build();
}
/** ParsedExprToAst converts a parsed expression proto message to an Ast. */
public static Ast parsedExprToAst(ParsedExpr parsedExpr) {
SourceInfo si = parsedExpr.getSourceInfo();
return new Ast(parsedExpr.getExpr(), si, newInfoSource(si));
}
/** AstToParsedExpr converts an Ast to an protobuf ParsedExpr value. */
public static ParsedExpr astToParsedExpr(Ast a) {
return ParsedExpr.newBuilder().setExpr(a.getExpr()).setSourceInfo(a.getSourceInfo()).build();
}
/**
* AstToString converts an Ast back to a string if possible.
*
* <p>Note, the conversion may not be an exact replica of the original expression, but will
* produce a string that is semantically equivalent and whose textual representation is stable.
*/
public static String astToString(Ast a) {
Expr expr = a.getExpr();
SourceInfo info = a.getSourceInfo();
return unparse(expr, info);
}
/** NoVars returns an empty Activation. */
public static Activation noVars() {
return emptyActivation();
}
/**
* PartialVars returns a PartialActivation which contains variables and a set of AttributePattern
* values that indicate variables or parts of variables whose value are not yet known.
*
* <p>The `vars` value may either be an interpreter.Activation or any valid input to the
* interpreter.NewActivation call.
*/
public static PartialActivation partialVars(Object vars, AttributePattern... unknowns) {
return newPartialActivation(vars, unknowns);
}
/**
* AttributePattern returns an AttributePattern that matches a top-level variable. The pattern is
* mutable, and its methods support the specification of one or more qualifier patterns.
*
* <p>For example, the AttributePattern(`a`).QualString(`b`) represents a variable access `a` with
* a string field or index qualification `b`. This pattern will match Attributes `a`, and `a.b`,
* but not `a.c`.
*
* <p>When using a CEL expression within a container, e.g. a package or namespace, the variable
* name in the pattern must match the qualified name produced during the variable namespace
* resolution. For example, when variable `a` is declared within an expression whose container is
* `ns.app`, the fully qualified variable name may be `ns.app.a`, `ns.a`, or `a` per the CEL
* namespace resolution rules. Pick the fully qualified variable name that makes sense within the
* container as the AttributePattern `varName` argument.
*
* <p>See the interpreter.AttributePattern and interpreter.AttributeQualifierPattern for more info
* about how to create and manipulate AttributePattern values.
*/
public static AttributePattern attributePattern(String varName) {
return newAttributePattern(varName);
}
/** EstimateCost returns the heuristic cost interval for the program. */
public static Cost estimateCost(Object p) {
if (p instanceof Coster) {
return ((Coster) p).cost();
}
return Cost.Unknown;
}
}
|
3e1932dc7a4938351858d154adf11f20801c452f | 1,014 | java | Java | uyaki-exception-boot-starter/src/main/java/com/uyaki/exception/common/exception/BusinessException.java | uyaki/spring-uyaki | 4321a61dcd00bd8ae717fa797404fcdaf2f8330e | [
"MIT"
] | 2 | 2020-06-19T06:25:14.000Z | 2020-10-12T11:56:27.000Z | uyaki-exception-boot-starter/src/main/java/com/uyaki/exception/common/exception/BusinessException.java | uyaki/spring-uyaki | 4321a61dcd00bd8ae717fa797404fcdaf2f8330e | [
"MIT"
] | null | null | null | uyaki-exception-boot-starter/src/main/java/com/uyaki/exception/common/exception/BusinessException.java | uyaki/spring-uyaki | 4321a61dcd00bd8ae717fa797404fcdaf2f8330e | [
"MIT"
] | 1 | 2020-06-19T06:25:16.000Z | 2020-06-19T06:25:16.000Z | 28.166667 | 106 | 0.657791 | 10,708 | package com.uyaki.exception.common.exception;
import com.uyaki.exception.common.core.BaseException;
import com.uyaki.exception.common.core.IResponseEnum;
/**
* The type Business exception.
*
* @author uyaki
* @date 2020 /06/06
*/
public class BusinessException extends BaseException {
/**
* Instantiates a new Business exception.
*
* @param responseEnum the response enum
* @param args the args
* @param message the message
*/
public BusinessException(IResponseEnum responseEnum, Object[] args, String message) {
super(responseEnum, args, message);
}
/**
* Instantiates a new Business exception.
*
* @param responseEnum the response enum
* @param args the args
* @param message the message
* @param cause the cause
*/
public BusinessException(IResponseEnum responseEnum, Object[] args, String message, Throwable cause) {
super(responseEnum, args, message, cause);
}
}
|
3e1932ee79764a7f9fa74c7508853cfa2409f013 | 2,568 | java | Java | src/main/java/com/castellanos94/problems/benchmarks/dtlz/DTLZ7.java | castellanos94/jemoa | dc2e96eae16c62a675df457612abd3f9dd2afe18 | [
"MIT"
] | 3 | 2021-08-30T08:50:31.000Z | 2022-03-27T07:00:56.000Z | src/main/java/com/castellanos94/problems/benchmarks/dtlz/DTLZ7.java | castellanos94/jemoa | dc2e96eae16c62a675df457612abd3f9dd2afe18 | [
"MIT"
] | 7 | 2020-10-24T22:01:14.000Z | 2021-12-20T03:43:18.000Z | src/main/java/com/castellanos94/problems/benchmarks/dtlz/DTLZ7.java | castellanos94/jemoa | dc2e96eae16c62a675df457612abd3f9dd2afe18 | [
"MIT"
] | null | null | null | 29.860465 | 108 | 0.574766 | 10,709 | package com.castellanos94.problems.benchmarks.dtlz;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import com.castellanos94.datatype.RealData;
import com.castellanos94.solutions.DoubleSolution;
/**
* This problem has disconnected Pareto-optimal regions in the search space. The
* functional g requires k=|xM|=n−M+1 decision variables. This problem will test
* an algorithm’s ability to maintain subpopulation in different Pareto-optimal
* regions. JMetal-based implementation.
*/
public class DTLZ7 extends DTLZ {
public DTLZ7() {
this(3, 22);
}
public DTLZ7(int numberOfObjectives, int numberOfVariables) {
super(numberOfObjectives, numberOfVariables);
}
@Override
public void evaluate(DoubleSolution solution) {
int numberOfVariables = getNumberOfDecisionVars();
int numberOfObjectives = getNumberOfObjectives();
double[] f = new double[numberOfObjectives];
double[] x = new double[numberOfVariables];
for (int i = 0; i < numberOfVariables; i++) {
x[i] = solution.getVariable(i);
}
double g = 0.0;
for (int i = numberOfVariables - k; i < numberOfVariables; i++) {
g += x[i];
}
g = 1 + (9.0 * g) / k;
System.arraycopy(x, 0, f, 0, numberOfObjectives - 1);
double h = 0.0;
for (int i = 0; i < numberOfObjectives - 1; i++) {
h += (f[i] / (1.0 + g)) * (1 + Math.sin(3.0 * Math.PI * f[i]));
}
h = numberOfObjectives - h;
f[numberOfObjectives - 1] = (1 + g) * h;
for (int i = 0; i < numberOfObjectives; i++) {
solution.setObjective(i, new RealData((f[i] )));
}
}
@Override
public double[][] getParetoOptimal3Obj() throws FileNotFoundException {
Scanner sc = new Scanner(new File("src/main/resources/pointsOfReference/DTLZ/DTLZ.3D/DTLZ7.3D.pf"));
ArrayList<Double[]> list = new ArrayList<>();
while (sc.hasNext()) {
Double row[] = new Double[3];
for (int i = 0; i < row.length; i++) {
row[i] = sc.nextDouble();
}
list.add(row);
}
int max = list.size();
double matrix[][] = new double[max][list.get(0).length];
for (int i = 0; i < max; i++) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = list.get(i)[j];
}
}
sc.close();
return matrix;
}
} |
3e1933a1875d2dbc53e6ae3164851a16d06dc7c2 | 3,118 | java | Java | Lesson_12/Binary_Search/src/com/timbuchalka/Theatre.java | Fabio-Morais/Learning-Java | 13c32fd37e9007b0f250d0882d20bad548e2f949 | [
"MIT"
] | null | null | null | Lesson_12/Binary_Search/src/com/timbuchalka/Theatre.java | Fabio-Morais/Learning-Java | 13c32fd37e9007b0f250d0882d20bad548e2f949 | [
"MIT"
] | null | null | null | Lesson_12/Binary_Search/src/com/timbuchalka/Theatre.java | Fabio-Morais/Learning-Java | 13c32fd37e9007b0f250d0882d20bad548e2f949 | [
"MIT"
] | null | null | null | 27.350877 | 87 | 0.493906 | 10,710 | package com.timbuchalka;
import java.util.*;
/**
* Created by dev on 2/12/2015.
*/
public class Theatre {
private final String theatreName;
private List<Seat> seats = new ArrayList<>();
static final Comparator<Seat> PRICE_ORDER;
static {
PRICE_ORDER = new Comparator<Seat>() {
@Override
public int compare(Seat seat1, Seat seat2) {
if (seat1.getPrice() < seat2.getPrice()) {
return -1;
} else if (seat1.getPrice() > seat2.getPrice()) {
return 1;
} else {
return 0;
}
}
};
}
public Theatre(String theatreName, int numRows, int seatsPerRow) {
this.theatreName = theatreName;
int lastRow = 'A' + (numRows -1);
for (char row = 'A'; row <= lastRow; row++) {
for(int seatNum = 1; seatNum <= seatsPerRow; seatNum++) {
double price = 12.00;
if((row < 'D') && (seatNum >=4 && seatNum <=9)) {
price = 14.00;
} else if((row > 'F') || (seatNum < 4 || seatNum > 9)) {
price = 7.00;
}
Seat seat = new Seat(row + String.format("%02d", seatNum), price);
seats.add(seat);
}
}
}
public String getTheatreName() {
return theatreName;
}
public boolean reserveSeat(String seatNumber) {
Seat requestedSeat = new Seat(seatNumber, 0);
int foundSeat = Collections.binarySearch(seats, requestedSeat, null);
if (foundSeat >= 0) {
return seats.get(foundSeat).reserve();
} else {
System.out.println("There is no seat " + seatNumber);
return false;
}
}
// for testing
public Collection<Seat> getSeats() {
return seats;
}
public class Seat implements Comparable<Seat> {
private final String seatNumber;
private double price;
private boolean reserved = false;
public Seat(String seatNumber, double price) {
this.seatNumber = seatNumber;
this.price = price;
}
@Override
public int compareTo(Seat seat) {
return this.seatNumber.compareToIgnoreCase(seat.getSeatNumber());
}
public boolean reserve() {
if(!this.reserved) {
this.reserved = true;
System.out.println("Seat " + seatNumber + " reserved");
return true;
} else {
return false;
}
}
public boolean cancel() {
if(this.reserved) {
this.reserved = false;
System.out.println("Reservation of seat " + seatNumber + " cancelled");
return true;
} else {
return false;
}
}
public String getSeatNumber() {
return seatNumber;
}
public double getPrice() {
return price;
}
}
}
|
3e1934ca64d802154e1a19f3021bb180bfa5e332 | 2,312 | java | Java | segmentstore/server/host/src/main/java/io/pravega/segmentstore/server/host/delegationtoken/DelegationTokenVerifier.java | shshashwat/pravega | f5ccb4c62087d37fe94fd116aa3c1e50b79d71b6 | [
"Apache-2.0"
] | 1,840 | 2017-05-10T16:29:14.000Z | 2022-03-31T07:02:11.000Z | segmentstore/server/host/src/main/java/io/pravega/segmentstore/server/host/delegationtoken/DelegationTokenVerifier.java | shshashwat/pravega | f5ccb4c62087d37fe94fd116aa3c1e50b79d71b6 | [
"Apache-2.0"
] | 5,485 | 2017-05-10T16:56:17.000Z | 2022-03-31T14:08:36.000Z | segmentstore/server/host/src/main/java/io/pravega/segmentstore/server/host/delegationtoken/DelegationTokenVerifier.java | shshashwat/pravega | f5ccb4c62087d37fe94fd116aa3c1e50b79d71b6 | [
"Apache-2.0"
] | 443 | 2017-05-10T21:34:50.000Z | 2022-03-31T07:02:14.000Z | 49.191489 | 117 | 0.723616 | 10,711 | /**
* Copyright Pravega Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.pravega.segmentstore.server.host.delegationtoken;
import io.pravega.auth.AuthHandler;
import io.pravega.auth.InvalidClaimException;
import io.pravega.auth.InvalidTokenException;
import io.pravega.auth.TokenException;
import io.pravega.auth.TokenExpiredException;
import io.pravega.shared.security.token.JsonWebToken;
/**
* This interface represents the code on segment store side that verifies the delegation token.
*/
public interface DelegationTokenVerifier {
/**
* Ensures that the given {@code token} represents specified {@code expectedLevel} of access on the
* given {@code resource}. It returns normally if the {@code token} grants {@code expectedLevel} of access,
* and throws an exception, otherwise.
*
* @param resource the resource for which access is desired.
* @param token the access/delegation token.
* @param expectedLevel maximum expected access to the given {@code resource}.
* @throws TokenExpiredException if the {@code token} has expired
* @throws InvalidTokenException if the {@code token} is invalid
* @throws InvalidClaimException if the {@code token} does not contain the claim representing
* {@code expectedLevel} of access
* @throws TokenException if any other failure condition is encountered
* @return JsonWebToken a non-null value if token was parsed and verified successfully, otherwise null.
*/
JsonWebToken verifyToken(String resource, String token, AuthHandler.Permissions expectedLevel)
throws TokenExpiredException, InvalidTokenException, InvalidClaimException, TokenException;
} |
3e193792ecc418e7f9f9de670385d820210e8bb9 | 163 | java | Java | BattleShip/BattleShipStrategyRandom.java | spookiecookie/BattleShipGame | 72bf828fda1c9796c010dba2439ed7a24cf86423 | [
"MIT"
] | null | null | null | BattleShip/BattleShipStrategyRandom.java | spookiecookie/BattleShipGame | 72bf828fda1c9796c010dba2439ed7a24cf86423 | [
"MIT"
] | null | null | null | BattleShip/BattleShipStrategyRandom.java | spookiecookie/BattleShipGame | 72bf828fda1c9796c010dba2439ed7a24cf86423 | [
"MIT"
] | null | null | null | 18.111111 | 40 | 0.760736 | 10,712 | public class BattleShipStrategyRandom
extends BattleShipStrategy
{
public Point getNextPoint(Board board)
{
return board.getRandomNotAttacked();
}
}
|
3e1939110e5a20dae7570c11711b0b632744cf58 | 1,185 | java | Java | endpoints-framework/src/main/java/com/google/api/server/spi/config/Description.java | rishisharma-google/endpoints-java | 39b73744c9ee4e39e94d6d11638ba34810e5de07 | [
"Apache-2.0"
] | 36 | 2016-09-02T13:02:04.000Z | 2022-01-22T16:22:43.000Z | endpoints-framework/src/main/java/com/google/api/server/spi/config/Description.java | rishisharma-google/endpoints-java | 39b73744c9ee4e39e94d6d11638ba34810e5de07 | [
"Apache-2.0"
] | 188 | 2016-09-01T22:23:32.000Z | 2022-03-09T08:30:25.000Z | endpoints-framework/src/main/java/com/google/api/server/spi/config/Description.java | rishisharma-google/endpoints-java | 39b73744c9ee4e39e94d6d11638ba34810e5de07 | [
"Apache-2.0"
] | 28 | 2016-09-01T22:04:40.000Z | 2021-11-12T15:32:53.000Z | 33.857143 | 80 | 0.75443 | 10,713 | /*
* Copyright 2016 Google 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.google.api.server.spi.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation to specify the description of an API parameter or enum constants.
* The description will be ignored if the annotation is used on resource fields.
*/
@Target({ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Description {
/**
* The parameter description.
*/
String value() default "";
}
|
3e19393016107aa3f6ffe3d1a8d7e9d57c2d00ef | 3,253 | java | Java | com/intkr/saas/engine/CookieEngine.java | Beiden/Intkr_SAAS_BEIDEN | fb2b68f2e04a891523e3589dd3abebd2fcd5828d | [
"Apache-2.0"
] | null | null | null | com/intkr/saas/engine/CookieEngine.java | Beiden/Intkr_SAAS_BEIDEN | fb2b68f2e04a891523e3589dd3abebd2fcd5828d | [
"Apache-2.0"
] | null | null | null | com/intkr/saas/engine/CookieEngine.java | Beiden/Intkr_SAAS_BEIDEN | fb2b68f2e04a891523e3589dd3abebd2fcd5828d | [
"Apache-2.0"
] | 1 | 2022-03-16T15:04:17.000Z | 2022-03-16T15:04:17.000Z | 26.233871 | 103 | 0.71534 | 10,714 | package com.intkr.saas.engine;
import java.util.Random;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Beiden
* @date 2011-5-24 上午11:13:59
* @version 1.0
*/
public class CookieEngine {
private static String rememberLoginUserId = "_l_u_i";// 用于记录自动登录的用户ID
private static String cookieCodeKey = "_m_p_c_c";// 用cookie来标识客户端
public static void setRememberLoginUserId(HttpServletResponse response, Long userId, Integer maxAge) {
Cookie nameCookie = new Cookie(CookieEngine.rememberLoginUserId, userId + "");
nameCookie.setMaxAge(maxAge);
setCookie(response, nameCookie);
}
public static Long getRememberLoginUserId(HttpServletRequest request) {
String value = getValue(request, rememberLoginUserId);
if (value == null || "".equals(value)) {
return null;
}
try {
return Long.valueOf(value);
} catch (NumberFormatException e) {
return null;
}
}
public static void removeLoginUserIdKey(HttpServletRequest request, HttpServletResponse response) {
remove(request, response, rememberLoginUserId);
}
public static boolean isExistCookieCode(HttpServletRequest request) {
return isExist(request, CookieEngine.cookieCodeKey);
}
public static String getCookieCode(HttpServletRequest request) {
return getValue(request, CookieEngine.cookieCodeKey);
}
public static String random() {
Random random = new Random();
return random.nextInt(9999) + "";
}
public static void setCookieCode(HttpServletRequest request, HttpServletResponse response) {
String code = "40f6_" + random() + "_8ef6";
Cookie nameCookie = new Cookie(CookieEngine.cookieCodeKey, code);
nameCookie.setMaxAge(24 * 60 * 60);// 单位,秒,设置存一天
setCookie(response, nameCookie);
}
public static boolean checkCookieCode(HttpServletRequest request, HttpServletResponse response) {
String cookieCode = getValue(request, CookieEngine.cookieCodeKey);
if (cookieCode == null) {
return false;
}
if (!cookieCode.startsWith("40f6_")) {
return false;
}
if (!cookieCode.endsWith("_8ef6")) {
return false;
}
return true;
}
public static String getValue(HttpServletRequest request, String key) {
if (key == null || "".equals(key)) {
return null;
}
Cookie cookie = get(request, key);
if (cookie == null) {
return null;
} else {
return cookie.getValue();
}
}
public static void remove(HttpServletRequest request, HttpServletResponse response, String key) {
Cookie cookie = get(request, key);
if (cookie != null) {
cookie.setMaxAge(0);
setCookie(response, cookie);
}
}
public static Cookie get(HttpServletRequest request, String key) {
if (key == null || "".equals(key)) {
return null;
}
Cookie[] cookies = request.getCookies();
if (cookies != null) {
if (null != cookies) {
for (Cookie cookie : cookies) {
if (key.equalsIgnoreCase(cookie.getName())) {
return cookie;
}
}
}
}
return null;
}
public static boolean isExist(HttpServletRequest request, String key) {
return get(request, key) != null;
}
public static void setCookie(HttpServletResponse response, Cookie cookie) {
cookie.setPath("/");
response.addCookie(cookie);
}
}
|
3e193988b90752147622c9480584de0a9afb9dc6 | 871 | java | Java | admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/auth/PasswordTO.java | andrehertwig/admintool | 5763c6a913244a7aab2f7564694fd6d756802116 | [
"MIT"
] | 10 | 2017-02-01T12:53:50.000Z | 2020-05-22T05:21:07.000Z | admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/auth/PasswordTO.java | andrehertwig/admintool | 5763c6a913244a7aab2f7564694fd6d756802116 | [
"MIT"
] | 46 | 2016-08-05T17:41:30.000Z | 2021-12-18T18:16:36.000Z | admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/auth/PasswordTO.java | andrehertwig/admintool | 5763c6a913244a7aab2f7564694fd6d756802116 | [
"MIT"
] | 8 | 2016-02-25T19:44:39.000Z | 2021-09-20T10:30:41.000Z | 23.540541 | 68 | 0.740528 | 10,715 | package de.chandre.admintool.security.dbuser.auth;
import java.io.Serializable;
/**
*
* @author André
* @since 1.2.0
*
*/
public class PasswordTO implements Serializable {
private static final long serialVersionUID = 7282206856603860917L;
private String currentPassword;
private String newPassword;
private String passwordConfirm;
public String getCurrentPassword() {
return currentPassword;
}
public void setCurrentPassword(String currentPassword) {
this.currentPassword = currentPassword;
}
public String getNewPassword() {
return newPassword;
}
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
}
|
3e19399fc8283c340469e8903240ce300c6a947c | 922 | java | Java | root/prj/sol/projects/renew2.5source/renew2.5/src/CH/src/CH/ifa/draw/application/InsertDrawingCommand.java | Glost/db_nets_renew_plugin | def4eaf7e55d79b9093bd59c5266804b345e8595 | [
"BSD-4-Clause-UC"
] | null | null | null | root/prj/sol/projects/renew2.5source/renew2.5/src/CH/src/CH/ifa/draw/application/InsertDrawingCommand.java | Glost/db_nets_renew_plugin | def4eaf7e55d79b9093bd59c5266804b345e8595 | [
"BSD-4-Clause-UC"
] | null | null | null | root/prj/sol/projects/renew2.5source/renew2.5/src/CH/src/CH/ifa/draw/application/InsertDrawingCommand.java | Glost/db_nets_renew_plugin | def4eaf7e55d79b9093bd59c5266804b345e8595 | [
"BSD-4-Clause-UC"
] | null | null | null | 23.05 | 69 | 0.625813 | 10,716 | package CH.ifa.draw.application;
import CH.ifa.draw.DrawPlugin;
import CH.ifa.draw.standard.NullDrawing;
import CH.ifa.draw.util.Command;
/**
* A command that inserts drawing from a file into another drawing.
*
* @author Michael Duvigneau
**/
public class InsertDrawingCommand extends Command {
public InsertDrawingCommand() {
super("Insert Drawing...");
}
/**
* This command is executable only if a drawing to insert into is
* available.
*
* @return <code>true</code> if there exists a current drawing.
**/
public final boolean isExecutable() {
DrawApplication app = DrawPlugin.getGui();
if (app == null) {
return false;
}
return !(app.drawing() instanceof NullDrawing);
}
/**
* Inserts a drawing from a file.
**/
public final void execute() {
DrawPlugin.getGui().promptInsert();
}
} |
3e193ab48d0b420bf3a02f388f8749c003fc467f | 718 | java | Java | tso-server/src/main/java/com/yahoo/omid/metrics/Metric.java | huayl/omid | a8ab423b0a008755eafccf680eac2c4f0fd8976c | [
"Apache-2.0"
] | null | null | null | tso-server/src/main/java/com/yahoo/omid/metrics/Metric.java | huayl/omid | a8ab423b0a008755eafccf680eac2c4f0fd8976c | [
"Apache-2.0"
] | null | null | null | tso-server/src/main/java/com/yahoo/omid/metrics/Metric.java | huayl/omid | a8ab423b0a008755eafccf680eac2c4f0fd8976c | [
"Apache-2.0"
] | null | null | null | 29.916667 | 75 | 0.729805 | 10,717 | /**
* Copyright 2011-2015 Yahoo 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.yahoo.omid.metrics;
/**
* Marker interface for distinguish metrics
*/
public interface Metric {
}
|
3e193adacfd1222da8c761f6fd7632d7de28fb42 | 2,159 | java | Java | ui_swing/src/main/java/com/dmdirc/addons/ui_swing/components/menubar/JMenuItemBuilder.java | csmith/DMDirc-Plugins | 260722a51955162f60933da2cbca789e0d019da8 | [
"MIT"
] | null | null | null | ui_swing/src/main/java/com/dmdirc/addons/ui_swing/components/menubar/JMenuItemBuilder.java | csmith/DMDirc-Plugins | 260722a51955162f60933da2cbca789e0d019da8 | [
"MIT"
] | 61 | 2015-01-04T01:14:08.000Z | 2017-04-14T22:46:37.000Z | ui_swing/src/main/java/com/dmdirc/addons/ui_swing/components/menubar/JMenuItemBuilder.java | csmith/DMDirc-Plugins | 260722a51955162f60933da2cbca789e0d019da8 | [
"MIT"
] | 4 | 2017-03-22T03:11:43.000Z | 2020-01-10T07:08:50.000Z | 34.269841 | 119 | 0.726725 | 10,718 | /*
* Copyright (c) 2006-2017 DMDirc Developers
*
* 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.dmdirc.addons.ui_swing.components.menubar;
import java.awt.event.ActionListener;
import javax.swing.JMenuItem;
/**
* Builder for creating new {@link JMenuItem}s.
*/
public class JMenuItemBuilder {
private final JMenuItem menuItem;
public static JMenuItemBuilder create() {
return new JMenuItemBuilder();
}
private JMenuItemBuilder() {
this.menuItem = new JMenuItem();
}
public JMenuItemBuilder setMnemonic(final char mnemonic) {
menuItem.setMnemonic(mnemonic);
return this;
}
public JMenuItemBuilder setText(final String text) {
menuItem.setText(text);
return this;
}
public JMenuItemBuilder addActionListener(final ActionListener listener) {
menuItem.addActionListener(listener);
return this;
}
public JMenuItemBuilder addActionMethod(final Runnable runnable) {
menuItem.addActionListener(e -> runnable.run());
return this;
}
public JMenuItem build() {
return menuItem;
}
}
|
3e193bc647c3f39b8523fecba3d8d6b8c4ab7a63 | 339 | java | Java | src/test/java/org/projectbarbel/histo/persistence/sql/AppTest.java | projectbarbel/barbelhisto-persistence-sql | 5a17f6581fbad37fe38aedd6775b4b967b765624 | [
"MIT"
] | null | null | null | src/test/java/org/projectbarbel/histo/persistence/sql/AppTest.java | projectbarbel/barbelhisto-persistence-sql | 5a17f6581fbad37fe38aedd6775b4b967b765624 | [
"MIT"
] | null | null | null | src/test/java/org/projectbarbel/histo/persistence/sql/AppTest.java | projectbarbel/barbelhisto-persistence-sql | 5a17f6581fbad37fe38aedd6775b4b967b765624 | [
"MIT"
] | null | null | null | 16.142857 | 58 | 0.643068 | 10,719 | package org.projectbarbel.histo.persistence.sql;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/**
* Unit test for simple App.
*/
public class AppTest
{
/**
* Rigorous Test :-)
*/
@Test
public void shouldAnswerWithTrue()
{
assertTrue( true );
}
}
|
3e193be26d3fd842d9e088d4452031f79310719b | 9,584 | java | Java | phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/PPIntent.java | TheWizard1328/PhoneProfilesPlus | 3aa5f3f9e13de986608afe50ee641a25d1ee41d5 | [
"Apache-2.0"
] | 122 | 2015-01-22T17:40:09.000Z | 2022-03-20T22:20:16.000Z | phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/PPIntent.java | TheWizard1328/PhoneProfilesPlus | 3aa5f3f9e13de986608afe50ee641a25d1ee41d5 | [
"Apache-2.0"
] | 77 | 2015-05-06T11:18:23.000Z | 2022-02-02T18:43:08.000Z | phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/PPIntent.java | TheWizard1328/PhoneProfilesPlus | 3aa5f3f9e13de986608afe50ee641a25d1ee41d5 | [
"Apache-2.0"
] | 29 | 2015-01-21T09:16:02.000Z | 2022-02-10T07:59:52.000Z | 32.709898 | 99 | 0.640129 | 10,720 | package sk.henrichg.phoneprofilesplus;
import android.os.Parcel;
import android.os.Parcelable;
class PPIntent implements Parcelable {
long _id;
String _name;
String _packageName;
String _className;
String _action;
String _data;
String _mimeType;
String _extraKey1;
String _extraValue1;
int _extraType1;
String _extraKey2;
String _extraValue2;
int _extraType2;
String _extraKey3;
String _extraValue3;
int _extraType3;
String _extraKey4;
String _extraValue4;
int _extraType4;
String _extraKey5;
String _extraValue5;
int _extraType5;
String _extraKey6;
String _extraValue6;
int _extraType6;
String _extraKey7;
String _extraValue7;
int _extraType7;
String _extraKey8;
String _extraValue8;
int _extraType8;
String _extraKey9;
String _extraValue9;
int _extraType9;
String _extraKey10;
String _extraValue10;
int _extraType10;
String _categories;
String _flags;
int _intentType;
int _usedCount;
PPIntent() {}
PPIntent(
long id,
String name,
String packageName,
String className,
String action,
String data,
String mimeType,
String extraKey1,
String extraValue1,
int extraType1,
String extraKey2,
String extraValue2,
int extraType2,
String extraKey3,
String extraValue3,
int extraType3,
String extraKey4,
String extraValue4,
int extraType4,
String extraKey5,
String extraValue5,
int extraType5,
String extraKey6,
String extraValue6,
int extraType6,
String extraKey7,
String extraValue7,
int extraType7,
String extraKey8,
String extraValue8,
int extraType8,
String extraKey9,
String extraValue9,
int extraType9,
String extraKey10,
String extraValue10,
int extraType10,
String categories,
String flags,
int usedCount,
int intentType
)
{
this._id = id;
this._name = name;
this._packageName = packageName;
this._className = className;
this._action = action;
this._data = data;
this._mimeType = mimeType;
this._extraKey1 = extraKey1;
this._extraValue1 = extraValue1;
this._extraType1 = extraType1;
this._extraKey2 = extraKey2;
this._extraValue2 = extraValue2;
this._extraType2 = extraType2;
this._extraKey3 = extraKey3;
this._extraValue3 = extraValue3;
this._extraType3 = extraType3;
this._extraKey4 = extraKey4;
this._extraValue4 = extraValue4;
this._extraType4 = extraType4;
this._extraKey5 = extraKey5;
this._extraValue5 = extraValue5;
this._extraType5 = extraType5;
this._extraKey6 = extraKey6;
this._extraValue6 = extraValue6;
this._extraType6 = extraType6;
this._extraKey7 = extraKey7;
this._extraValue7 = extraValue7;
this._extraType7 = extraType7;
this._extraKey8 = extraKey8;
this._extraValue8 = extraValue8;
this._extraType8 = extraType8;
this._extraKey9 = extraKey9;
this._extraValue9 = extraValue9;
this._extraType9 = extraType9;
this._extraKey10 = extraKey10;
this._extraValue10 = extraValue10;
this._extraType10 = extraType10;
this._categories = categories;
this._flags = flags;
this._intentType = intentType;
this._usedCount = usedCount;
}
private PPIntent(Parcel in) {
this._id = in.readLong();
this._name = in.readString();
this._packageName = in.readString();
this._className = in.readString();
this._action = in.readString();
this._data = in.readString();
this._mimeType = in.readString();
this._extraKey1 = in.readString();
this._extraValue1 = in.readString();
this._extraType1 = in.readInt();
this._extraKey2 = in.readString();
this._extraValue2 = in.readString();
this._extraType2 = in.readInt();
this._extraKey3 = in.readString();
this._extraValue3 = in.readString();
this._extraType3 = in.readInt();
this._extraKey4 = in.readString();
this._extraValue4 = in.readString();
this._extraType4 = in.readInt();
this._extraKey5 = in.readString();
this._extraValue5 = in.readString();
this._extraType5 = in.readInt();
this._extraKey6 = in.readString();
this._extraValue6 = in.readString();
this._extraType6 = in.readInt();
this._extraKey7 = in.readString();
this._extraValue7 = in.readString();
this._extraType7 = in.readInt();
this._extraKey8 = in.readString();
this._extraValue8 = in.readString();
this._extraType8 = in.readInt();
this._extraKey9 = in.readString();
this._extraValue9 = in.readString();
this._extraType9 = in.readInt();
this._extraKey10 = in.readString();
this._extraValue10 = in.readString();
this._extraType10 = in.readInt();
this._categories = in.readString();
this._flags = in.readString();
this._intentType = in.readInt();
this._usedCount = in.readInt();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this._id);
dest.writeString(this._name);
dest.writeString(this._packageName);
dest.writeString(this._className);
dest.writeString(this._action);
dest.writeString(this._data);
dest.writeString(this._mimeType);
dest.writeString(this._extraKey1);
dest.writeString(this._extraValue1);
dest.writeInt(this._extraType1);
dest.writeString(this._extraKey2);
dest.writeString(this._extraValue2);
dest.writeInt(this._extraType2);
dest.writeString(this._extraKey3);
dest.writeString(this._extraValue3);
dest.writeInt(this._extraType3);
dest.writeString(this._extraKey4);
dest.writeString(this._extraValue4);
dest.writeInt(this._extraType4);
dest.writeString(this._extraKey5);
dest.writeString(this._extraValue5);
dest.writeInt(this._extraType5);
dest.writeString(this._extraKey6);
dest.writeString(this._extraValue6);
dest.writeInt(this._extraType6);
dest.writeString(this._extraKey7);
dest.writeString(this._extraValue7);
dest.writeInt(this._extraType7);
dest.writeString(this._extraKey8);
dest.writeString(this._extraValue8);
dest.writeInt(this._extraType8);
dest.writeString(this._extraKey9);
dest.writeString(this._extraValue9);
dest.writeInt(this._extraType9);
dest.writeString(this._extraKey10);
dest.writeString(this._extraValue10);
dest.writeInt(this._extraType10);
dest.writeString(this._categories);
dest.writeString(this._flags);
dest.writeInt(this._intentType);
dest.writeInt(this._usedCount);
}
PPIntent duplicate() {
PPIntent newPPIntent = new PPIntent();
newPPIntent._name = _name + "_d";
newPPIntent._packageName = _packageName;
newPPIntent._className = _className;
newPPIntent._action = _action;
newPPIntent._data = _data;
newPPIntent._mimeType = _mimeType;
newPPIntent._extraKey1 = _extraKey1;
newPPIntent._extraValue1 = _extraValue1;
newPPIntent._extraType1 = _extraType1;
newPPIntent._extraKey2 = _extraKey2;
newPPIntent._extraValue2 = _extraValue2;
newPPIntent._extraType2 = _extraType2;
newPPIntent._extraKey3 = _extraKey3;
newPPIntent._extraValue3 = _extraValue3;
newPPIntent._extraType3 = _extraType3;
newPPIntent._extraKey4 = _extraKey4;
newPPIntent._extraValue4 = _extraValue4;
newPPIntent._extraType4 = _extraType4;
newPPIntent._extraKey5 = _extraKey5;
newPPIntent._extraValue5 = _extraValue5;
newPPIntent._extraType5 = _extraType5;
newPPIntent._extraKey6 = _extraKey6;
newPPIntent._extraValue6 = _extraValue6;
newPPIntent._extraType6 = _extraType6;
newPPIntent._extraKey7 = _extraKey7;
newPPIntent._extraValue7 = _extraValue7;
newPPIntent._extraType7 = _extraType7;
newPPIntent._extraKey8 = _extraKey8;
newPPIntent._extraValue8 = _extraValue8;
newPPIntent._extraType8 = _extraType8;
newPPIntent._extraKey9 = _extraKey9;
newPPIntent._extraValue9 = _extraValue9;
newPPIntent._extraType9 = _extraType9;
newPPIntent._extraKey10 = _extraKey10;
newPPIntent._extraValue10 = _extraValue10;
newPPIntent._extraType10 = _extraType10;
newPPIntent._categories = _categories;
newPPIntent._flags = _flags;
newPPIntent._intentType = _intentType;
return newPPIntent;
}
public static final Parcelable.Creator<PPIntent> CREATOR = new Parcelable.Creator<PPIntent>() {
public PPIntent createFromParcel(Parcel source) {
return new PPIntent(source);
}
public PPIntent[] newArray(int size) {
return new PPIntent[size];
}
};
}
|
3e193ce150a2fdea0c639b6f8745667fdb2ef4fd | 1,590 | java | Java | sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/apachecommons/lang/math/NumberUtils.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 1,350 | 2015-01-17T05:22:05.000Z | 2022-03-29T21:00:37.000Z | sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/apachecommons/lang/math/NumberUtils.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 16,834 | 2015-01-07T02:19:09.000Z | 2022-03-31T23:29:10.000Z | sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/apachecommons/lang/math/NumberUtils.java | yiliuTo/azure-sdk-for-java | 4536b6e99ded1b2b77f79bc2c31f42566c97b704 | [
"MIT"
] | 1,586 | 2015-01-02T01:50:28.000Z | 2022-03-31T11:25:34.000Z | 36.136364 | 85 | 0.689308 | 10,721 | /*
* 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.
*/
/*
* Portions Copyright (c) Microsoft Corporation
*/
package com.azure.cosmos.implementation.apachecommons.lang.math;
public class NumberUtils {
/**
* <p>Convert a <code>String</code> to a <code>long</code>, returning a
* default value if the conversion fails.</p>
*
* @param str the string to convert, may be null
* @param defaultValue the default value
* @return the long represented by the string, or the default if conversion fails
*/
public static long toLong(final String str, final long defaultValue) {
if (str == null) {
return defaultValue;
}
try {
return Long.parseLong(str);
} catch (final NumberFormatException nfe) {
return defaultValue;
}
}
}
|
3e193e5a783c6c996c924d8043f27a3688dd829d | 2,498 | java | Java | src/main/java/org/jhove2/core/format/FormatFactory.java | opf-labs/jhove2 | cae9ab898bcc82b9623539f161bc4d749b365a48 | [
"BSD-2-Clause"
] | 11 | 2015-02-03T19:52:39.000Z | 2020-03-24T11:25:29.000Z | src/main/java/org/jhove2/core/format/FormatFactory.java | opf-labs/jhove2 | cae9ab898bcc82b9623539f161bc4d749b365a48 | [
"BSD-2-Clause"
] | 1 | 2015-05-12T12:03:52.000Z | 2015-05-12T12:24:08.000Z | src/main/java/org/jhove2/core/format/FormatFactory.java | opf-labs/jhove2 | cae9ab898bcc82b9623539f161bc4d749b365a48 | [
"BSD-2-Clause"
] | 1 | 2015-04-30T11:02:02.000Z | 2015-04-30T11:02:02.000Z | 44.607143 | 93 | 0.754203 | 10,722 | /**
* JHOVE2 - Next-generation architecture for format-aware characterization
*
* Copyright (c) 2009 by The Regents of the University of California, Ithaka
* Harbors, Inc., and The Board of Trustees of the Leland Stanford Junior
* University. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of the University of California/California Digital
* Library, Ithaka Harbors/Portico, or Stanford University, 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.jhove2.core.format;
import org.jhove2.core.I8R;
import org.jhove2.core.JHOVE2Exception;
/**
* Factory Interface for {@link org.jhove2.core.format.Format}instances
*
* @author smorrissey
*/
public interface FormatFactory {
/**
* Constructs {@link org.jhove2.core.format.Format}instance
* @param formatIdentifier {@link org.jhove2.core.I8R} that uniquely identifies this Format
* @return Format instances corresponding to the formatIdentifier
* @throws JHOVE2Exception
*/
public Format getFormat(I8R formatIdentifier)
throws JHOVE2Exception;
}
|
3e193f302614b0f17238d3282ca6fbc0618c0ac0 | 7,352 | java | Java | selected projects/mobile/Signal-Android-4.60.5/app/src/main/java/org/thoughtcrime/securesms/util/DateUtils.java | danielogen/msc_research | 0b6644c11c6152510707d5d6eaf3fab640b3ce7a | [
"MIT"
] | null | null | null | selected projects/mobile/Signal-Android-4.60.5/app/src/main/java/org/thoughtcrime/securesms/util/DateUtils.java | danielogen/msc_research | 0b6644c11c6152510707d5d6eaf3fab640b3ce7a | [
"MIT"
] | null | null | null | selected projects/mobile/Signal-Android-4.60.5/app/src/main/java/org/thoughtcrime/securesms/util/DateUtils.java | danielogen/msc_research | 0b6644c11c6152510707d5d6eaf3fab640b3ce7a | [
"MIT"
] | 1 | 2021-02-01T14:42:08.000Z | 2021-02-01T14:42:08.000Z | 42.252874 | 129 | 0.697361 | 10,723 | /*
* Copyright (C) 2014 Open Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.thoughtcrime.securesms.util;
import android.content.Context;
import android.text.format.DateFormat;
import androidx.annotation.NonNull;
import org.thoughtcrime.securesms.R;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
/**
* Utility methods to help display dates in a nice, easily readable way.
*/
public class DateUtils extends android.text.format.DateUtils {
@SuppressWarnings("unused")
private static final String TAG = DateUtils.class.getSimpleName();
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
private static boolean isWithin(final long millis, final long span, final TimeUnit unit) {
return System.currentTimeMillis() - millis <= unit.toMillis(span);
}
private static boolean isWithinAbs(final long millis, final long span, final TimeUnit unit) {
return Math.abs(System.currentTimeMillis() - millis) <= unit.toMillis(span);
}
private static boolean isYesterday(final long when) {
return DateUtils.isToday(when + TimeUnit.DAYS.toMillis(1));
}
private static int convertDelta(final long millis, TimeUnit to) {
return (int) to.convert(System.currentTimeMillis() - millis, TimeUnit.MILLISECONDS);
}
private static String getFormattedDateTime(long time, String template, Locale locale) {
final String localizedPattern = getLocalizedPattern(template, locale);
return new SimpleDateFormat(localizedPattern, locale).format(new Date(time));
}
public static String getBriefRelativeTimeSpanString(final Context c, final Locale locale, final long timestamp) {
if (isWithin(timestamp, 1, TimeUnit.MINUTES)) {
return c.getString(R.string.DateUtils_just_now);
} else if (isWithin(timestamp, 1, TimeUnit.HOURS)) {
int mins = convertDelta(timestamp, TimeUnit.MINUTES);
return c.getResources().getString(R.string.DateUtils_minutes_ago, mins);
} else if (isWithin(timestamp, 1, TimeUnit.DAYS)) {
int hours = convertDelta(timestamp, TimeUnit.HOURS);
return c.getResources().getQuantityString(R.plurals.hours_ago, hours, hours);
} else if (isWithin(timestamp, 6, TimeUnit.DAYS)) {
return getFormattedDateTime(timestamp, "EEE", locale);
} else if (isWithin(timestamp, 365, TimeUnit.DAYS)) {
return getFormattedDateTime(timestamp, "MMM d", locale);
} else {
return getFormattedDateTime(timestamp, "MMM d, yyyy", locale);
}
}
public static String getExtendedRelativeTimeSpanString(final Context c, final Locale locale, final long timestamp) {
if (isWithin(timestamp, 1, TimeUnit.MINUTES)) {
return c.getString(R.string.DateUtils_just_now);
} else if (isWithin(timestamp, 1, TimeUnit.HOURS)) {
int mins = (int)TimeUnit.MINUTES.convert(System.currentTimeMillis() - timestamp, TimeUnit.MILLISECONDS);
return c.getResources().getString(R.string.DateUtils_minutes_ago, mins);
} else {
StringBuilder format = new StringBuilder();
if (isWithin(timestamp, 6, TimeUnit.DAYS)) format.append("EEE ");
else if (isWithin(timestamp, 365, TimeUnit.DAYS)) format.append("MMM d, ");
else format.append("MMM d, yyyy, ");
if (DateFormat.is24HourFormat(c)) format.append("HH:mm");
else format.append("hh:mm a");
return getFormattedDateTime(timestamp, format.toString(), locale);
}
}
public static String getTimeString(final Context c, final Locale locale, final long timestamp) {
StringBuilder format = new StringBuilder();
if (isSameDay(System.currentTimeMillis(), timestamp)) format.append("");
else if (isWithinAbs(timestamp, 6, TimeUnit.DAYS)) format.append("EEE ");
else if (isWithinAbs(timestamp, 364, TimeUnit.DAYS)) format.append("MMM d, ");
else format.append("MMM d, yyyy, ");
if (DateFormat.is24HourFormat(c)) format.append("HH:mm");
else format.append("hh:mm a");
return getFormattedDateTime(timestamp, format.toString(), locale);
}
public static String getDayPrecisionTimeSpanString(Context context, Locale locale, long timestamp) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
if (simpleDateFormat.format(System.currentTimeMillis()).equals(simpleDateFormat.format(timestamp))) {
return context.getString(R.string.DeviceListItem_today);
} else {
String format;
if (isWithin(timestamp, 6, TimeUnit.DAYS)) format = "EEE ";
else if (isWithin(timestamp, 365, TimeUnit.DAYS)) format = "MMM d";
else format = "MMM d, yyy";
return getFormattedDateTime(timestamp, format, locale);
}
}
public static SimpleDateFormat getDetailedDateFormatter(Context context, Locale locale) {
String dateFormatPattern;
if (DateFormat.is24HourFormat(context)) {
dateFormatPattern = getLocalizedPattern("MMM d, yyyy HH:mm:ss zzz", locale);
} else {
dateFormatPattern = getLocalizedPattern("MMM d, yyyy hh:mm:ss a zzz", locale);
}
return new SimpleDateFormat(dateFormatPattern, locale);
}
public static String getRelativeDate(@NonNull Context context,
@NonNull Locale locale,
long timestamp)
{
if (isToday(timestamp)) {
return context.getString(R.string.DateUtils_today);
} else if (isYesterday(timestamp)) {
return context.getString(R.string.DateUtils_yesterday);
} else {
return formatDate(locale, timestamp);
}
}
public static String formatDate(@NonNull Locale locale, long timestamp) {
return getFormattedDateTime(timestamp, "EEE, MMM d, yyyy", locale);
}
public static String formatDateWithoutDayOfWeek(@NonNull Locale locale, long timestamp) {
return getFormattedDateTime(timestamp, "MMM d yyyy", locale);
}
public static boolean isSameDay(long t1, long t2) {
return DATE_FORMAT.format(new Date(t1)).equals(DATE_FORMAT.format(new Date(t2)));
}
public static boolean isSameExtendedRelativeTimestamp(@NonNull Context context, @NonNull Locale locale, long t1, long t2) {
return getExtendedRelativeTimeSpanString(context, locale, t1).equals(getExtendedRelativeTimeSpanString(context, locale, t2));
}
private static String getLocalizedPattern(String template, Locale locale) {
return DateFormat.getBestDateTimePattern(locale, template);
}
}
|
3e193fad065b707ca16d593d9c2bf21e107d5bbe | 1,578 | java | Java | src/main/java/org/janelia/it/ims/tmog/plugin/SessionListener.java | JaneliaSciComp/tmog | bd15cf409fd564ef1ef95dd4be08a83d859f6f81 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/org/janelia/it/ims/tmog/plugin/SessionListener.java | JaneliaSciComp/tmog | bd15cf409fd564ef1ef95dd4be08a83d859f6f81 | [
"BSD-3-Clause"
] | 1 | 2021-11-24T16:32:29.000Z | 2021-11-24T16:32:29.000Z | src/main/java/org/janelia/it/ims/tmog/plugin/SessionListener.java | JaneliaSciComp/tmog | bd15cf409fd564ef1ef95dd4be08a83d859f6f81 | [
"BSD-3-Clause"
] | null | null | null | 31.56 | 78 | 0.709125 | 10,724 | /*
* Copyright (c) 2011 Howard Hughes Medical Institute.
* All rights reserved.
* Use is subject to Janelia Farm Research Campus Software Copyright 1.1
* license terms (http://license.janelia.org/license/jfrc_copyright_1_1.html).
*/
package org.janelia.it.ims.tmog.plugin;
import org.janelia.it.ims.tmog.DataRow;
import java.util.List;
/**
* This interface identifies the methods required for all session
* event listeners.
*
* @author Eric Trautman
*/
public interface SessionListener extends Plugin {
/**
* Notifies this listener that session processing has started.
*
* @param modelRows list of data rows to be processed.
*
* @throws ExternalDataException
* if a recoverable data error occurs during processing.
* @throws ExternalSystemException
* if a non-recoverable system error occurs during processing.
*
* @return the specified model rows with potentially modified content.
*/
public List<DataRow> startSession(List<DataRow> modelRows)
throws ExternalDataException, ExternalSystemException;
/**
* Notifies this listener that session processing has ended.
*
* @param message a message summarizing what was processed.
*
* @throws ExternalDataException
* if a recoverable data error occurs during processing.
* @throws ExternalSystemException
* if a non-recoverable system error occurs during processing.
*/
public void endSession(String message)
throws ExternalDataException, ExternalSystemException;
}
|
3e193ff8161f85a99054a8dc0f083f01b0bb579b | 13,137 | java | Java | plugin-infra/go-plugin-infra/src/main/java/com/thoughtworks/go/plugin/infra/monitor/DefaultPluginJarLocationMonitor.java | ajesse11x/gocd | 42d1cbe661161b5400289ead86c0447c84af8c0a | [
"Apache-2.0"
] | 1 | 2020-08-01T15:03:16.000Z | 2020-08-01T15:03:16.000Z | plugin-infra/go-plugin-infra/src/main/java/com/thoughtworks/go/plugin/infra/monitor/DefaultPluginJarLocationMonitor.java | gavenwangcn/gocd | d3626f57f8c1a1bac26515caf707a730d00cf076 | [
"Apache-2.0"
] | null | null | null | plugin-infra/go-plugin-infra/src/main/java/com/thoughtworks/go/plugin/infra/monitor/DefaultPluginJarLocationMonitor.java | gavenwangcn/gocd | d3626f57f8c1a1bac26515caf707a730d00cf076 | [
"Apache-2.0"
] | 1 | 2020-08-01T15:03:19.000Z | 2020-08-01T15:03:19.000Z | 42.241158 | 210 | 0.681662 | 10,725 | /*
* Copyright 2017 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.plugin.infra.monitor;
import com.thoughtworks.go.util.SystemEnvironment;
import org.apache.commons.collections4.Closure;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.IterableUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import static com.thoughtworks.go.util.SystemEnvironment.*;
@Component
public class DefaultPluginJarLocationMonitor implements PluginJarLocationMonitor {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultPluginJarLocationMonitor.class);
private List<WeakReference<PluginJarChangeListener>> pluginJarChangeListener = new CopyOnWriteArrayList<>();
private File bundledPluginDirectory;
private final File externalPluginDirectory;
private PluginLocationMonitorThread monitorThread;
private SystemEnvironment systemEnvironment;
@Autowired
public DefaultPluginJarLocationMonitor(SystemEnvironment systemEnvironment) {
this.systemEnvironment = systemEnvironment;
this.bundledPluginDirectory = new File(this.systemEnvironment.get(PLUGIN_GO_PROVIDED_PATH));
this.externalPluginDirectory = new File(this.systemEnvironment.get(PLUGIN_EXTERNAL_PROVIDED_PATH));
}
public void initialize() {
validateBundledPluginDirectory();
validateExternalPluginDirectory();
}
@Override
public void addPluginJarChangeListener(PluginJarChangeListener listener) {
pluginJarChangeListener.add(new WeakReference<>(listener));
removeClearedWeakReferences();
}
@Override
public void removePluginJarChangeListener(final PluginJarChangeListener listener) {
WeakReference<PluginJarChangeListener> referenceOfListenerToBeRemoved = IterableUtils.find(pluginJarChangeListener, listenerWeakReference -> {
PluginJarChangeListener registeredListener = listenerWeakReference.get();
return registeredListener != null && registeredListener == listener;
});
pluginJarChangeListener.remove(referenceOfListenerToBeRemoved);
removeClearedWeakReferences();
}
@Override
public void start() {
initializeMonitorThread();
monitorThread.start();
}
long getLastRun() {
if (monitorThread == null) {
return 0;
}
return monitorThread.getLastRun();
}
private void initializeMonitorThread() {
if (monitorThread != null) {
throw new IllegalStateException("Cannot start the monitor multiple times.");
}
monitorThread = new PluginLocationMonitorThread(bundledPluginDirectory, externalPluginDirectory, pluginJarChangeListener, systemEnvironment);
monitorThread.setDaemon(true);
}
@Override
public void oneShot() {
initializeMonitorThread();
monitorThread.oneShot();
}
@Override
public void stop() {
if (monitorThread == null) {
return;
}
monitorThread.interrupt();
try {
monitorThread.join();
} catch (InterruptedException e) {
}
monitorThread = null;
}
public void validateBundledPluginDirectory() {
if (bundledPluginDirectory.exists()) {
return;
}
try {
LOGGER.debug("Force creating the plugins jar directory as it does not exist {}", bundledPluginDirectory.getAbsolutePath());
FileUtils.forceMkdir(bundledPluginDirectory);
} catch (IOException e) {
String message = "Failed to create plugins folder in location " + bundledPluginDirectory.getAbsolutePath();
LOGGER.warn(message, e);
throw new RuntimeException(message, e);
}
}
private void validateExternalPluginDirectory() {
if (externalPluginDirectory.exists()) {
return;
}
try {
LOGGER.debug("Force creating the plugins jar directory as it does not exist {}", externalPluginDirectory.getAbsolutePath());
FileUtils.forceMkdir(externalPluginDirectory);
} catch (IOException e) {
String message = "Failed to create external plugins folder in location " + externalPluginDirectory.getAbsolutePath();
LOGGER.warn(message, e);
throw new RuntimeException(message, e);
}
}
private void removeClearedWeakReferences() {
Iterator<WeakReference<PluginJarChangeListener>> iterator = pluginJarChangeListener.iterator();
while (iterator.hasNext()) {
WeakReference<PluginJarChangeListener> next = iterator.next();
if (next.get() == null) {
iterator.remove();
}
}
}
private static class PluginLocationMonitorThread extends Thread {
private Set<PluginFileDetails> knownBundledPluginFileDetails = new HashSet<>();
private Set<PluginFileDetails> knownExternalPluginFileDetails = new HashSet<>();
private File bundledPluginDirectory;
private File externalPluginDirectory;
private List<WeakReference<PluginJarChangeListener>> pluginJarChangeListener;
private SystemEnvironment systemEnvironment;
private long lastRun; //used for tests
public PluginLocationMonitorThread(File bundledPluginDirectory, File externalPluginDirectory, List<WeakReference<PluginJarChangeListener>> pluginJarChangeListener, SystemEnvironment systemEnvironment) {
this.bundledPluginDirectory = bundledPluginDirectory;
this.externalPluginDirectory = externalPluginDirectory;
this.pluginJarChangeListener = pluginJarChangeListener;
this.systemEnvironment = systemEnvironment;
}
@Override
public void run() {
do {
oneShot();
int interval = systemEnvironment.get(PLUGIN_LOCATION_MONITOR_INTERVAL_IN_SECONDS);
if (interval <= 0) {
break;
}
waitForMonitorInterval(interval);
} while (!Thread.currentThread().isInterrupted());
}
//Added synchronized because the compiler can change the order of instructions, meaning that the lastRun can be
//updated before the listeners are notified.
//lastRun is needed only for tests. It may be a bit excessive to synchronize methods just for tests. So this can
//definitely be improved in the future
public synchronized void oneShot() {
knownBundledPluginFileDetails = loadAndNotifyPluginsFrom(bundledPluginDirectory, knownBundledPluginFileDetails, true);
knownExternalPluginFileDetails = loadAndNotifyPluginsFrom(externalPluginDirectory, knownExternalPluginFileDetails, false);
lastRun = System.currentTimeMillis();
}
synchronized long getLastRun() {
return lastRun;
}
private Set<PluginFileDetails> loadAndNotifyPluginsFrom(File pluginDirectory, Set<PluginFileDetails> knownPluginFiles, boolean isBundledPluginsLocation) {
Set<PluginFileDetails> currentPluginFiles = getDetailsOfCurrentPluginFilesFrom(pluginDirectory, isBundledPluginsLocation);
notifyListenersOfRemovedPlugins(currentPluginFiles, knownPluginFiles);
notifyListenersOfUpdatedPlugins(currentPluginFiles, knownPluginFiles);
notifyListenersOfAddedPlugins(currentPluginFiles, knownPluginFiles);
return currentPluginFiles;
}
private void notifyListenersOfAddedPlugins(Set<PluginFileDetails> currentPluginFiles, Set<PluginFileDetails> previouslyKnownPluginFiles) {
HashSet<PluginFileDetails> currentPlugins = new HashSet<>(currentPluginFiles);
currentPlugins.removeAll(previouslyKnownPluginFiles);
for (PluginFileDetails newlyAddedPluginFile : currentPlugins) {
doOnAllListeners().pluginJarAdded(newlyAddedPluginFile);
}
}
private void notifyListenersOfRemovedPlugins(Set<PluginFileDetails> currentPluginFiles, Set<PluginFileDetails> previouslyKnownPluginFiles) {
HashSet<PluginFileDetails> previouslyKnownPlugins = new HashSet<>(previouslyKnownPluginFiles);
previouslyKnownPlugins.removeAll(currentPluginFiles);
for (PluginFileDetails removedPluginFile : previouslyKnownPlugins) {
doOnAllListeners().pluginJarRemoved(removedPluginFile);
}
}
private void notifyListenersOfUpdatedPlugins(Set<PluginFileDetails> currentPluginFiles, Set<PluginFileDetails> knownPluginFileDetails) {
final ArrayList<PluginFileDetails> updatedPlugins = findUpdatedPlugins(currentPluginFiles, knownPluginFileDetails);
for (PluginFileDetails updatedPlugin : updatedPlugins) {
doOnAllListeners().pluginJarUpdated(updatedPlugin);
}
}
private PluginJarChangeListener doOnAllListeners() {
return new DoOnAllListeners(pluginJarChangeListener);
}
private void waitForMonitorInterval(int interval) {
try {
Thread.sleep(interval * 1000);
} catch (InterruptedException e) {
this.interrupt();
}
}
private Set<PluginFileDetails> getDetailsOfCurrentPluginFilesFrom(File directory, boolean isBundledPluginsLocation) {
Set<PluginFileDetails> currentPluginFileDetails = new HashSet<>();
for (Object fileOfPlugin : FileUtils.listFiles(directory, new String[]{"jar"}, false)) {
currentPluginFileDetails.add(new PluginFileDetails((File) fileOfPlugin, isBundledPluginsLocation));
}
return currentPluginFileDetails;
}
private ArrayList<PluginFileDetails> findUpdatedPlugins(Set<PluginFileDetails> currentPluginFiles, Set<PluginFileDetails> knownPluginFileDetails) {
final ArrayList<PluginFileDetails> currentPlugins = new ArrayList<>(currentPluginFiles);
final ArrayList<PluginFileDetails> knownPlugins = new ArrayList<>(knownPluginFileDetails);
CollectionUtils.filter(knownPlugins, object -> {
PluginFileDetails knownPlugin = (PluginFileDetails) object;
int i = currentPlugins.indexOf(knownPlugin);
if (i == -1) {
return false;
}
PluginFileDetails plugin = currentPlugins.get(i);
return plugin.doesTimeStampDiffer(knownPlugin);
});
return knownPlugins;
}
public static class DoOnAllListeners implements PluginJarChangeListener {
private List<WeakReference<PluginJarChangeListener>> listeners;
public DoOnAllListeners(List<WeakReference<PluginJarChangeListener>> listeners) {
this.listeners = listeners;
}
@Override
public void pluginJarAdded(final PluginFileDetails pluginFileDetails) {
doOnAllPluginJarChangeListener(o -> o.pluginJarAdded(pluginFileDetails));
}
@Override
public void pluginJarUpdated(final PluginFileDetails pluginFileDetails) {
doOnAllPluginJarChangeListener(o -> o.pluginJarUpdated(pluginFileDetails));
}
@Override
public void pluginJarRemoved(final PluginFileDetails pluginFileDetails) {
doOnAllPluginJarChangeListener(o -> o.pluginJarRemoved(pluginFileDetails));
}
private void doOnAllPluginJarChangeListener(Closure<PluginJarChangeListener> closure) {
for (WeakReference<PluginJarChangeListener> listener : listeners) {
PluginJarChangeListener changeListener = listener.get();
if (changeListener == null) {
continue;
}
try {
closure.execute(changeListener);
} catch (Exception e) {
LOGGER.warn("Plugin listener failed", e);
}
}
}
}
}
}
|
3e194002de4fc178904d2eaea5a27f64ff9458dc | 2,699 | java | Java | software/nbia-web/src/gov/nih/nci/nbia/beans/searchform/AvailableSearchTermsBean.java | TCIA/national-biomedical-image-archive | ac26ef878a3d8818a0037e2b74ace6b8068f4ce1 | [
"BSD-3-Clause"
] | 1 | 2019-04-22T17:38:54.000Z | 2019-04-22T17:38:54.000Z | software/nbia-web/src/gov/nih/nci/nbia/beans/searchform/AvailableSearchTermsBean.java | TCIA/national-biomedical-image-archive | ac26ef878a3d8818a0037e2b74ace6b8068f4ce1 | [
"BSD-3-Clause"
] | null | null | null | software/nbia-web/src/gov/nih/nci/nbia/beans/searchform/AvailableSearchTermsBean.java | TCIA/national-biomedical-image-archive | ac26ef878a3d8818a0037e2b74ace6b8068f4ce1 | [
"BSD-3-Clause"
] | null | null | null | 34.602564 | 112 | 0.68618 | 10,726 | /*L
* Copyright SAIC, Ellumen and RSNA (CTP)
*
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/national-biomedical-image-archive/LICENSE.txt for details.
*/
package gov.nih.nci.nbia.beans.searchform;
import gov.nih.nci.nbia.beans.BeanManager;
import gov.nih.nci.nbia.lookup.LookupManager;
import gov.nih.nci.ncia.search.AvailableSearchTerms;
import gov.nih.nci.ncia.search.UsAvailableSearchTerms;
import gov.nih.nci.ncia.search.NBIANode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class AvailableSearchTermsBean {
////////////////////// Public /////////////////////////////
/**
* Return the available search terms for all NBIA nodes that the system recoginzes.
* This is cached per session.
*/
public List<AvailableSearchTermsWrapper> getNode() {
if (wrapperList == null) {
wrapperList = new ArrayList<AvailableSearchTermsWrapper>();
searchableNodes = lookupManager.getSearchableNodes().entrySet();
searchableNodesForUs = lookupManager.getSearchableNodesForUs().entrySet();
for(Iterator<Map.Entry<NBIANode, AvailableSearchTerms>> iterator = searchableNodes.iterator();
iterator.hasNext() ; )
{
Map.Entry<NBIANode, AvailableSearchTerms> entry =iterator.next();
NBIANode key = (NBIANode)entry.getKey();
AvailableSearchTerms value = (AvailableSearchTerms)entry.getValue();
AvailableSearchTermsWrapper wrapper = new AvailableSearchTermsWrapper();
wrapper.setNode(key);
wrapper.setTerms(value);
for(Iterator<Map.Entry<NBIANode, UsAvailableSearchTerms>> iteratorUs = searchableNodesForUs.iterator();
iteratorUs.hasNext() ; ){
Map.Entry<NBIANode, UsAvailableSearchTerms> usEntry =iteratorUs.next();
NBIANode usKey = (NBIANode)usEntry.getKey();
UsAvailableSearchTerms usValue = (UsAvailableSearchTerms)usEntry.getValue();
if(usKey.compareTo(key)==0) {
wrapper.setNewTerms(usValue);
}
}
wrapperList.add(wrapper);
}
Collections.sort(wrapperList);
return wrapperList;
}
else {
return wrapperList;
}
}
//////////////////////////// Private /////////////////////
private Set<Map.Entry<NBIANode, AvailableSearchTerms>> searchableNodes;
private Set<Map.Entry<NBIANode, UsAvailableSearchTerms>> searchableNodesForUs;
private List<AvailableSearchTermsWrapper> wrapperList;
private LookupManager lookupManager = BeanManager.getSearchWorkflowBean().getLookupMgr();
}
|
3e194257130cf7fcc31d95d4e343cedc697f5842 | 2,054 | java | Java | hw1_3/src/main/java/hw1testforstudents/test/TestImpl.java | Etoneon/ot-spring-2022 | 3c6827973198d5efa4e9aab766aec84bd808e1b9 | [
"MIT"
] | null | null | null | hw1_3/src/main/java/hw1testforstudents/test/TestImpl.java | Etoneon/ot-spring-2022 | 3c6827973198d5efa4e9aab766aec84bd808e1b9 | [
"MIT"
] | null | null | null | hw1_3/src/main/java/hw1testforstudents/test/TestImpl.java | Etoneon/ot-spring-2022 | 3c6827973198d5efa4e9aab766aec84bd808e1b9 | [
"MIT"
] | null | null | null | 28.929577 | 119 | 0.565239 | 10,727 | package hw1testforstudents.test;
import hw1testforstudents.domain.Person;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TestImpl implements Test {
private final static String COMMA_DELIMITER = ",";
private String fileNameCSV = " ";
public void setFileNameCSV (String fileNameCSV) {
this.fileNameCSV = fileNameCSV;
}
@Override
public void performTest(Person person){
person.test.clear();
InputStream fromCSVfile =
getClass().getClassLoader().getResourceAsStream(fileNameCSV);
try (Scanner scanner = new Scanner(fromCSVfile)) {
while (scanner.hasNextLine()) {
person.test.add(getRecordFromLine(scanner.nextLine()));
}
}
System.out.println("Hi "+ person.getName()+" "+ person.getSurname() + ", please answer following questions: ");
for (List<String> list : person.test) {
askQuestion(list);
list.set(0,receiveAnswer());
}
}
private void askQuestion(List<String> list){
System.out.println(list.get(2));
for (int i = 3; i < list.size(); i++){
if (i%2 != 0 ) {
System.out.print(list.get(i)+": ");
} else {
System.out.print(list.get(i)+"\n");
}
}
}
private String receiveAnswer(){
String[] answers = {"A","B","C","D","E"};
int r = (int) Math.round(Math.random()*5.0 - 0.5);
System.out.println("Please enter your choice: " + answers[r]);
return answers[r];
}
private List<String> getRecordFromLine(String line) {
List<String> entries = new ArrayList();
try (Scanner lineScanner = new Scanner(line)) {
lineScanner.useDelimiter(COMMA_DELIMITER);
while (lineScanner.hasNext()) {
entries.add(lineScanner.next());
}
}
return entries;
}
}
|
3e1942a78b2cb878105e5dd276e89da4d308a999 | 1,514 | java | Java | testbench/testsolutions/editor.test/source_gen/jetbrains/mps/lang/editor/label/tests/LabelWithBrackets_RemoveText_Test.java | trespasserw/MPS | dbc5c76496e8ccef46dd420eefcd5089b1bc234b | [
"Apache-2.0"
] | null | null | null | testbench/testsolutions/editor.test/source_gen/jetbrains/mps/lang/editor/label/tests/LabelWithBrackets_RemoveText_Test.java | trespasserw/MPS | dbc5c76496e8ccef46dd420eefcd5089b1bc234b | [
"Apache-2.0"
] | null | null | null | testbench/testsolutions/editor.test/source_gen/jetbrains/mps/lang/editor/label/tests/LabelWithBrackets_RemoveText_Test.java | trespasserw/MPS | dbc5c76496e8ccef46dd420eefcd5089b1bc234b | [
"Apache-2.0"
] | null | null | null | 35.209302 | 226 | 0.778732 | 10,728 | package jetbrains.mps.lang.editor.label.tests;
/*Generated by MPS */
import jetbrains.mps.MPSLaunch;
import jetbrains.mps.lang.test.runtime.BaseTransformationTest;
import org.junit.ClassRule;
import jetbrains.mps.lang.test.runtime.TestParametersCache;
import org.junit.Test;
import jetbrains.mps.lang.test.runtime.BaseEditorTestBody;
import jetbrains.mps.lang.test.runtime.TransformationTest;
@MPSLaunch
public class LabelWithBrackets_RemoveText_Test extends BaseTransformationTest {
@ClassRule
public static final TestParametersCache ourParamCache = new TestParametersCache(LabelWithBrackets_RemoveText_Test.class, "${mps_home}", "r:40a702b4-7737-42f4-8412-0355208396f3(jetbrains.mps.lang.editor.label.tests)", false);
public LabelWithBrackets_RemoveText_Test() {
super(ourParamCache);
}
@Test
public void test_LabelWithBrackets_RemoveText() throws Throwable {
new TestBody(this).testMethod();
}
/*package*/ static class TestBody extends BaseEditorTestBody {
/*package*/ TestBody(TransformationTest owner) {
super(owner);
}
@Override
public void testMethodImpl() throws Exception {
initEditorComponent("6546125805699762593", "6546125805699762595");
invokeAction("jetbrains.mps.ide.editor.actions.Backspace_Action");
invokeAction("jetbrains.mps.ide.editor.actions.Backspace_Action");
invokeAction("jetbrains.mps.ide.editor.actions.Backspace_Action");
invokeAction("jetbrains.mps.ide.editor.actions.Backspace_Action");
}
}
}
|
3e1942bd953e35dd96196f0505cb59190ed474af | 4,564 | java | Java | consumer_rabbit_middleware/src/test/java/com/example/ApplicationTests.java | guhuajun/spring-cloud-contract-samples | 41b7f12809ce31a559e57599df17945f8b2363ac | [
"Apache-2.0"
] | 339 | 2016-11-24T05:23:30.000Z | 2022-03-03T01:03:47.000Z | consumer_rabbit_middleware/src/test/java/com/example/ApplicationTests.java | guhuajun/spring-cloud-contract-samples | 41b7f12809ce31a559e57599df17945f8b2363ac | [
"Apache-2.0"
] | 159 | 2016-11-09T17:36:24.000Z | 2022-03-30T05:16:17.000Z | consumer_rabbit_middleware/src/test/java/com/example/ApplicationTests.java | guhuajun/spring-cloud-contract-samples | 41b7f12809ce31a559e57599df17945f8b2363ac | [
"Apache-2.0"
] | 325 | 2016-11-24T05:23:35.000Z | 2022-03-04T06:20:04.000Z | 36.512 | 170 | 0.786372 | 10,729 | /*
* Copyright 2018-2019 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
*
* 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.
*/
package com.example;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.assertj.core.api.BDDAssertions;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.RabbitMQContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.contract.stubrunner.StubTrigger;
import org.springframework.cloud.contract.stubrunner.spring.AutoConfigureStubRunner;
import org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties;
import org.springframework.cloud.contract.verifier.converter.YamlContract;
import org.springframework.cloud.contract.verifier.messaging.MessageVerifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE, classes = {TestConfig.class, Application.class}, properties = "stubrunner.amqp.mockConnection=false")
@AutoConfigureStubRunner(ids = "com.example:beer-api-producer-rabbit-middleware", stubsMode = StubRunnerProperties.StubsMode.LOCAL)
@Testcontainers
@ActiveProfiles("test")
public class ApplicationTests {
@Container static RabbitMQContainer rabbit = new RabbitMQContainer();
@DynamicPropertySource
static void rabbitProperties(DynamicPropertyRegistry registry) {
rabbit.start();
registry.add("spring.rabbitmq.port", rabbit::getAmqpPort);
}
@Autowired
StubTrigger trigger;
@Autowired
Application application;
@Test
public void contextLoads() {
this.trigger.trigger("trigger");
Awaitility.await().untilAsserted(() -> {
BDDAssertions.then(this.application.storedFoo).isNotNull();
BDDAssertions.then(this.application.storedFoo.getFoo()).isEqualTo("example");
});
}
}
@Configuration
class TestConfig {
private static final Logger log = LoggerFactory.getLogger(TestConfig.class);
@Bean
MessageVerifier<Message> testMessageVerifier(RabbitTemplate rabbitTemplate) {
return new MessageVerifier<>() {
@Override
public Message receive(String destination, long timeout, TimeUnit timeUnit, @Nullable YamlContract contract) {
return null;
}
@Override
public Message receive(String destination, YamlContract contract) {
return null;
}
@Override
public void send(Message message, String destination, @Nullable YamlContract contract) {
rabbitTemplate.send(destination, message);
}
@Override
public <T> void send(T payload, Map<String, Object> headers, String destination, @Nullable YamlContract contract) {
Map<String, Object> newHeaders = headers != null ? new HashMap<>(headers) : new HashMap<>();
MessageProperties messageProperties = new MessageProperties();
newHeaders.forEach(messageProperties::setHeader);
log.info("Sending a message to destination [{}] with routing key", destination);
if (payload instanceof String) {
String json = (String) payload;
Message message = MessageBuilder.withBody(json.getBytes(StandardCharsets.UTF_8)).andProperties(messageProperties).build();
send(message, destination, contract);
} else {
throw new IllegalStateException("Payload is not a String");
}
}
};
}
}
|
3e1942e35e1585784e7e68f18044b12993153c04 | 966 | java | Java | src/main/java/com/github/east196/ezsb/core/BootException.java | East196/easyboot | b5f4a2d86c3b69a4a1fc9b163824626c31c4032f | [
"Apache-2.0"
] | 1 | 2018-09-09T14:16:59.000Z | 2018-09-09T14:16:59.000Z | src/main/java/com/github/east196/ezsb/core/BootException.java | East196/easyboot | b5f4a2d86c3b69a4a1fc9b163824626c31c4032f | [
"Apache-2.0"
] | null | null | null | src/main/java/com/github/east196/ezsb/core/BootException.java | East196/easyboot | b5f4a2d86c3b69a4a1fc9b163824626c31c4032f | [
"Apache-2.0"
] | null | null | null | 18.226415 | 62 | 0.530021 | 10,730 | package com.github.east196.ezsb.core;
import lombok.Data;
/**
* @author east196
*/
@Data
public class BootException extends RuntimeException {
private String msg;
public BootException(String msg){
super(msg);
this.msg = msg;
}
private int code = 500;
public BootException(String msg, Throwable e) {
super(msg, e);
this.msg = msg;
}
public BootException(String msg, int code) {
super(msg);
this.msg = msg;
this.code = code;
}
public BootException(String msg, int code, Throwable e) {
super(msg, e);
this.msg = msg;
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
|
3e19439db2e1baa4e9111d826e1d05ff472f891a | 3,709 | java | Java | scansite-shared/src/main/java/edu/mit/scansite/shared/transferobjects/RestrictionProperties.java | kkrismer/scansite | e331f488130289f0aff5d247521d09430f29249f | [
"MIT"
] | null | null | null | scansite-shared/src/main/java/edu/mit/scansite/shared/transferobjects/RestrictionProperties.java | kkrismer/scansite | e331f488130289f0aff5d247521d09430f29249f | [
"MIT"
] | null | null | null | scansite-shared/src/main/java/edu/mit/scansite/shared/transferobjects/RestrictionProperties.java | kkrismer/scansite | e331f488130289f0aff5d247521d09430f29249f | [
"MIT"
] | null | null | null | 24.562914 | 67 | 0.758695 | 10,731 | package edu.mit.scansite.shared.transferobjects;
import java.util.List;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* @author Konstantin Krismer
*/
public class RestrictionProperties implements IsSerializable {
private OrganismClass organismClass = OrganismClass.MAMMALIA;
private String speciesRegEx = null;
private int phosphorylatedSites = 0;
private Double molecularWeightFrom = null;
private Double molecularWeightTo = null;
private Double isoelectricPointFrom = null;
private Double isoelectricPointTo = null;
private String keywordRegEx = null;
private List<String> sequenceRegEx = null;
public RestrictionProperties() {
}
public RestrictionProperties(OrganismClass organismClass,
String speciesRegEx, int phosphorylatedSites,
Double molecularWeightFrom, Double molecularWeightTo,
Double isoelectricPointFrom, Double isoelectricPointTo,
String keywordRegEx, List<String> sequenceRegEx) {
this.organismClass = organismClass;
if (speciesRegEx != null && !speciesRegEx.isEmpty()) {
this.speciesRegEx = speciesRegEx;
}
this.phosphorylatedSites = phosphorylatedSites;
this.molecularWeightFrom = molecularWeightFrom;
this.molecularWeightTo = molecularWeightTo;
this.isoelectricPointFrom = isoelectricPointFrom;
this.isoelectricPointTo = isoelectricPointTo;
if (keywordRegEx != null && !keywordRegEx.isEmpty()) {
this.keywordRegEx = keywordRegEx;
}
if (sequenceRegEx != null && !sequenceRegEx.isEmpty()) {
this.sequenceRegEx = sequenceRegEx;
}
}
public boolean isDefault() {
if (!organismClass.equals(OrganismClass.MAMMALIA)) {
return false;
}
if (speciesRegEx != null) {
return false;
}
if (phosphorylatedSites != 0) {
return false;
}
if (molecularWeightFrom != null) {
return false;
}
if (molecularWeightTo != null) {
return false;
}
if (isoelectricPointFrom != null) {
return false;
}
if (isoelectricPointTo != null) {
return false;
}
if (keywordRegEx != null) {
return false;
}
if (sequenceRegEx != null) {
return false;
}
return true;
}
public OrganismClass getOrganismClass() {
return organismClass;
}
public void setOrganismClass(OrganismClass organismClass) {
this.organismClass = organismClass;
}
public String getSpeciesRegEx() {
return speciesRegEx;
}
public void setSpeciesRegEx(String speciesRegEx) {
this.speciesRegEx = speciesRegEx;
}
public int getPhosphorylatedSites() {
return phosphorylatedSites;
}
public void setPhosphorylatedSites(int phosphorylatedSites) {
this.phosphorylatedSites = phosphorylatedSites;
}
public Double getMolecularWeightFrom() {
return molecularWeightFrom;
}
public void setMolecularWeightFrom(Double molecularWeightFrom) {
this.molecularWeightFrom = molecularWeightFrom;
}
public Double getMolecularWeightTo() {
return molecularWeightTo;
}
public void setMolecularWeightTo(Double molecularWeightTo) {
this.molecularWeightTo = molecularWeightTo;
}
public Double getIsoelectricPointFrom() {
return isoelectricPointFrom;
}
public void setIsoelectricPointFrom(Double isoelectricPointFrom) {
this.isoelectricPointFrom = isoelectricPointFrom;
}
public Double getIsoelectricPointTo() {
return isoelectricPointTo;
}
public void setIsoelectricPointTo(Double isoelectricPointTo) {
this.isoelectricPointTo = isoelectricPointTo;
}
public String getKeywordRegEx() {
return keywordRegEx;
}
public void setKeywordRegEx(String keywordRegEx) {
this.keywordRegEx = keywordRegEx;
}
public List<String> getSequenceRegEx() {
return sequenceRegEx;
}
public void setSequenceRegEx(List<String> sequenceRegEx) {
this.sequenceRegEx = sequenceRegEx;
}
}
|
3e1943a8ed82b544db5be3686df5c23e306a1752 | 3,222 | java | Java | SDK4_1_1/junit/src/test/gov/nih/nci/cacoresdk/domain/onetoone/bidirectional/withjoin/O2OBidirectionalWithJoinWritableApiTest.java | NCIP/lexevs-remote | 0915afa3467f0e4724e5f59d1de46cd0267c63f1 | [
"BSD-3-Clause"
] | 1 | 2021-04-28T22:10:19.000Z | 2021-04-28T22:10:19.000Z | SDK4_1_1/junit/src/test/gov/nih/nci/cacoresdk/domain/onetoone/bidirectional/withjoin/O2OBidirectionalWithJoinWritableApiTest.java | NCIP/lexevs-remote | 0915afa3467f0e4724e5f59d1de46cd0267c63f1 | [
"BSD-3-Clause"
] | 2 | 2015-01-09T19:57:02.000Z | 2018-05-15T21:37:54.000Z | SDK4_1_1/junit/src/test/gov/nih/nci/cacoresdk/domain/onetoone/bidirectional/withjoin/O2OBidirectionalWithJoinWritableApiTest.java | NCIP/lexevs-remote | 0915afa3467f0e4724e5f59d1de46cd0267c63f1 | [
"BSD-3-Clause"
] | 1 | 2016-10-04T04:00:45.000Z | 2016-10-04T04:00:45.000Z | 37.465116 | 103 | 0.724084 | 10,732 | package test.gov.nih.nci.cacoresdk.domain.onetoone.bidirectional.withjoin;
import org.apache.log4j.Logger;
import gov.nih.nci.cacoresdk.domain.onetoone.bidirectional.withjoin.Chain;
import gov.nih.nci.cacoresdk.domain.onetoone.bidirectional.withjoin.Pendant;
import junit.framework.Assert;
import test.gov.nih.nci.cacoresdk.SDKWritableApiBaseTest;
public class O2OBidirectionalWithJoinWritableApiTest extends SDKWritableApiBaseTest {
private static Logger log = Logger.getLogger(O2OBidirectionalWithJoinWritableApiTest.class);
public static String getTestCaseName() {
return "One to One Bidirectional With Join WritableApi Test Case";
}
public void testSaveObjectChain(){
log.debug("\n-----------testSaveObjectChain()--------\n");
Chain chain=new Chain();
chain.setMetal("metal");
save(chain);
Chain resultChain=(Chain)getObject(Chain.class, chain.getId());
Assert.assertEquals(chain.getMetal(), resultChain.getMetal());
}
public void testSaveObjectPendantOne2OneChain(){
log.debug("\n-----------testSaveObjectPendantOne2OneChain()--------\n");
Chain chain = new Chain();
chain.setMetal("metal");
Pendant pendant = new Pendant();
pendant.setShape("shape");
chain.setPendant(pendant);
save(pendant);
save(chain); //inverse=false on chain.hbm.xml
Chain resultChain=(Chain)getObjectAndLazyObject(Chain.class, chain.getId(), "pendant");
Assert.assertEquals(chain.getMetal(), resultChain.getMetal());
Assert.assertEquals(pendant.getShape(), resultChain.getPendant().getShape());
}
public void testUpdateChainOnetoOneCascadeDeletePendant(){
log.debug("\n-----------testUpdateChainOnetoOneCascadeDeletePendant()--------\n");
Chain chain=new Chain();
chain.setMetal("metal");
Pendant pendant = new Pendant();
pendant.setShape("shape");
chain.setPendant(pendant);
save(pendant);
save(chain);//inverse=false on chain.hbm.xml
Chain updateChain=(Chain)getObjectAndLazyObject(Chain.class, chain.getId(), "pendant");
updateChain.setMetal("updateMetal");
updateChain.getPendant().setShape("updateShape");
update(updateChain);
Chain resultChain=(Chain)getObjectAndLazyObject(Chain.class, chain.getId(), "pendant");
Assert.assertEquals(updateChain.getMetal(), resultChain.getMetal());
Assert.assertFalse(updateChain.getPendant().getShape().equals(resultChain.getPendant().getShape()));
}
public void testDeleteChainOnetoOneCascadeDeletePendant(){
log.debug("\n-----------deleteChainOnetoOneCascadeDeletePendant()--------\n");
Chain chain = new Chain();
chain.setMetal("metal");
Pendant pendant = new Pendant();
pendant.setShape("shape");
chain.setPendant(pendant);
save(pendant);
save(chain);//inverse=false on chain.hbm.xml
Chain deleteChain=(Chain)getObjectAndLazyObject(Chain.class, chain.getId(), "pendant");
delete(deleteChain);
Chain resultChain=(Chain)getObject(Chain.class, chain.getId());
Pendant resultPendant=(Pendant)getObject(Pendant.class, pendant.getId());
Assert.assertNull("chain must be deleted ",resultChain);
Assert.assertNull("pendant must be deleted as cascade=delete",resultPendant);
}
}
|
3e19440ff0e227296d40b4eda624c1ba947176b8 | 1,383 | java | Java | app/src/main/java/com/github/st1hy/countthemcalories/core/command/undo/UndoInvalidator.java | st1hy/Red-Calories | db5111abad35eecd9f10e4292cede66a7a9d9c4c | [
"MIT"
] | 3 | 2017-02-23T15:53:53.000Z | 2017-10-22T21:16:25.000Z | app/src/main/java/com/github/st1hy/countthemcalories/core/command/undo/UndoInvalidator.java | st1hy/Red-Calories | db5111abad35eecd9f10e4292cede66a7a9d9c4c | [
"MIT"
] | 19 | 2016-07-16T13:53:53.000Z | 2017-01-24T22:06:42.000Z | app/src/main/java/com/github/st1hy/countthemcalories/core/command/undo/UndoInvalidator.java | st1hy/Red-Calories | db5111abad35eecd9f10e4292cede66a7a9d9c4c | [
"MIT"
] | null | null | null | 32.928571 | 122 | 0.62979 | 10,733 | package com.github.st1hy.countthemcalories.core.command.undo;
import android.support.annotation.NonNull;
import com.github.st1hy.countthemcalories.core.command.CommandResponse;
import java.util.concurrent.atomic.AtomicReference;
import rx.Observable;
public class UndoInvalidator<Re, Un> implements Observable.Transformer<CommandResponse<Re, Un>, CommandResponse<Re, Un>> {
@NonNull
private final AtomicReference<CommandResponse> lastResponse;
public UndoInvalidator() {
lastResponse = new AtomicReference<>();
}
public UndoInvalidator(@NonNull AtomicReference<CommandResponse> lastResponse) {
this.lastResponse = lastResponse;
}
@Override
public Observable<CommandResponse<Re, Un>> call(Observable<CommandResponse<Re, Un>> observable) {
return observable
.doOnSubscribe(() -> {
CommandResponse commandResponse1 = lastResponse.getAndSet(null);
if (commandResponse1 != null) {
commandResponse1.invalidate();
}
})
.doOnNext(newResponse -> {
CommandResponse commandResponse = lastResponse.getAndSet(newResponse);
if (commandResponse != null) {
commandResponse.invalidate();
}
});
}
}
|
3e19443602152b5d94d2ec0d3dcb42ccadba2fbb | 1,706 | java | Java | src/com/nshirley/engine3d/utils/BufferUtils.java | natethegreat2525/3dEngine | 3521b1e3363472b30af3634f21e129b0936224da | [
"MIT"
] | 1 | 2017-01-02T15:54:03.000Z | 2017-01-02T15:54:03.000Z | src/com/nshirley/engine3d/utils/BufferUtils.java | natethegreat2525/3dEngine | 3521b1e3363472b30af3634f21e129b0936224da | [
"MIT"
] | null | null | null | src/com/nshirley/engine3d/utils/BufferUtils.java | natethegreat2525/3dEngine | 3521b1e3363472b30af3634f21e129b0936224da | [
"MIT"
] | 1 | 2018-03-12T17:27:40.000Z | 2018-03-12T17:27:40.000Z | 27.967213 | 111 | 0.739742 | 10,734 | package com.nshirley.engine3d.utils;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.HashMap;
public class BufferUtils {
private BufferUtils() {
}
private static HashMap<Integer, ArrayList<FloatBuffer>> floatBufferQueue;
static {
floatBufferQueue = new HashMap<Integer, ArrayList<FloatBuffer>>();
}
private static FloatBuffer genFloatBuffer(int size) {
ArrayList<FloatBuffer> bufferList = floatBufferQueue.get(size);
if (bufferList != null && bufferList.size() > 0) {
FloatBuffer buffer = bufferList.remove(bufferList.size() - 1);
return buffer;
}
return ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder()).asFloatBuffer();
}
public static void freeFloatBuffer(FloatBuffer buffer) {
int size = buffer.capacity() * 4;
buffer.rewind();
ArrayList<FloatBuffer> bufferList = floatBufferQueue.get(size);
if (bufferList == null) {
bufferList = new ArrayList<FloatBuffer>();
floatBufferQueue.put(size, bufferList);
}
bufferList.add(buffer);
}
public static ByteBuffer createByteBuffer(byte[] array) {
ByteBuffer result = ByteBuffer.allocateDirect(array.length).order(ByteOrder.nativeOrder());
result.put(array).flip();
return result;
}
public static FloatBuffer createFloatBuffer(float[] array) {
FloatBuffer result = genFloatBuffer(array.length << 2);
result.put(array).flip();
return result;
}
public static IntBuffer createIntBuffer(int[] array) {
IntBuffer result = ByteBuffer.allocateDirect(array.length << 2).order(ByteOrder.nativeOrder()).asIntBuffer();
result.put(array).flip();
return result;
}
}
|
3e1946550287f5e561a0c268cb6f2af0568c3a06 | 3,277 | java | Java | aliyun-java-sdk-qualitycheck/src/main/java/com/aliyuncs/qualitycheck/model/v20190115/GetCustomizationConfigListResponse.java | czy95czy/aliyun-openapi-java-sdk | 5410bde6a54fe40a471b43e50696f991f5df25aa | [
"Apache-2.0"
] | 3 | 2021-01-25T16:15:23.000Z | 2021-01-25T16:15:54.000Z | aliyun-java-sdk-qualitycheck/src/main/java/com/aliyuncs/qualitycheck/model/v20190115/GetCustomizationConfigListResponse.java | xunanping/aliyun-openapi-java-sdk | 6784f7a7e9a841b221076c8bad01541cc663cd95 | [
"Apache-2.0"
] | null | null | null | aliyun-java-sdk-qualitycheck/src/main/java/com/aliyuncs/qualitycheck/model/v20190115/GetCustomizationConfigListResponse.java | xunanping/aliyun-openapi-java-sdk | 6784f7a7e9a841b221076c8bad01541cc663cd95 | [
"Apache-2.0"
] | null | null | null | 22.445205 | 101 | 0.715899 | 10,735 | /*
* 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.aliyuncs.qualitycheck.model.v20190115;
import java.util.List;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.qualitycheck.transform.v20190115.GetCustomizationConfigListResponseUnmarshaller;
import com.aliyuncs.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class GetCustomizationConfigListResponse extends AcsResponse {
private String requestId;
private Boolean success;
private String code;
private String message;
private List<ModelCustomizationDataSetPo> data;
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public Boolean getSuccess() {
return this.success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
public List<ModelCustomizationDataSetPo> getData() {
return this.data;
}
public void setData(List<ModelCustomizationDataSetPo> data) {
this.data = data;
}
public static class ModelCustomizationDataSetPo {
private Long modelId;
private String modeCustomizationId;
private String modelName;
private Integer modelStatus;
private Integer taskType;
private String createTime;
public Long getModelId() {
return this.modelId;
}
public void setModelId(Long modelId) {
this.modelId = modelId;
}
public String getModeCustomizationId() {
return this.modeCustomizationId;
}
public void setModeCustomizationId(String modeCustomizationId) {
this.modeCustomizationId = modeCustomizationId;
}
public String getModelName() {
return this.modelName;
}
public void setModelName(String modelName) {
this.modelName = modelName;
}
public Integer getModelStatus() {
return this.modelStatus;
}
public void setModelStatus(Integer modelStatus) {
this.modelStatus = modelStatus;
}
public Integer getTaskType() {
return this.taskType;
}
public void setTaskType(Integer taskType) {
this.taskType = taskType;
}
public String getCreateTime() {
return this.createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
}
@Override
public GetCustomizationConfigListResponse getInstance(UnmarshallerContext context) {
return GetCustomizationConfigListResponseUnmarshaller.unmarshall(this, context);
}
}
|
3e19469c48eabd69342602bba62f5928b348974e | 366 | java | Java | src/main/java/io/shelang/aghab/service/dto/LinkMetaDTO.java | shelang/aghab | a414f7d17c7c7aab213392718fbd9bce059211b7 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/shelang/aghab/service/dto/LinkMetaDTO.java | shelang/aghab | a414f7d17c7c7aab213392718fbd9bce059211b7 | [
"Apache-2.0"
] | 2 | 2021-04-11T13:16:13.000Z | 2021-05-01T06:34:45.000Z | src/main/java/io/shelang/aghab/service/dto/LinkMetaDTO.java | shelang/aghab | a414f7d17c7c7aab213392718fbd9bce059211b7 | [
"Apache-2.0"
] | null | null | null | 19.263158 | 37 | 0.79235 | 10,736 | package io.shelang.aghab.service.dto;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.time.Instant;
@Data
@Accessors(chain = true)
@NoArgsConstructor
public class LinkMetaDTO {
private Long id;
private String title;
private String description;
private Instant createAt;
private Instant updateAt;
}
|
3e19472702db6d1a2414581f0aaa326aba7d9fb2 | 2,497 | java | Java | app/src/main/java/com/adam/aslfms/util/MyContextWrapper.java | franciscojunior/sls | 1c933bc9752205e939badbdf9fe53d4117d90016 | [
"Apache-2.0"
] | 275 | 2015-01-13T12:41:28.000Z | 2019-08-10T20:26:06.000Z | app/src/main/java/com/adam/aslfms/util/MyContextWrapper.java | AdrianaDJ/sls | 04380f4ea9224ba12d4682b7605fa3b6f9c6cc77 | [
"Apache-2.0"
] | 384 | 2015-01-02T17:11:50.000Z | 2019-08-11T12:34:31.000Z | app/src/main/java/com/adam/aslfms/util/MyContextWrapper.java | AdrianaDJ/sls | 04380f4ea9224ba12d4682b7605fa3b6f9c6cc77 | [
"Apache-2.0"
] | 101 | 2015-01-08T16:55:02.000Z | 2019-08-09T19:25:52.000Z | 34.680556 | 88 | 0.705647 | 10,737 | /**
* This file is part of Simple Scrobbler.
* <p>
* https://github.com/simple-last-fm-scrobbler/sls
* <p>
* Copyright 2011 Simple Scrobbler Team
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.adam.aslfms.util;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import java.util.Locale;
public class MyContextWrapper{
private static final String TAG = "MyContextWrapper";
public static Context wrap(Context context) {
AppSettings appSettings = new AppSettings(context);
String language = appSettings.getAppLocale();
String[] language_region = language.split("-r");
Locale locale = null;
if (language_region.length == 1) {
locale = new Locale(language_region[0]);
} else if (language_region.length == 2){
locale = new Locale(language_region[0],language_region[1]);
} else {
}
Locale.setDefault(locale);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResourcesLocale(context, locale);
}
return updateResourcesLocaleLegacy(context, locale);
}
@TargetApi(Build.VERSION_CODES.N)
private static Context updateResourcesLocale(Context context, Locale locale) {
Configuration configuration = context.getResources().getConfiguration();
configuration.setLocale(locale);
return context.createConfigurationContext(configuration);
}
@SuppressWarnings("deprecation")
private static Context updateResourcesLocaleLegacy(Context context, Locale locale) {
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = locale;
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
return context;
}
} |
3e19475ee43dd9fb4e87c052ea66e52e0ac88765 | 242 | java | Java | northstar-strategy-common/src/main/java/tech/xuanwu/northstar/strategy/common/event/ModuleEvent.java | kevinhuangwl/northstar | 1b2826d7b62dc99227b9ee210471a9dbb86f224f | [
"Apache-2.0"
] | 11 | 2020-04-21T20:51:40.000Z | 2021-07-20T01:49:33.000Z | northstar-strategy-common/src/main/java/tech/xuanwu/northstar/strategy/common/event/ModuleEvent.java | butter-fly/northstar | 74f8e44a24b7fbda9da7051e031495e1deadacb0 | [
"Apache-2.0"
] | null | null | null | northstar-strategy-common/src/main/java/tech/xuanwu/northstar/strategy/common/event/ModuleEvent.java | butter-fly/northstar | 74f8e44a24b7fbda9da7051e031495e1deadacb0 | [
"Apache-2.0"
] | 4 | 2020-04-21T20:51:43.000Z | 2021-07-18T13:04:44.000Z | 12.736842 | 52 | 0.739669 | 10,738 | package tech.xuanwu.northstar.strategy.common.event;
import lombok.Builder;
import lombok.Data;
/**
*
* @author KevinHuangwl
*
*/
@Data
@Builder
public class ModuleEvent {
private ModuleEventType eventType;
private Object data;
}
|
3e19489f5d293073ccd7bbf6268cc2e62e03f545 | 13,901 | java | Java | mso-api-handlers/mso-api-handler-infra/src/test/java/org/openecomp/mso/apihandlerinfra/tenantisolation/CloudResourcesOrchestrationTest.java | kweveen/so | f5618da7e8d8398d5f85fe950fd5c88e84481f83 | [
"Apache-2.0"
] | null | null | null | mso-api-handlers/mso-api-handler-infra/src/test/java/org/openecomp/mso/apihandlerinfra/tenantisolation/CloudResourcesOrchestrationTest.java | kweveen/so | f5618da7e8d8398d5f85fe950fd5c88e84481f83 | [
"Apache-2.0"
] | null | null | null | mso-api-handlers/mso-api-handler-infra/src/test/java/org/openecomp/mso/apihandlerinfra/tenantisolation/CloudResourcesOrchestrationTest.java | kweveen/so | f5618da7e8d8398d5f85fe950fd5c88e84481f83 | [
"Apache-2.0"
] | null | null | null | 41.61976 | 123 | 0.730955 | 10,739 | /*-
* ============LICENSE_START=======================================================
* ONAP - SO
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. 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.
* ============LICENSE_END=========================================================
*/
package org.openecomp.mso.apihandlerinfra.tenantisolation;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.spi.ResteasyUriInfo;
import org.junit.Ignore;
import org.junit.Test;
import org.openecomp.mso.requestsdb.InfraActiveRequests;
import org.openecomp.mso.requestsdb.RequestsDatabase;
public class CloudResourcesOrchestrationTest {
private String requestJSON = "{\"requestDetails\":{\"requestInfo\":{\"source\":\"VID\",\"requestorId\":\"zz9999\" } } }";
@Test
public void testUnlockFailObjectMapping() {
CloudResourcesOrchestration cor = new CloudResourcesOrchestration();
Response response = cor.unlockOrchestrationRequest(null, null, null);
String body = response.getEntity().toString();
assertTrue(body.contains("Mapping of request to JSON object failed."));
assertEquals(400, response.getStatus());
}
@Test
public void testUnlockFailObjectMapping2() {
CloudResourcesOrchestration cor = new CloudResourcesOrchestration();
Response response = cor.unlockOrchestrationRequest(null, "requestId", null);
String body = response.getEntity().toString();
assertTrue(body.contains("Mapping of request to JSON object failed."));
assertEquals(400, response.getStatus());
}
@Test
public void testParseOrchestrationError1() {
String requestJSON = "{\"requestDetails\": null }";
CloudResourcesOrchestration cor = new CloudResourcesOrchestration();
Response response = cor.unlockOrchestrationRequest(requestJSON, "requestId", null);
String body = response.getEntity().toString();
assertTrue(body.contains("Error parsing request."));
assertEquals(400, response.getStatus());
}
@Test
public void testParseOrchestrationError2() {
String requestJSON = "{\"requestDetails\":{\"requestInfo\":{\"source\":\"\",\"requestorId\":\"zz9999\" } } }";
CloudResourcesOrchestration cor = new CloudResourcesOrchestration();
Response response = cor.unlockOrchestrationRequest(requestJSON, "requestId", null);
String body = response.getEntity().toString();
assertTrue(body.contains("Error parsing request."));
assertEquals(400, response.getStatus());
}
@Test
public void testParseOrchestrationError3() {
String requestJSON = "{\"requestDetails\":{\"requestInfo\":{\"source\":\"VID\",\"requestorId\":\"\" } } }";
CloudResourcesOrchestration cor = new CloudResourcesOrchestration();
Response response = cor.unlockOrchestrationRequest(requestJSON, "requestId", null);
String body = response.getEntity().toString();
assertTrue(body.contains("Error parsing request."));
assertEquals(400, response.getStatus());
}
@Test
public void testGetInfraActiveRequestNull() {
CloudResourcesOrchestration cor = new CloudResourcesOrchestration();
RequestsDatabase reqDB = mock(RequestsDatabase.class);
cor.setRequestsDB(reqDB);
when(reqDB.getRequestFromInfraActive("requestId")).thenReturn(null);
Response response = cor.unlockOrchestrationRequest(requestJSON, "requestId", null);
String body = response.getEntity().toString();
assertTrue(body.contains("Orchestration RequestId requestId is not found in DB"));
assertEquals(404, response.getStatus());
}
@Test
public void testUnlockError() {
InfraActiveRequests iar = new InfraActiveRequests();
iar.setRequestId("requestId");
iar.setRequestScope("requestScope");
iar.setRequestType("requestType");
iar.setOperationalEnvId("operationalEnvironmentId");
iar.setOperationalEnvName("operationalEnvName");
iar.setRequestorId("ma920e");
iar.setRequestBody("");
iar.setRequestStatus("IN_PROGRESS");
CloudResourcesOrchestration cor = new CloudResourcesOrchestration();
RequestsDatabase reqDB = mock(RequestsDatabase.class);
cor.setRequestsDB(reqDB);
when(reqDB.getRequestFromInfraActive("requestId")).thenReturn(iar);
when(reqDB.updateInfraStatus("requestId", "UNLOCKED", "APIH")).thenReturn(1);
Response response = cor.unlockOrchestrationRequest(requestJSON, "requestId", null);
assertEquals(404, response.getStatus());
}
@Test
public void testUnlock() throws ParseException {
InfraActiveRequests iar = new InfraActiveRequests();
iar.setRequestId("requestId");
iar.setRequestScope("requestScope");
iar.setRequestType("requestType");
iar.setOperationalEnvId("operationalEnvironmentId");
iar.setOperationalEnvName("operationalEnvName");
iar.setRequestorId("ma920e");
iar.setRequestBody("");
iar.setRequestStatus("IN_PROGRESS");
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("23/09/2007");
long time = date.getTime();
iar.setStartTime(new Timestamp(time));
CloudResourcesOrchestration cor = new CloudResourcesOrchestration();
RequestsDatabase reqDB = mock(RequestsDatabase.class);
cor.setRequestsDB(reqDB);
when(reqDB.getRequestFromInfraActive("requestId")).thenReturn(iar);
when(reqDB.updateInfraStatus("requestId", "UNLOCKED", "APIH")).thenReturn(1);
Response response = cor.unlockOrchestrationRequest(requestJSON, "requestId", null);
assertEquals(204, response.getStatus());
}
@Test
public void testUnlockComplete() throws ParseException {
InfraActiveRequests iar = new InfraActiveRequests();
iar.setRequestId("requestId");
iar.setRequestScope("requestScope");
iar.setRequestType("requestType");
iar.setOperationalEnvId("operationalEnvironmentId");
iar.setOperationalEnvName("operationalEnvName");
iar.setRequestorId("ma920e");
iar.setRequestBody("");
iar.setRequestStatus("COMPLETE");
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("23/09/2007");
long time = date.getTime();
iar.setStartTime(new Timestamp(time));
CloudResourcesOrchestration cor = new CloudResourcesOrchestration();
RequestsDatabase reqDB = mock(RequestsDatabase.class);
cor.setRequestsDB(reqDB);
when(reqDB.getRequestFromInfraActive("requestId")).thenReturn(iar);
when(reqDB.updateInfraStatus("requestId", "UNLOCKED", "APIH")).thenReturn(1);
Response response = cor.unlockOrchestrationRequest(requestJSON, "requestId", null);
String body = response.getEntity().toString();
assertTrue(body.contains("Orchestration RequestId requestId has a status of COMPLETE and can not be unlocked"));
assertEquals(400, response.getStatus());
}
@Test
public void testGetOperationalEnvFilter() {
ResteasyUriInfo uriInfo = new ResteasyUriInfo("", "requestId=89c56827-1c78-4827-bc4d-6afcdb37a51f", "");
CloudResourcesOrchestration cor = new CloudResourcesOrchestration();
RequestsDatabase reqDB = mock(RequestsDatabase.class);
cor.setRequestsDB(reqDB);
when(reqDB.getRequestFromInfraActive("89c56827-1c78-4827-bc4d-6afcdb37a51f")).thenReturn(null);
Response response = cor.getOperationEnvironmentStatusFilter(uriInfo, null);
String body = response.getEntity().toString();
assertTrue(body.contains("Orchestration RequestId 89c56827-1c78-4827-bc4d-6afcdb37a51f is not found in DB"));
assertEquals(204, response.getStatus());
}
@Test
public void testGetOperationalEnvFilterException() {
ResteasyUriInfo uriInfo = new ResteasyUriInfo("", "requestId=89c56827-1c78-4827-bc4d-6afcdb37a51f", "");
CloudResourcesOrchestration cor = new CloudResourcesOrchestration();
Response response = cor.getOperationEnvironmentStatusFilter(uriInfo, null);
assertEquals(404, response.getStatus());
}
@Test
public void testGetOperationalEnvSuccess() throws ParseException {
InfraActiveRequests iar = new InfraActiveRequests();
iar.setRequestId("requestId");
iar.setRequestScope("requestScope");
iar.setRequestType("requestType");
iar.setOperationalEnvId("operationalEnvironmentId");
iar.setOperationalEnvName("operationalEnvName");
iar.setRequestorId("ma920e");
iar.setRequestBody("");
iar.setRequestStatus("COMPLETE");
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("23/09/2007");
long time = date.getTime();
iar.setStartTime(new Timestamp(time));
ResteasyUriInfo uriInfo = new ResteasyUriInfo("", "requestId=89c56827-1c78-4827-bc4d-6afcdb37a51f", "");
CloudResourcesOrchestration cor = new CloudResourcesOrchestration();
RequestsDatabase reqDB = mock(RequestsDatabase.class);
cor.setRequestsDB(reqDB);
when(reqDB.getRequestFromInfraActive("89c56827-1c78-4827-bc4d-6afcdb37a51f")).thenReturn(iar);
Response response = cor.getOperationEnvironmentStatusFilter(uriInfo, null);
assertEquals(200, response.getStatus());
}
@Test
public void testGetOperationalEnvFilterSuccess() throws ParseException {
InfraActiveRequests iar = new InfraActiveRequests();
iar.setRequestId("requestId");
iar.setRequestScope("requestScope");
iar.setRequestType("requestType");
iar.setOperationalEnvId("operationalEnvironmentId");
iar.setOperationalEnvName("operationalEnvName");
iar.setRequestorId("ma920e");
iar.setRequestBody("");
iar.setRequestStatus("COMPLETE");
iar.setStatusMessage("status Message");
iar.setProgress(20L);
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("23/09/2007");
long time = date.getTime();
iar.setStartTime(new Timestamp(time));
iar.setEndTime(new Timestamp(time));
List<InfraActiveRequests> requests = new ArrayList<>();
requests.add(iar);
Map<String, String> map = new HashMap<>();
map.put("operationalEnvironmentName", "myVnfOpEnv");
ResteasyUriInfo uriInfo = new ResteasyUriInfo("", "operationalEnvironmentName=myVnfOpEnv&requestorId=test", "");
CloudResourcesOrchestration cor = new CloudResourcesOrchestration();
RequestsDatabase reqDB = mock(RequestsDatabase.class);
cor.setRequestsDB(reqDB);
when(reqDB.getCloudOrchestrationFiltersFromInfraActive(map)).thenReturn(requests);
Response response = cor.getOperationEnvironmentStatusFilter(uriInfo, null);
assertEquals(200, response.getStatus());
}
@Ignore // 1802 merge
@Test
public void testGetOperationalEnvFilterException1() throws ParseException {
InfraActiveRequests iar = new InfraActiveRequests();
iar.setRequestId("requestId");
iar.setRequestScope("requestScope");
iar.setRequestType("requestType");
iar.setOperationalEnvId("operationalEnvironmentId");
iar.setOperationalEnvName("operationalEnvName");
iar.setRequestorId("ma920e");
iar.setRequestBody("");
iar.setRequestStatus("COMPLETE");
List<InfraActiveRequests> requests = new ArrayList<>();
requests.add(iar);
Map<String, String> map = new HashMap<>();
map.put("operationalEnvironmentName", "myVnfOpEnv");
ResteasyUriInfo uriInfo = new ResteasyUriInfo("", "filter=operationalEnvironmentName:EQUALS:myVnfOpEnv", "");
CloudResourcesOrchestration cor = new CloudResourcesOrchestration();
RequestsDatabase reqDB = mock(RequestsDatabase.class);
cor.setRequestsDB(reqDB);
when(reqDB.getCloudOrchestrationFiltersFromInfraActive(map)).thenReturn(requests);
Response response = cor.getOperationEnvironmentStatusFilter(uriInfo, null);
assertEquals(500, response.getStatus());
}
@Test
public void testGetOperationalEnvFilterException2() throws ParseException {
InfraActiveRequests iar = new InfraActiveRequests();
iar.setRequestId("requestId");
iar.setRequestScope("requestScope");
iar.setRequestType("requestType");
iar.setOperationalEnvId("operationalEnvId");
iar.setOperationalEnvName("operationalEnvName");
iar.setRequestorId("ma920e");
iar.setRequestBody("");
iar.setRequestStatus("COMPLETE");
List<InfraActiveRequests> requests = new ArrayList<>();
requests.add(iar);
Map<String, String> map = new HashMap<>();
map.put("operationalEnvironmentName", "myVnfOpEnv");
ResteasyUriInfo uriInfo = new ResteasyUriInfo("", "operationalEnvironmentName=", "");
CloudResourcesOrchestration cor = new CloudResourcesOrchestration();
RequestsDatabase reqDB = mock(RequestsDatabase.class);
cor.setRequestsDB(reqDB);
when(reqDB.getCloudOrchestrationFiltersFromInfraActive(map)).thenReturn(requests);
Response response = cor.getOperationEnvironmentStatusFilter(uriInfo, null);
assertEquals(500, response.getStatus());
assertTrue(response.getEntity().toString().contains("No valid operationalEnvironmentName value is specified"));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.