hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
7230da5b06d9e5b43bebd7e871ef430fc59bd417 | 354 | package com.ccnode.codegenerator.dialog.exception;
import org.jetbrains.annotations.NonNls;
/**
* Created by bruce.ge on 2016/12/25.
*/
public class TypeNotFoundException extends RuntimeException {
public TypeNotFoundException() {
super();
}
public TypeNotFoundException(@NonNls String message) {
super(message);
}
}
| 20.823529 | 61 | 0.706215 |
447f48604bedfc90a77a3b3d56dccc2909266669 | 163 | package ru.job4j.unblock;
public class OptimisticException extends RuntimeException {
public OptimisticException(String name) {
super(name);
}
}
| 18.111111 | 59 | 0.723926 |
15586c55d54d538d4fa67f9bb1dd184dd6815a77 | 1,396 | package io.yodo.crmdemo.servlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.sql.Connection;
import java.sql.DriverManager;
@WebServlet("/health")
public class HealthCheckServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String jdbcUrl = "jdbc:postgresql://postgres:5432/crmdemo?";
String driverClassName = "org.postgresql.Driver";
String userName = "postgres";
String password = "postgres";
try {
Class.forName(driverClassName);
Connection conn = DriverManager.getConnection(jdbcUrl, userName, password);
if (conn == null ) {
resp.setStatus(HttpURLConnection.HTTP_INTERNAL_ERROR);
resp.getWriter().append("DB connection failed");
} else {
resp.getWriter().append("DB connection successful");
}
}
catch(Exception ex) {
resp.setStatus(HttpURLConnection.HTTP_INTERNAL_ERROR);
resp.getWriter().append("DB connection failed, see console output for details");
ex.printStackTrace();
}
}
}
| 35.794872 | 95 | 0.673352 |
05046aadeffb7f26babf79fb909fa94bafcf1a34 | 2,438 | package com.sparkit.staf.core.runtime.interpreter.expression;
import com.sparkit.staf.core.ast.ExpressionOperator;
import com.sparkit.staf.core.ast.types.AbstractStafObject;
import com.sparkit.staf.core.ast.types.StafBoolean;
import com.sparkit.staf.core.runtime.interpreter.exceptions.InvalidExpressionOperationParams;
import org.springframework.stereotype.Component;
import javax.naming.OperationNotSupportedException;
@Component
public class BooleanExpressionEvaluator implements ExpressionEvaluator {
@Override
public AbstractStafObject evaluate(AbstractStafObject expressionLeftMember, AbstractStafObject expressionRightMember, ExpressionOperator operator)
throws InvalidExpressionOperationParams, OperationNotSupportedException {
if (expressionLeftMember.getValue() instanceof String || expressionRightMember.getValue() instanceof String) {
throw new InvalidExpressionOperationParams();
} else if (expressionLeftMember.getValue() instanceof Double || expressionRightMember.getValue() instanceof Double
|| expressionLeftMember.getValue() instanceof Integer || expressionRightMember.getValue() instanceof Integer) {
double expressionLeftMemberValue = Double.parseDouble(expressionLeftMember.getValue().toString());
double expressionRightMemberValue = Double.parseDouble(expressionRightMember.getValue().toString());
return new StafBoolean(compareNumbers(expressionLeftMemberValue, expressionRightMemberValue, operator));
}
throw new InvalidExpressionOperationParams();
}
private boolean compareNumbers(double expressionLeftMember, double expressionRightMember, ExpressionOperator operator) throws OperationNotSupportedException {
switch (operator) {
case EQUAL:
return expressionLeftMember == expressionRightMember;
case GT:
return expressionLeftMember > expressionRightMember;
case LT:
return expressionLeftMember < expressionRightMember;
case NE:
return expressionLeftMember != expressionRightMember;
case GTE:
return expressionLeftMember >= expressionRightMember;
case LTE:
return expressionLeftMember <= expressionRightMember;
default:
throw new OperationNotSupportedException();
}
}
}
| 53 | 162 | 0.736669 |
3301cc2769bf45c1993c91b557d849b9091a6218 | 568 | package edu.usc.ict.nl.dm.reward.possibilityGraph;
import edu.usc.ict.nl.bus.events.Event;
import edu.usc.ict.nl.dm.reward.DormantActions;
import edu.usc.ict.nl.dm.reward.model.DialogueOperator;
import edu.usc.ict.nl.kb.DialogueKB;
public class PossibleISForEvent extends PossibleIS {
public PossibleISForEvent(Event ev, DialogueOperator op, Type type, String name,
DialogueKB is, DormantActions dormantActions) {
super(op, type, name, is, dormantActions);
this.inputEvent=ev;
}
Event inputEvent=null;
public Event getInputEvent() {return inputEvent;}
} | 31.555556 | 81 | 0.785211 |
de78ba19959db82ade700d591ac44b0b6f0e972f | 924 | package app.mamac.albadiya;
import android.content.Context;
import com.google.gson.JsonObject;
/**
* Created by T on 21-11-2016.
*/
public class Packages {
public String id,title,title_ar,price,validity,messages,go_icon,timeline,social,description;
public Packages(JsonObject jsonObject, Context context){
id = jsonObject.get("id").getAsString();
title = jsonObject.get("title").getAsString();
title_ar = jsonObject.get("title_ar").getAsString();
price = jsonObject.get("price").getAsString();
validity = jsonObject.get("validity").getAsString();
messages = jsonObject.get("messages").getAsString();
go_icon = jsonObject.get("go_icon").getAsString();
timeline = jsonObject.get("timeline").getAsString();
social = jsonObject.get("social").getAsString();
description= jsonObject.get("description").getAsString();
}
}
| 26.4 | 97 | 0.67316 |
5349a6115bf0703caafe1846a932cec31392fa1d | 8,689 | package com.reactnativedigitalink;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.mlkit.vision.digitalink.DigitalInkRecognitionModelIdentifier;
import com.reactnativedigitalink.StrokeManager.DownloadedModelsChangedListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
public class DigitalInkModule extends ReactContextBaseJavaModule implements DownloadedModelsChangedListener {
@VisibleForTesting
public static final StrokeManager strokeManager = new StrokeManager();
private static final String DURATION_SHORT_KEY = "SHORT";
private static final String DURATION_LONG_KEY = "LONG";
private static final String TAG = "MLKDI.Activity";
private static final ImmutableMap<String, String> NON_TEXT_MODELS =
ImmutableMap.of(
"zxx-Zsym-x-autodraw",
"Autodraw",
"zxx-Zsye-x-emoji",
"Emoji",
"zxx-Zsym-x-shapes",
"Shapes");
private static ReactApplicationContext reactContext;
private final ArrayList<ModelLanguageContainer> mLanguagesList;
DigitalInkModule(ReactApplicationContext context) {
super(context);
reactContext = context;
strokeManager.setDownloadedModelsChangedListener(this);
strokeManager.setClearCurrentInkAfterRecognition(true);
strokeManager.setTriggerRecognitionAfterInput(false);
mLanguagesList = populateLanguages();
strokeManager.refreshDownloadedModelsStatus();
strokeManager.reset();
}
public static StrokeManager getStrokeManager() {
return strokeManager;
}
@Override
public String getName() {
return "DigitalInk";
}
@Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put(DURATION_SHORT_KEY, Toast.LENGTH_SHORT);
constants.put(DURATION_LONG_KEY, Toast.LENGTH_LONG);
return constants;
}
@ReactMethod
public void multiply(int x, int y, Promise promise) {
promise.resolve(x * y);
}
@ReactMethod
public void show(String message, int duration) {
Toast.makeText(getReactApplicationContext(), message, duration).show();
}
@ReactMethod
public void clear(Promise promise) {
getReactApplicationContext().getCurrentActivity().runOnUiThread(() -> {
DigitalInkView digitalInkView = DigitalInkViewManager.getViewInstance();
boolean isNull = digitalInkView == null;
promise.resolve("isNull: " + isNull + " " + R.id.digital_ink_view);
if (!isNull) digitalInkView.clear();
strokeManager.reset();
});
}
@ReactMethod
public void getLanguages(Promise promise) {
WritableArray languages = Arguments.createArray();
for (int i = 0; i < mLanguagesList.size(); i++) {
ModelLanguageContainer container = mLanguagesList.get(i);
WritableMap languageItem = Arguments.createMap();
languageItem.putString("label", container.label);
languageItem.putString("languageTag", container.languageTag);
languageItem.putBoolean("downloaded", ((Boolean) container.downloaded));
languages.pushMap(languageItem);
}
promise.resolve(languages);
}
@ReactMethod
public void setModel(String languageTag, Promise promise) {
promise.resolve(strokeManager.getModelManager().setModel(languageTag));
}
@ReactMethod
public void getDownloadedModelLanguages(Promise promise) {
strokeManager.getModelManager()
.getDownloadedModelLanguages()
.addOnSuccessListener(
downloadedLanguageTags -> {
WritableArray downloadedModelLanguages = Arguments.createArray();
Object[] languageTags = downloadedLanguageTags.toArray();
for (int i = 0; i < downloadedLanguageTags.size(); i++) {
downloadedModelLanguages.pushString(languageTags[i].toString());
}
promise.resolve(downloadedModelLanguages);
});
}
@ReactMethod
public void downloadModel(String languageTag, Promise promise) {
strokeManager.getModelManager().setModel(languageTag);
strokeManager.download(promise);
}
@ReactMethod
public Task<String> recognize(Promise promise) {
return strokeManager.recognize(promise);
}
@ReactMethod
public void loadLocalModels(Promise promise) {
LocalModelManager localModelManager = new LocalModelManager();
localModelManager.setContext(reactContext);
String result = localModelManager.loadModels();
promise.resolve(result);
}
@ReactMethod
public void deleteDownloadedModel(String languageTag, Promise promise) {
strokeManager.setActiveModel(languageTag);
strokeManager.deleteActiveModel(promise);
}
@Override
public void onDownloadedModelsChanged(Set<String> downloadedLanguageTags) {
for (int i = 0; i < mLanguagesList.size(); i++) {
ModelLanguageContainer container = mLanguagesList.get(i);
container.setDownloaded(downloadedLanguageTags.contains(container.languageTag));
}
}
private ArrayList<ModelLanguageContainer> populateLanguages() {
ArrayList<ModelLanguageContainer> languagesList = new ArrayList<>();
languagesList.add(ModelLanguageContainer.createLabelOnly("Select language"));
languagesList.add(ModelLanguageContainer.createLabelOnly("Non-text Models"));
// Manually add non-text models first
for (String languageTag : NON_TEXT_MODELS.keySet()) {
languagesList.add(
ModelLanguageContainer.createModelContainer(
NON_TEXT_MODELS.get(languageTag), languageTag));
}
languagesList.add(ModelLanguageContainer.createLabelOnly("Text Models"));
ImmutableSortedSet.Builder<ModelLanguageContainer> textModels =
ImmutableSortedSet.naturalOrder();
for (DigitalInkRecognitionModelIdentifier modelIdentifier :
DigitalInkRecognitionModelIdentifier.allModelIdentifiers()) {
if (NON_TEXT_MODELS.containsKey(modelIdentifier.getLanguageTag())) {
continue;
}
StringBuilder label = new StringBuilder();
label.append(new Locale(modelIdentifier.getLanguageSubtag()).getDisplayName());
if (modelIdentifier.getRegionSubtag() != null) {
label.append(" (").append(modelIdentifier.getRegionSubtag()).append(")");
}
if (modelIdentifier.getScriptSubtag() != null) {
label.append(", ").append(modelIdentifier.getScriptSubtag()).append(" Script");
}
textModels.add(
ModelLanguageContainer.createModelContainer(
label.toString(), modelIdentifier.getLanguageTag()));
}
languagesList.addAll(textModels.build());
return languagesList;
}
private static class ModelLanguageContainer implements Comparable<ModelLanguageContainer> {
private final String label;
@Nullable
private final String languageTag;
private boolean downloaded;
private ModelLanguageContainer(String label, @Nullable String languageTag) {
this.label = label;
this.languageTag = languageTag;
}
/**
* Populates and returns a real model identifier, with label, language tag and downloaded
* status.
*/
public static ModelLanguageContainer createModelContainer(String label, String languageTag) {
// Offset the actual language labels for better readability
return new ModelLanguageContainer(label, languageTag);
}
/**
* Populates and returns a label only, without a language tag.
*/
public static ModelLanguageContainer createLabelOnly(String label) {
return new ModelLanguageContainer(label, null);
}
public String getLanguageTag() {
return languageTag;
}
public void setDownloaded(boolean downloaded) {
this.downloaded = downloaded;
}
@NonNull
@Override
public String toString() {
if (languageTag == null) {
return label;
} else if (downloaded) {
return " [D] " + label;
} else {
return " " + label;
}
}
@Override
public int compareTo(ModelLanguageContainer o) {
return label.compareTo(o.label);
}
}
}
| 33.941406 | 109 | 0.729428 |
d42566c1c21c529654a9c0456347b0b136bff0e2 | 526 | package configurall.internal;
import org.objectweb.asm.Type;
/**
* @author Marco Romagnolo
*/
public class TypeValue {
private Type type;
private Object value;
private int access;
public TypeValue(int access, Type type, Object value) {
this.access = access;
this.type = type;
this.value = value;
}
public int getAccess() {
return access;
}
public Type getType() {
return type;
}
public Object getValue() {
return value;
}
}
| 15.939394 | 59 | 0.595057 |
ab4ea47198db52a5e94be73eef9d18f53784e9dc | 7,817 | package com.thunderwarn.thunderwarn;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.thunderwarn.thunderwarn.activities.MenuActivity;
import com.thunderwarn.thunderwarn.common.Log;
import com.thunderwarn.thunderwarn.common.SharedResources;
import com.thunderwarn.thunderwarn.common.configuration.ConfigurationManager;
import com.thunderwarn.thunderwarn.common.configuration.LayoutManager;
import com.thunderwarn.thunderwarn.manager.ForecastInterfaceManager;
import com.thunderwarn.thunderwarn.manager.UserLocationManager;
import com.thunderwarn.thunderwarn.manager.WeatherDataManager;
import com.thunderwarn.thunderwarn.scheduler.SendNotificationManager;
/**
* Set location on emulator:
* telnet localhost 5554
* Porto:
* geo fix -8.6189801 41.1611893
* Lousã:
* geo fix -8.251846 40.1167541
* Lisboa:
* geo fix -9.1462298 38.7155239
*
* Send reboot intent:
* cd /Users/ivofernandes/Library/Android/sdk/platform-tools/
* ./adb shell am broadcast -a android.intent.action.BOOT_COMPLETED
*/
public class MainActivity extends MenuActivity {
private static final String TAG = "MainActivity";
private SharedResources sharedResources = SharedResources.getInstance();
// Class to get the location of the user
private UserLocationManager userLocationManager = UserLocationManager.getInstance();
// Forecast User Interface
private ForecastInterfaceManager forecastInterfaceManager = ForecastInterfaceManager.getInstance();
private LayoutManager layoutManager = LayoutManager.getInstance();
private ConfigurationManager configurationManager = ConfigurationManager.getInstance();
private SendNotificationManager sendNotificationManager = SendNotificationManager.getInstance();
// Singleton
private static MainActivity instance = null;
private LinearLayout mainView;
public static MainActivity getInstance(){
return instance;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate START >");
super.onCreate(savedInstanceState);
init();
Log.d(TAG, "onCreate END <");
}
@Override
protected void onResume() {
Log.d(TAG, "onResume START >");
super.onResume();
SharedResources.getInstance().setContext(getApplicationContext());
start();
// Init activity
configureOrientation(getResources().getConfiguration());
// Analytics
try {
((AnalyticsApplication) getApplication()).startTracking();
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}catch(Exception e){
Log.e(TAG,"error initing ads and analytics",e);
}
Log.d(TAG, "onResume END <");
}
private void init() {
instance = this;
final SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
sharedResources.init(getApplicationContext());
FragmentManager fragmentManager = getSupportFragmentManager();
sharedResources.setFragmentManager(fragmentManager);
setContentView(R.layout.activity_main);
}
public void initLabels() {
TextView text3hours = (TextView) findViewById(R.id.text3hours);
TextView textDaily = (TextView) findViewById(R.id.textDaily);
text3hours.setTextColor(layoutManager.getSmoothForegroundColor());
textDaily.setTextColor(layoutManager.getSmoothForegroundColor());
}
private void start() {
initLocation();
initViews();
}
private void initViews() {
this.mainView = (LinearLayout) findViewById(R.id.mainView);
this.mainView.setBackgroundColor(layoutManager.getBackgroundColor());
}
/**
* Do the stuff related to start the user location manager
*/
private void initLocation() {
// Start Forecast UI manager
final LinearLayout forecastPanel = (LinearLayout) findViewById(R.id.forecastView);
forecastInterfaceManager.setForecastView(forecastPanel);
userLocationManager.getUserLocation(WeatherDataManager.WeatherRequestType.UPDATE_VIEWS);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
//No call for super(). Bug on API Level > 11.
}
public void loadingComplete(){
RelativeLayout image = (RelativeLayout) findViewById(R.id.loadingImage);
image.setVisibility(View.GONE);
// Init labels
initLabels();
}
public void setLastUpdate(String lastUpd,int color){
// show last update
TextView textView = (TextView) findViewById(R.id.lastUpd);
if(lastUpd != null) {
String lastUpdateDescription = sharedResources.resolveString(R.string.last_update);
textView.setText(lastUpdateDescription + " " + lastUpd);
textView.setVisibility(View.VISIBLE);
textView.setTextColor(color);
textView.setGravity(Gravity.CENTER);
}else{
textView.setVisibility(View.GONE);
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
configureOrientation(newConfig);
}
private void configureOrientation(Configuration config) {
LinearLayout forecastView = (LinearLayout) findViewById(R.id.forecastView);
FrameLayout id3hours = (FrameLayout) findViewById(R.id.id3hours);
FrameLayout idDaily = (FrameLayout) findViewById(R.id.idDaily);
// Checks the orientation of the screen
if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
forecastView.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams id3hoursLayoutParams = (LinearLayout.LayoutParams) id3hours.getLayoutParams();
id3hoursLayoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
id3hoursLayoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT;
id3hours.setLayoutParams(id3hoursLayoutParams);
LinearLayout.LayoutParams idDailyLayoutParams = (LinearLayout.LayoutParams) id3hours.getLayoutParams();
idDailyLayoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;
idDailyLayoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT;
idDaily.setLayoutParams(idDailyLayoutParams);
} else if (config.orientation == Configuration.ORIENTATION_PORTRAIT){
forecastView.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) id3hours.getLayoutParams();
params.height = LinearLayout.LayoutParams.WRAP_CONTENT;
params.width = LinearLayout.LayoutParams.MATCH_PARENT;
id3hours.setLayoutParams(params);
LinearLayout.LayoutParams idDailyLayoutParams = (LinearLayout.LayoutParams) id3hours.getLayoutParams();
idDailyLayoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT;
idDailyLayoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT;
idDaily.setLayoutParams(idDailyLayoutParams);
}
}
public void setAppTitle(String appTitle) {
if(appTitle != null && !appTitle.equals("")) {
setTitle(appTitle);
}
}
}
| 34.436123 | 116 | 0.711014 |
a04b9a81653eb29727c6ab12c2beca99d62f6257 | 13,939 | package uk.co.m4numbers.ludum.design;
/**
* Copyright 2015 M. D. Ball (m.d.ball2@ncl.ac.uk)
* <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.
*/
import org.jsfml.graphics.*;
import org.jsfml.system.Vector2f;
import uk.co.m4numbers.ludum.LudumMain;
import uk.co.m4numbers.ludum.logic.*;
import uk.co.m4numbers.ludum.utils.Pair;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
/**
* Class Name - Level
* Package - uk.co.m4numbers.ludum.design
* Desc of Class - ...
* Author(s) - M. D. Ball
* Last Mod: 22/08/2015
*/
public class Level {
private Map<Pair, Integer> levelMap;
private Map<Integer, Texture> textureMap;
public MonsterUI ui;
public Set<Sprite> floorSet;
public Set<Sprite> wallSet;
public Player player;
public Set<Enemy> enemySet;
public Pair startingPoint;
public Level(
Map<Pair, Integer> levelMap, Map<Integer, Texture> textureMap,
Pair charStart) {
this.levelMap = levelMap;
this.textureMap = textureMap;
this.startingPoint = charStart;
this.clear();
System.out.printf(
"There are %d entries in the level, and %d textures present\n",
levelMap.size(), textureMap.size()
);
//for (Map.Entry<Pair, Integer> e: levelMap.entrySet()) {
// System.out.printf("Item at location %d/%d is %d\n", e.getKey().x, e.getKey().y, e.getValue());
//}
for (Map.Entry<Integer, Texture> text : this.textureMap.entrySet()) {
System.out.printf("Texture at loc %d is %s\n", text.getKey(), text.getValue().toString());
}
}
public void clear() {
this.ui = new MonsterUI();
this.floorSet = new HashSet<Sprite>();
this.wallSet = new HashSet<Sprite>();
this.enemySet = new HashSet<Enemy>();
this.player = new Player(new Sprite(textureMap.get(5), new IntRect(0, 0, 8, 8)), startingPoint);
}
private IntRect getSpriteRotated(Pair location, Integer value) {
String rep = "";
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; ++j) {
if (location.x + i < 0 || location.x + i > 29 || location.y + j < 0 || location.y + j > 15) {
rep += Integer.toString(1);
} else {
Pair p = new Pair(location.x + i, location.y + j);
if (levelMap.containsKey(p))
rep += (levelMap.get(p).equals(value)) ? 1 : 0;
else
rep += Integer.toString(1);
}
}
}
System.out.printf("Square registered as %s\n", rep);
if (rep.equals("100010000") || rep.equals("001010000")
|| rep.equals("000010100") || rep.equals("000010001")
|| rep.equals("000010000") || rep.equals("101010101")
|| rep.equals("101010100") || rep.equals("001010101")
|| rep.equals("101010001") || rep.equals("100010101")
|| rep.equals("101010000") || rep.equals("001010100")
|| rep.equals("100010001") || rep.equals("000010101")
|| rep.equals("100010100") || rep.equals("001010001")) {
return new IntRect(13 * 16, 0, 16, 16);
} else if (rep.equals("010010000") || rep.equals("000110000")
|| rep.equals("000011000") || rep.equals("000010010")
|| rep.equals("111010000") || rep.equals("100110100")
|| rep.equals("001011001") || rep.equals("000010111")
|| rep.equals("110010000") || rep.equals("011010000")
|| rep.equals("001011000") || rep.equals("000011001")
|| rep.equals("000010011") || rep.equals("000010110")
|| rep.equals("000110100") || rep.equals("100110000")) {
return new IntRect(12 * 16, 0, 16, 16);
} else if (rep.equals("010010010") || rep.equals("000111000")) {
return new IntRect(11 * 16, 0, 16, 16);
} else if (rep.equals("011011011") || rep.equals("000111111")
|| rep.equals("110110110") || rep.equals("111111000")) {
return new IntRect(10*16, 0, 16, 16);
} else if (rep.equals("011011010") || rep.equals("000111011")
|| rep.equals("010110110") || rep.equals("110111000")) {
return new IntRect(9*16, 0, 16, 16);
} else if (rep.equals("010011010") || rep.equals("000111010")
|| rep.equals("010110010") || rep.equals("010111000")) {
return new IntRect(8*16, 0, 16, 16);
} else if (rep.equals("000011011") || rep.equals("000110110")
|| rep.equals("110110000") || rep.equals("011011000")) {
return new IntRect(7*16, 0, 16, 16);
} else if (rep.equals("000011010") || rep.equals("000110010")
|| rep.equals("010110000") || rep.equals("010011000")) {
return new IntRect(6*16, 0, 16, 16);
} else if (rep.equals("010111010")) {
return new IntRect(5*16, 0, 16, 16);
} else if (rep.equals("110111010") || rep.equals("011111010")
|| rep.equals("010111110") || rep.equals("010111011")) {
return new IntRect(4 * 16, 0, 16, 16);
} else if (rep.equals("010111111") || rep.equals("110111110")
|| rep.equals("111111010") || rep.equals("011111011")) {
return new IntRect(3*16, 0, 16, 16);
} else if (rep.equals("110111011") || rep.equals("011111110")) {
return new IntRect(2*16, 0, 16, 16);
} else if (rep.equals("011111111") || rep.equals("110111111")
|| rep.equals("111111011") || rep.equals("111111110")) {
return new IntRect(16, 0, 16, 16);
}
return new IntRect(0, 0, 16, 16);
}
public Sprite createSprite(EnemyEnums type) {
Sprite s = new Sprite(textureMap.get(type.texture), new IntRect(0, 0, 8, 8));
s.setScale(new Vector2f(LudumMain.scalingConst, LudumMain.scalingConst));
s.setOrigin(new Vector2f(
s.getLocalBounds().width / 2,
s.getLocalBounds().height / 2
));
Random rnd = new Random();
Pair p;
do {
int x = rnd.nextInt(30);
int y = rnd.nextInt(16);
p = new Pair(x, y);
} while (levelMap.get(p) != 0);
s.setPosition(new Vector2f(
p.x * (16 * LudumMain.scalingConst) + (16 * LudumMain.scalingConst) / 2,
p.y * (16 * LudumMain.scalingConst) + (16 * LudumMain.scalingConst) / 2
));
return s;
}
public void load() {
Sprite s;
for (Map.Entry<Pair, Integer> entry : levelMap.entrySet()) {
System.out.printf(
"Adding pos (%d, %d) as %d to spritemap\n",
entry.getKey().x, entry.getKey().y, entry.getValue()
);
s = new Sprite(textureMap.get(entry.getValue()), getSpriteRotated(entry.getKey(), entry.getValue()));
s.setScale(new Vector2f(LudumMain.scalingConst, LudumMain.scalingConst));
s.setPosition(new Vector2f(
entry.getKey().x * (16 * LudumMain.scalingConst),
entry.getKey().y * (16 * LudumMain.scalingConst)
));
if (entry.getValue() == 0) {
floorSet.add(s);
} else {
wallSet.add(s);
}
}
System.out.printf("All Environ sprites loaded...\n");
}
public void setAllEnemyTo(TerrorEnums te) {
for (Enemy e: enemySet) {
e.setTerrorLevel(te);
}
}
public Vector2f limitLine(Vertex[] vertexes, Vector2f initial) {
Vector2f ret = initial;
for (int i=0; i<vertexes.length; ++i) {
//System.out.printf("Vertex %d is being checked\n", i);
if (vertexes[i] != null) {
ret = vertexes[i].position;
for (Sprite wall : wallSet) {
if (wall.getGlobalBounds().contains(ret) || player.isColliding(ret)) {
//System.out.printf("Limit for line found at %f/%f\n", ret.x, ret.y);
return Vector2f.sub(ret, initial);
}
}
}
}
return Vector2f.sub(ret, initial);
}
public void nextFrame(Sprite actor, Integer start) {
this.nextFrame(actor, start, actor.getTexture().getSize().x/8);
}
public void nextFrame(Sprite actor, Integer start, Integer end) {
IntRect planned = new IntRect(
actor.getTextureRect().left + 8, actor.getTextureRect().top,
actor.getTextureRect().width, actor.getTextureRect().height
);
if (planned.left >= end * 8 || actor.getTextureRect().left < start*8) {
actor.setTextureRect(new IntRect(
start*8, 0, actor.getTextureRect().width,
actor.getTextureRect().height)
);
} else {
actor.setTextureRect(planned);
}
}
public void stopFrame(Sprite actor) {
actor.setTextureRect(new IntRect(0, 0, 8, 8));
}
public Vector2f processMove(Sprite actor, float horMov, float verMov) {
Vector2f position = new Vector2f(actor.getGlobalBounds().left, actor.getGlobalBounds().top);
Vector2f planned = Vector2f.add(position, new Vector2f(horMov, verMov));
Vector2f plannedHTL = Vector2f.add(position, new Vector2f(horMov, 0));
Vector2f plannedHTR = Vector2f.add(plannedHTL, new Vector2f(actor.getGlobalBounds().width, 0));
Vector2f plannedHBL = Vector2f.add(plannedHTL, new Vector2f(0, actor.getGlobalBounds().height));
Vector2f plannedHBR = Vector2f.add(plannedHTR, new Vector2f(0, actor.getGlobalBounds().height));
Vector2f plannedVTL = Vector2f.add(position, new Vector2f(0, verMov));
Vector2f plannedVTR = Vector2f.add(plannedVTL, new Vector2f(actor.getGlobalBounds().width, 0));
Vector2f plannedVBL = Vector2f.add(plannedVTL, new Vector2f(0, actor.getGlobalBounds().height));
Vector2f plannedVBR = Vector2f.add(plannedVTR, new Vector2f(0, actor.getGlobalBounds().height));
boolean blockHor = false;
boolean blockVer = false;
for (Sprite wall : LudumMain.currentLevel.wallSet) {
blockHor = blockHor || (wall.getGlobalBounds().contains(plannedHTL) || wall.getGlobalBounds().contains(plannedHTR)
|| wall.getGlobalBounds().contains(plannedHBL) || wall.getGlobalBounds().contains(plannedHBR));
blockVer = blockVer || (wall.getGlobalBounds().contains(plannedVTL) || wall.getGlobalBounds().contains(plannedVTR)
|| wall.getGlobalBounds().contains(plannedVBL) || wall.getGlobalBounds().contains(plannedVBR));
}
Vector2f globalTL = Vector2f.sub(
new Vector2f(LudumMain.window.getSize().x, LudumMain.window.getSize().y),
new Vector2f(planned.x, planned.y)
);
Vector2f globalTR = Vector2f.add(globalTL, new Vector2f(actor.getGlobalBounds().width, 0));
Vector2f globalBL = Vector2f.add(plannedHTL, new Vector2f(0, actor.getGlobalBounds().height));
Vector2f globalBR = Vector2f.add(plannedHTR, new Vector2f(0, actor.getGlobalBounds().height));
if (globalTL.x < 0 || globalTL.x > LudumMain.window.getSize().x
|| globalTR.x < 0 || globalTR.x > LudumMain.window.getSize().x
|| globalBL.x < 0 || globalBL.x > LudumMain.window.getSize().x
|| globalBR.x < 0 || globalBR.x > LudumMain.window.getSize().x)
blockHor = true;
if (globalTL.y < 0 || globalTL.y > LudumMain.window.getSize().y
|| globalTR.y < 0 || globalTR.y > LudumMain.window.getSize().y
|| globalBL.y < 0 || globalBL.y > LudumMain.window.getSize().y
|| globalBR.y < 0 || globalBR.y > LudumMain.window.getSize().y)
blockVer = true;
return new Vector2f((blockHor) ? 0 : horMov, (blockVer) ? 0 : verMov);
}
public void render() {
for (Sprite s: floorSet) {
LudumMain.window.draw(s);
}
for (Sprite s: wallSet) {
LudumMain.window.draw(s);
}
ui.draw(LudumMain.window);
for (Enemy e: enemySet) {
e.checkSeen(player.getCurrentBox());
e.isTouching(player.getCurrentBox());
e.draw(LudumMain.window);
}
if (player != null) {
player.draw(LudumMain.window);
}
}
public void killEnemy(Set<Enemy> e) {
for (Enemy f: e)
enemySet.remove(f);
}
private void spawnEnemy(int count, EnemyEnums type) {
try {
for (int i=0; i<count; ++i) {
enemySet.add(
(Enemy) type.reflector.getConstructor(Sprite.class).newInstance(createSprite(type))
);
}
} catch (Exception e) {
}
}
public void releaseEnemies(Integer key) {
//spawnEnemy( key / 10, EnemyEnums.EXTERMINATOR);
spawnEnemy(key / 3, EnemyEnums.SOILDIER);
spawnEnemy(key % 3, EnemyEnums.TOURIST);
}
}
| 40.286127 | 126 | 0.56367 |
684759a4fdf538720a2cbffe9eee2fa6fed548c4 | 696 | package com.dpgrandslam.stockdataservice.adapter.repository.mapper;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;
public class ExpirationDateResultSetExtractor implements ResultSetExtractor<Set<LocalDate>> {
@Override
public Set<LocalDate> extractData(ResultSet rs) throws SQLException, DataAccessException {
Set<LocalDate> dates = new HashSet<>();
while (rs.next()) {
dates.add(rs.getDate("expiration").toLocalDate());
}
return dates;
}
}
| 30.26087 | 94 | 0.74569 |
d551bd4a31c89bcf6fb27ab7227bbbb1b042af54 | 969 | package ml.mcos.servermonitor.config;
import java.util.HashMap;
import java.util.List;
public class Config {
public static String language;
public static String dateFormat;
public static String lineSeparator;
public static boolean realTimeSave;
public static boolean zipOldLog;
public static int delOldLog;
public static boolean checkUpdate;
public static HashMap<String, Boolean> playerChat = new HashMap<>();
public static HashMap<String, Boolean> playerCommand = new HashMap<>();
public static HashMap<String, Boolean> playerGameModeChange = new HashMap<>();
public static boolean opChange;
public static boolean joinAndLeave;
public static List<String> whitelist;
public static boolean commandAlert;
public static List<String> commandWhiteList;
public static boolean cancel;
public static int handleMethod;
public static HashMap<String, List<String>> handleMethodConfig = new HashMap<>();
}
| 37.269231 | 85 | 0.75129 |
e2c41f077b5fb03e16f1fd6e83bef6ad1adea623 | 4,412 | package com.condingblocks.multicopy.Adapters;
import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Pair;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.condingblocks.multicopy.R;
import com.condingblocks.multicopy.Utils.Constants;
import com.condingblocks.multicopy.model.NotesModel;
import com.condingblocks.multicopy.views.Activities.NoteEditActvity;
import com.google.gson.Gson;
import java.util.ArrayList;
import io.realm.RealmResults;
/**
* Created by rishabhkhanna on 14/05/17.
*/
public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.NotesViewHolder>{
public ArrayList<NotesModel> notesModelArrayList;
private Context context;
//contexttual Action Bar
private SparseBooleanArray mSelectedItems;
Gson gson = new Gson();
public static final String TAG = "NotesAdapter";
public NotesAdapter(ArrayList<NotesModel> notesModelArrayList, Context context) {
this.notesModelArrayList = notesModelArrayList;
this.context = context;
mSelectedItems = new SparseBooleanArray();
}
@Override
public NotesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = li.inflate(R.layout.notes_layout,parent,false);
NotesViewHolder holder = new NotesViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(final NotesViewHolder holder, final int position) {
final NotesModel thisNote = notesModelArrayList.get(position);
holder.tvNote.setText(thisNote.getNote());
holder.tvTimeStamp.setText(thisNote.getCreatedAt());
holder.noteCardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(context, NoteEditActvity.class);
i.putExtra(Constants.NOTES_EDIT_TEXT, thisNote.getNote());
i.putExtra(Constants.NOTES_EDIT_POSITION,position);
ActivityOptions activityOptions = ActivityOptions.makeSceneTransitionAnimation((Activity) context, Pair.create((View)holder.tvNote,"notes_text"));
((Activity)context).startActivityForResult(i,Constants.NOTES_RESULT);
}
});
holder.itemView.setBackgroundColor(mSelectedItems.get(position)? context.getResources().getColor(R.color.ColorPrimaryLight): Color.TRANSPARENT);
}
@Override
public int getItemCount() {
return notesModelArrayList.size();
}
public class NotesViewHolder extends RecyclerView.ViewHolder{
TextView tvNote;
TextView tvTimeStamp;
CardView noteCardView;
View selectedOverlay;
public NotesViewHolder(View itemView) {
super(itemView);
tvNote = (TextView) itemView.findViewById(R.id.tvNoteText);
tvTimeStamp = (TextView) itemView.findViewById(R.id.tvCreatedAt);
noteCardView = (CardView) itemView.findViewById(R.id.notesCardView);
selectedOverlay = itemView.findViewById(R.id.selected_overlay);
}
}
//delete items from notes function
public void delteNotes(){
}
//methods required to do selections in android
//toggle state from selected or deselected
public void toggleSelection(int position){
selectView(position,!mSelectedItems.get(position));
}
//remove selected items
public void removeSelection(){
mSelectedItems = new SparseBooleanArray();
notifyDataSetChanged();
}
//
public void selectView(int position,boolean value){
if (value)
mSelectedItems.put(position,value);
else
mSelectedItems.delete(position);
notifyDataSetChanged();
}
//get total selected items
public int getSelectedCount(){
return mSelectedItems.size();
}
//return all selected ids
public SparseBooleanArray getmSelectedItems(){
return mSelectedItems;
}
}
| 33.424242 | 162 | 0.709882 |
58ba135b471bb57290acaadcdcfff7e55249e9d0 | 813 | package util;
import edu.uta.cse.fireeye.common.Parameter;
import java.util.ArrayList;
public class TWayCoverage {
private ArrayList<Parameter> paramList;
private float coverage;
public TWayCoverage(ArrayList<Parameter> paramList, float coverage) {
this.paramList = paramList;
this.coverage = coverage;
}
public ArrayList<Parameter> getParamList() {
return paramList;
}
public float getCoverage() {
return coverage;
}
@Override
public String toString() {
String paramList = "";
for(Parameter p : this.paramList) {
paramList += p.getName() + ",";
}
return "TWayCoverage{" +
"parameter=" + paramList +
" coverage=" + coverage +
'}';
}
}
| 20.846154 | 73 | 0.581796 |
0404a9c17b099fb6867ad18bb632684b3fde6043 | 585 | package it.unibz.inf.ontop.model.term;
import it.unibz.inf.ontop.model.type.TermType;
import it.unibz.inf.ontop.model.type.TermTypeInference;
import java.util.Optional;
public interface NonNullConstant extends Constant {
TermType getType();
@Override
default Optional<TermType> getOptionalType() {
return Optional.of(getType());
}
@Override
default boolean isNull() {
return false;
}
@Override
default Optional<TermTypeInference> inferType() {
return Optional.of(TermTypeInference.declareTermType(getType()));
}
}
| 21.666667 | 73 | 0.700855 |
04d420bd2713f5bb78b0c3d4ec08b671d932c8bd | 2,632 | package com.robmelfi.rcraspi.service.impl;
import com.robmelfi.rcraspi.domain.Humidity;
import com.robmelfi.rcraspi.domain.Temperature;
import com.robmelfi.rcraspi.repository.HumidityRepository;
import com.robmelfi.rcraspi.repository.TemperatureRepository;
import com.robmelfi.rcraspi.sensor.dto.DHT11DataDTO;
import com.robmelfi.rcraspi.service.DHT11Service;
import io.github.jhipster.config.JHipsterConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Random;
@Service
@Transactional
@Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)
public class DHT11ServiceDevImpl implements DHT11Service {
final float c_min = -20;
final float c_max = 50;
final float h_min = 0;
final float h_max = 50;
private final Logger log = LoggerFactory.getLogger(DHT11ServiceDevImpl.class);
private final TemperatureRepository temperatureRepository;
private final HumidityRepository humidityRepository;
public DHT11ServiceDevImpl(TemperatureRepository temperatureRepository, HumidityRepository humidityRepository) {
this.temperatureRepository = temperatureRepository;
this.humidityRepository = humidityRepository;
}
@Override
public DHT11DataDTO readTempHum(int pin) {
return getMockDHT11DataDTO();
}
@Override
public void storeTempHum(int pin) {
DHT11DataDTO result = this.getMockDHT11DataDTO();
ZonedDateTime timestamp = ZonedDateTime.now(ZoneId.systemDefault());
Temperature temperature = new Temperature()
.value(result.getTemperature())
.timestamp(timestamp);
Humidity humidity = new Humidity()
.value(result.getHumidity())
.timestamp(timestamp);
log.debug("temperature {} - humidity {}", temperature, humidity);
this.temperatureRepository.save(temperature);
this.humidityRepository.save(humidity);
}
private DHT11DataDTO getMockDHT11DataDTO() {
Random r = new Random();
DHT11DataDTO dht11DataDTO = new DHT11DataDTO();
dht11DataDTO.setTemperature(getMockTemp(r));
dht11DataDTO.setHumidity(getMockHum(r));
return dht11DataDTO;
}
private float getMockTemp(Random r) {
return c_min + r.nextFloat() * (c_max - c_min);
}
private float getMockHum(Random r) {
return h_min + r.nextFloat() * (h_max - h_min);
}
}
| 33.74359 | 116 | 0.735182 |
4aea0a5a780186f6bb489b6255dd125a55a41603 | 5,121 | package com.ydds.modulefirst.activity;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.ydds.libcommon.base.BaseActivity;
import com.ydds.librouter.ServiceCallback;
import com.ydds.librouter.consts.MFirstConst;
import com.ydds.librouter.consts.MSecondConst;
import com.ydds.librouter.services.ISecondService;
import com.ydds.modulefirst.R;
import com.ydds.modulefirst.bean.Person;
/**
* Description: TODO (用一句话描述该文件做什么)
* author: Administrator
* version: V1.0
* Date: 2019/4/29
*/
@Route(path = MFirstConst.MF_ACTIVITY_FIRST, name = "module first first")
public class FirstActivity extends BaseActivity implements View.OnClickListener {
@Autowired
public String from;
@Autowired(name = "name")
public String mName;
@Autowired
public Person person;
@Autowired
public ISecondService secondService;
private Button mBtGo;
private Button mBtGoResult;
private Button mBtDo;
private Button mBtDoAsync;
private Button mBtSet;
private Button mBtCheckSet;
private Button mBtDegrade;
private TextView mTv;
@Override
public int getLayoutID() {
return R.layout.activity_first;
}
@Override
public void init() {
ARouter.getInstance().inject(this);
}
@Override
public void initView() {
mTv = findViewById(R.id.tv);
mBtGo = findViewById(R.id.bt_go);
mBtGoResult = findViewById(R.id.bt_go_result);
mBtDo = findViewById(R.id.bt_do);
mBtDoAsync = findViewById(R.id.bt_do_async);
mBtSet = findViewById(R.id.bt_set);
mBtCheckSet = findViewById(R.id.bt_check_set);
mBtDegrade = findViewById(R.id.bt_degrade);
}
@Override
public void initListener() {
mBtGo.setOnClickListener(this);
mBtGoResult.setOnClickListener(this);
mBtDo.setOnClickListener(this);
mBtDoAsync.setOnClickListener(this);
mBtSet.setOnClickListener(this);
mBtCheckSet.setOnClickListener(this);
mBtDegrade.setOnClickListener(this);
}
@Override
public void initData() {
mTv.setText("name:" + mName + " from:" + from);
}
@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.bt_go) {
startSecond();
} else if (id == R.id.bt_go_result) {
startSecondForResult();
} else if (id == R.id.bt_do) {
doSecond();
} else if (id == R.id.bt_do_async) {
doSecondAsync();
} else if (id == R.id.bt_set) {
setSecond();
} else if (id == R.id.bt_check_set) {
getSetSecond();
} else if (id == R.id.bt_degrade) {
testDegrade();
}
}
private void testDegrade() {
ARouter.getInstance().build("/ModuleFirst/xxx").navigation(this);
}
private void getSetSecond() {
String str = secondService.getSetInfo();
mTv.setText(str);
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
private void setSecond() {
secondService.setSecondInfo("还能不能玩了!!!");
}
private void doSecondAsync() {
secondService.getSecondInfo(new ServiceCallback<Person>() {
@Override
public void onSuccess(Person person) {
mTv.setText(person.name + " 来自:" + person.from);
Toast.makeText(FirstActivity.this, mTv.getText(), Toast.LENGTH_LONG).show();
}
@Override
public void onFail(String msg) {
}
}, Person.class);
}
private void doSecond() {
if (secondService != null) {
mTv.setText(secondService.getSecondInfo());
}
}
private void startSecondForResult() {
ARouter.getInstance()
.build(MSecondConst.MS_ACTIVITY_SECOND)
.withString("name", "张三")
.withString("from", "module first")
.navigation(FirstActivity.this, MSecondConst.MS_REQUEST_INFO);
}
private void startSecond() {
ARouter.getInstance()
.build(MSecondConst.MS_ACTIVITY_SECOND)
.withString("name", "张三")
.withString("from", "module first")
.navigation();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data == null) {
return;
}
if (resultCode == MSecondConst.MS_REQUEST_INFO) {
mTv.setText("result:" + data.getStringExtra("ms_second_info"));
}
}
@Override
protected void onDestroy() {
super.onDestroy();
secondService = null;
}
} | 28.769663 | 93 | 0.620191 |
2873e8655506d6725f110f5c94d5062927519602 | 18,785 |
package org.example.api.beans;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"CORS",
"publicAPI",
"privateAPI",
"cancelOrder",
"cancelOrders",
"createDepositAddress",
"createOrder",
"createMarketOrder",
"createLimitOrder",
"editOrder",
"fetchBalance",
"fetchBidsAsks",
"fetchClosedOrders",
"fetchCurrencies",
"fetchDepositAddress",
"fetchFundingFees",
"fetchL2OrderBook",
"fetchMarkets",
"fetchMyTrades",
"fetchOHLCV",
"fetchOpenOrders",
"fetchOrder",
"fetchOrderBook",
"fetchOrderBooks",
"fetchOrders",
"fetchTicker",
"fetchTickers",
"fetchTrades",
"fetchTradingFees",
"fetchTradingLimits",
"withdraw"
})
public class ExchangeHasCapabilities {
/**
*
* (Required)
*
*/
@JsonProperty("CORS")
private org.example.api.beans.ExchangeCapability cors;
/**
*
* (Required)
*
*/
@JsonProperty("publicAPI")
private org.example.api.beans.ExchangeCapability publicAPI;
/**
*
* (Required)
*
*/
@JsonProperty("privateAPI")
private org.example.api.beans.ExchangeCapability privateAPI;
/**
*
* (Required)
*
*/
@JsonProperty("cancelOrder")
private org.example.api.beans.ExchangeCapability cancelOrder;
/**
*
* (Required)
*
*/
@JsonProperty("cancelOrders")
private org.example.api.beans.ExchangeCapability cancelOrders;
/**
*
* (Required)
*
*/
@JsonProperty("createDepositAddress")
private org.example.api.beans.ExchangeCapability createDepositAddress;
/**
*
* (Required)
*
*/
@JsonProperty("createOrder")
private org.example.api.beans.ExchangeCapability createOrder;
/**
*
* (Required)
*
*/
@JsonProperty("createMarketOrder")
private org.example.api.beans.ExchangeCapability createMarketOrder;
/**
*
* (Required)
*
*/
@JsonProperty("createLimitOrder")
private org.example.api.beans.ExchangeCapability createLimitOrder;
/**
*
* (Required)
*
*/
@JsonProperty("editOrder")
private org.example.api.beans.ExchangeCapability editOrder;
/**
*
* (Required)
*
*/
@JsonProperty("fetchBalance")
private org.example.api.beans.ExchangeCapability fetchBalance;
/**
*
* (Required)
*
*/
@JsonProperty("fetchBidsAsks")
private org.example.api.beans.ExchangeCapability fetchBidsAsks;
/**
*
* (Required)
*
*/
@JsonProperty("fetchClosedOrders")
private org.example.api.beans.ExchangeCapability fetchClosedOrders;
/**
*
* (Required)
*
*/
@JsonProperty("fetchCurrencies")
private org.example.api.beans.ExchangeCapability fetchCurrencies;
/**
*
* (Required)
*
*/
@JsonProperty("fetchDepositAddress")
private org.example.api.beans.ExchangeCapability fetchDepositAddress;
/**
*
* (Required)
*
*/
@JsonProperty("fetchFundingFees")
private org.example.api.beans.ExchangeCapability fetchFundingFees;
/**
*
* (Required)
*
*/
@JsonProperty("fetchL2OrderBook")
private org.example.api.beans.ExchangeCapability fetchL2OrderBook;
/**
*
* (Required)
*
*/
@JsonProperty("fetchMarkets")
private org.example.api.beans.ExchangeCapability fetchMarkets;
/**
*
* (Required)
*
*/
@JsonProperty("fetchMyTrades")
private org.example.api.beans.ExchangeCapability fetchMyTrades;
/**
*
* (Required)
*
*/
@JsonProperty("fetchOHLCV")
private org.example.api.beans.ExchangeCapability fetchOHLCV;
/**
*
* (Required)
*
*/
@JsonProperty("fetchOpenOrders")
private org.example.api.beans.ExchangeCapability fetchOpenOrders;
/**
*
* (Required)
*
*/
@JsonProperty("fetchOrder")
private org.example.api.beans.ExchangeCapability fetchOrder;
/**
*
* (Required)
*
*/
@JsonProperty("fetchOrderBook")
private org.example.api.beans.ExchangeCapability fetchOrderBook;
/**
*
* (Required)
*
*/
@JsonProperty("fetchOrderBooks")
private org.example.api.beans.ExchangeCapability fetchOrderBooks;
/**
*
* (Required)
*
*/
@JsonProperty("fetchOrders")
private org.example.api.beans.ExchangeCapability fetchOrders;
/**
*
* (Required)
*
*/
@JsonProperty("fetchTicker")
private org.example.api.beans.ExchangeCapability fetchTicker;
/**
*
* (Required)
*
*/
@JsonProperty("fetchTickers")
private org.example.api.beans.ExchangeCapability fetchTickers;
/**
*
* (Required)
*
*/
@JsonProperty("fetchTrades")
private org.example.api.beans.ExchangeCapability fetchTrades;
/**
*
* (Required)
*
*/
@JsonProperty("fetchTradingFees")
private org.example.api.beans.ExchangeCapability fetchTradingFees;
/**
*
* (Required)
*
*/
@JsonProperty("fetchTradingLimits")
private org.example.api.beans.ExchangeCapability fetchTradingLimits;
/**
*
* (Required)
*
*/
@JsonProperty("withdraw")
private org.example.api.beans.ExchangeCapability withdraw;
/**
*
* (Required)
*
*/
@JsonProperty("CORS")
public org.example.api.beans.ExchangeCapability getCors() {
return cors;
}
/**
*
* (Required)
*
*/
@JsonProperty("CORS")
public void setCors(org.example.api.beans.ExchangeCapability cors) {
this.cors = cors;
}
/**
*
* (Required)
*
*/
@JsonProperty("publicAPI")
public org.example.api.beans.ExchangeCapability getPublicAPI() {
return publicAPI;
}
/**
*
* (Required)
*
*/
@JsonProperty("publicAPI")
public void setPublicAPI(org.example.api.beans.ExchangeCapability publicAPI) {
this.publicAPI = publicAPI;
}
/**
*
* (Required)
*
*/
@JsonProperty("privateAPI")
public org.example.api.beans.ExchangeCapability getPrivateAPI() {
return privateAPI;
}
/**
*
* (Required)
*
*/
@JsonProperty("privateAPI")
public void setPrivateAPI(org.example.api.beans.ExchangeCapability privateAPI) {
this.privateAPI = privateAPI;
}
/**
*
* (Required)
*
*/
@JsonProperty("cancelOrder")
public org.example.api.beans.ExchangeCapability getCancelOrder() {
return cancelOrder;
}
/**
*
* (Required)
*
*/
@JsonProperty("cancelOrder")
public void setCancelOrder(org.example.api.beans.ExchangeCapability cancelOrder) {
this.cancelOrder = cancelOrder;
}
/**
*
* (Required)
*
*/
@JsonProperty("cancelOrders")
public org.example.api.beans.ExchangeCapability getCancelOrders() {
return cancelOrders;
}
/**
*
* (Required)
*
*/
@JsonProperty("cancelOrders")
public void setCancelOrders(org.example.api.beans.ExchangeCapability cancelOrders) {
this.cancelOrders = cancelOrders;
}
/**
*
* (Required)
*
*/
@JsonProperty("createDepositAddress")
public org.example.api.beans.ExchangeCapability getCreateDepositAddress() {
return createDepositAddress;
}
/**
*
* (Required)
*
*/
@JsonProperty("createDepositAddress")
public void setCreateDepositAddress(org.example.api.beans.ExchangeCapability createDepositAddress) {
this.createDepositAddress = createDepositAddress;
}
/**
*
* (Required)
*
*/
@JsonProperty("createOrder")
public org.example.api.beans.ExchangeCapability getCreateOrder() {
return createOrder;
}
/**
*
* (Required)
*
*/
@JsonProperty("createOrder")
public void setCreateOrder(org.example.api.beans.ExchangeCapability createOrder) {
this.createOrder = createOrder;
}
/**
*
* (Required)
*
*/
@JsonProperty("createMarketOrder")
public org.example.api.beans.ExchangeCapability getCreateMarketOrder() {
return createMarketOrder;
}
/**
*
* (Required)
*
*/
@JsonProperty("createMarketOrder")
public void setCreateMarketOrder(org.example.api.beans.ExchangeCapability createMarketOrder) {
this.createMarketOrder = createMarketOrder;
}
/**
*
* (Required)
*
*/
@JsonProperty("createLimitOrder")
public org.example.api.beans.ExchangeCapability getCreateLimitOrder() {
return createLimitOrder;
}
/**
*
* (Required)
*
*/
@JsonProperty("createLimitOrder")
public void setCreateLimitOrder(org.example.api.beans.ExchangeCapability createLimitOrder) {
this.createLimitOrder = createLimitOrder;
}
/**
*
* (Required)
*
*/
@JsonProperty("editOrder")
public org.example.api.beans.ExchangeCapability getEditOrder() {
return editOrder;
}
/**
*
* (Required)
*
*/
@JsonProperty("editOrder")
public void setEditOrder(org.example.api.beans.ExchangeCapability editOrder) {
this.editOrder = editOrder;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchBalance")
public org.example.api.beans.ExchangeCapability getFetchBalance() {
return fetchBalance;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchBalance")
public void setFetchBalance(org.example.api.beans.ExchangeCapability fetchBalance) {
this.fetchBalance = fetchBalance;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchBidsAsks")
public org.example.api.beans.ExchangeCapability getFetchBidsAsks() {
return fetchBidsAsks;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchBidsAsks")
public void setFetchBidsAsks(org.example.api.beans.ExchangeCapability fetchBidsAsks) {
this.fetchBidsAsks = fetchBidsAsks;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchClosedOrders")
public org.example.api.beans.ExchangeCapability getFetchClosedOrders() {
return fetchClosedOrders;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchClosedOrders")
public void setFetchClosedOrders(org.example.api.beans.ExchangeCapability fetchClosedOrders) {
this.fetchClosedOrders = fetchClosedOrders;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchCurrencies")
public org.example.api.beans.ExchangeCapability getFetchCurrencies() {
return fetchCurrencies;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchCurrencies")
public void setFetchCurrencies(org.example.api.beans.ExchangeCapability fetchCurrencies) {
this.fetchCurrencies = fetchCurrencies;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchDepositAddress")
public org.example.api.beans.ExchangeCapability getFetchDepositAddress() {
return fetchDepositAddress;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchDepositAddress")
public void setFetchDepositAddress(org.example.api.beans.ExchangeCapability fetchDepositAddress) {
this.fetchDepositAddress = fetchDepositAddress;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchFundingFees")
public org.example.api.beans.ExchangeCapability getFetchFundingFees() {
return fetchFundingFees;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchFundingFees")
public void setFetchFundingFees(org.example.api.beans.ExchangeCapability fetchFundingFees) {
this.fetchFundingFees = fetchFundingFees;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchL2OrderBook")
public org.example.api.beans.ExchangeCapability getFetchL2OrderBook() {
return fetchL2OrderBook;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchL2OrderBook")
public void setFetchL2OrderBook(org.example.api.beans.ExchangeCapability fetchL2OrderBook) {
this.fetchL2OrderBook = fetchL2OrderBook;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchMarkets")
public org.example.api.beans.ExchangeCapability getFetchMarkets() {
return fetchMarkets;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchMarkets")
public void setFetchMarkets(org.example.api.beans.ExchangeCapability fetchMarkets) {
this.fetchMarkets = fetchMarkets;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchMyTrades")
public org.example.api.beans.ExchangeCapability getFetchMyTrades() {
return fetchMyTrades;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchMyTrades")
public void setFetchMyTrades(org.example.api.beans.ExchangeCapability fetchMyTrades) {
this.fetchMyTrades = fetchMyTrades;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchOHLCV")
public org.example.api.beans.ExchangeCapability getFetchOHLCV() {
return fetchOHLCV;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchOHLCV")
public void setFetchOHLCV(org.example.api.beans.ExchangeCapability fetchOHLCV) {
this.fetchOHLCV = fetchOHLCV;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchOpenOrders")
public org.example.api.beans.ExchangeCapability getFetchOpenOrders() {
return fetchOpenOrders;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchOpenOrders")
public void setFetchOpenOrders(org.example.api.beans.ExchangeCapability fetchOpenOrders) {
this.fetchOpenOrders = fetchOpenOrders;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchOrder")
public org.example.api.beans.ExchangeCapability getFetchOrder() {
return fetchOrder;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchOrder")
public void setFetchOrder(org.example.api.beans.ExchangeCapability fetchOrder) {
this.fetchOrder = fetchOrder;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchOrderBook")
public org.example.api.beans.ExchangeCapability getFetchOrderBook() {
return fetchOrderBook;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchOrderBook")
public void setFetchOrderBook(org.example.api.beans.ExchangeCapability fetchOrderBook) {
this.fetchOrderBook = fetchOrderBook;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchOrderBooks")
public org.example.api.beans.ExchangeCapability getFetchOrderBooks() {
return fetchOrderBooks;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchOrderBooks")
public void setFetchOrderBooks(org.example.api.beans.ExchangeCapability fetchOrderBooks) {
this.fetchOrderBooks = fetchOrderBooks;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchOrders")
public org.example.api.beans.ExchangeCapability getFetchOrders() {
return fetchOrders;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchOrders")
public void setFetchOrders(org.example.api.beans.ExchangeCapability fetchOrders) {
this.fetchOrders = fetchOrders;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchTicker")
public org.example.api.beans.ExchangeCapability getFetchTicker() {
return fetchTicker;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchTicker")
public void setFetchTicker(org.example.api.beans.ExchangeCapability fetchTicker) {
this.fetchTicker = fetchTicker;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchTickers")
public org.example.api.beans.ExchangeCapability getFetchTickers() {
return fetchTickers;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchTickers")
public void setFetchTickers(org.example.api.beans.ExchangeCapability fetchTickers) {
this.fetchTickers = fetchTickers;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchTrades")
public org.example.api.beans.ExchangeCapability getFetchTrades() {
return fetchTrades;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchTrades")
public void setFetchTrades(org.example.api.beans.ExchangeCapability fetchTrades) {
this.fetchTrades = fetchTrades;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchTradingFees")
public org.example.api.beans.ExchangeCapability getFetchTradingFees() {
return fetchTradingFees;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchTradingFees")
public void setFetchTradingFees(org.example.api.beans.ExchangeCapability fetchTradingFees) {
this.fetchTradingFees = fetchTradingFees;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchTradingLimits")
public org.example.api.beans.ExchangeCapability getFetchTradingLimits() {
return fetchTradingLimits;
}
/**
*
* (Required)
*
*/
@JsonProperty("fetchTradingLimits")
public void setFetchTradingLimits(org.example.api.beans.ExchangeCapability fetchTradingLimits) {
this.fetchTradingLimits = fetchTradingLimits;
}
/**
*
* (Required)
*
*/
@JsonProperty("withdraw")
public org.example.api.beans.ExchangeCapability getWithdraw() {
return withdraw;
}
/**
*
* (Required)
*
*/
@JsonProperty("withdraw")
public void setWithdraw(org.example.api.beans.ExchangeCapability withdraw) {
this.withdraw = withdraw;
}
}
| 21.274066 | 104 | 0.591323 |
441f02877d8b42f15f3c36e0178b42ba5ee7fc3f | 1,141 | package com.blackchopper.demo_onlite;
import com.hacknife.onlite.annotation.AutoInc;
import com.hacknife.onlite.annotation.Column;
import com.hacknife.onlite.annotation.Table;
import com.hacknife.onlite.annotation.Unique;
import com.hacknife.onlite.annotation.Version;
/**
* author : Hacknife
* e-mail : 4884280@qq.com
* github : http://github.com/hacknife
* project : OnLite
*/
@Table("user_info")
@Version(1)
public class User {
@Column(name = "_id")
@AutoInc
Integer id;
@Column(name = "name")
String name;
@Unique
@Column(name = "_pwd")
String pwd;
@Column(name = "_img")
String img;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
}
| 17.828125 | 46 | 0.606486 |
e55254eec95a84741df36d3a57d6a551aef2ac55 | 1,905 | package cca.topology;
import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichSpout;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import cca.Order;
import com.google.gson.Gson;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Spout extends BaseRichSpout {
private SpoutOutputCollector spoutOutputCollector;
private List<Order> orderList;
public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {
outputFieldsDeclarer.declare(new Fields("order"));
}
private List<Order> convertJsonList(List<String> jsonList) {
List<Order> orders = new ArrayList<>();
Gson gson = new Gson();
for (String json : jsonList) {
Order order = gson.fromJson(json, Order.class);
orders.add(order);
}
return orders;
}
public void open(Map map, TopologyContext topologyContext, SpoutOutputCollector spoutOutputCollector) {
this.spoutOutputCollector = spoutOutputCollector;
try {
List<String> jsonList = IOUtils.readLines(ClassLoader.getSystemResourceAsStream("orders.txt"),
Charset.defaultCharset());
orderList = convertJsonList(jsonList);
} catch (IOException io) {
throw new RuntimeException(io);
}
}
public void nextTuple() {
for (Order order : orderList) {
spoutOutputCollector.emit(new Values(order));
}
}
@Override
public void ack(Object msgId) {
super.ack(msgId);
}
@Override
public void fail(Object msgId) {
super.fail(msgId);
}
}
| 29.765625 | 107 | 0.68399 |
6ff5af8657907c8d7b36f620f775940d0c2e8924 | 1,040 | package net.ddns.crbkproject.api.soil.moisture;
import io.swagger.v3.oas.annotations.Operation;
import net.ddns.crbkproject.api.PaginatedResponse;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.SortDefault;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping("/v1/soil-moisture")
class SoilMoistureController {
private final SoilMoistureFacade facade;
public SoilMoistureController(SoilMoistureFacade facade) {
this.facade = facade;
}
@GetMapping
@Operation(summary = "Wyszukiwanie wszystkich pomiarów wilgotności gleby")
public Mono<PaginatedResponse<SoilMoistureResponse>> getPage(@SortDefault(sort = "measuredAt", direction = Sort.Direction.DESC) Pageable pageable) {
return facade.getPage(pageable);
}
}
| 37.142857 | 152 | 0.798077 |
b9e43ebf4f311385fe28f58a4e594bda3918ec72 | 1,999 | /*
* Copyright (C) 2017 ~ 2025 the original author or authors.
* <Wanglsir@gmail.com, 983708408@qq.com> Technology CO.LTD.
* 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.
*
* Reference to website: http://wl4g.com
*/
package com.wl4g.component.integration.feign.core.extension;
import static com.wl4g.component.common.collection.CollectionUtils2.isEmptyArray;
import static java.util.Objects.nonNull;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import javax.annotation.Nullable;
import javax.validation.constraints.NotNull;
import com.wl4g.component.core.bean.BaseBean;
import com.wl4g.component.integration.feign.core.context.internal.FeignContextCoprocessor;
import feign.Response;
/**
* {@link InsertBeanBindingCoprocessor}
*
* @author Wangl.sir <wanglsir@gmail.com, 983708408@qq.com>
* @version v1.0 2021-05-20
* @sine v1.0
* @see
*/
public class InsertBeanBindingCoprocessor implements FeignContextCoprocessor {
@Override
public void beforeConsumerExecution(@NotNull Object proxy, @NotNull Method method, @Nullable Object[] args) {
if (!isEmptyArray(args)) {
for (Object arg : args) {
if (nonNull(arg) && BaseBean.class.isAssignableFrom(arg.getClass())) {
BaseBean.InternalUtil.bind((BaseBean) arg);
break;
}
}
}
}
@Override
public void afterConsumerExecution(@NotNull Response response, Type type) {
// Update current inserted bean id.
BaseBean.InternalUtil.update();
}
}
| 30.753846 | 110 | 0.746373 |
5e6a7270bea159cfe65e167bfca0ce818621f1e7 | 1,192 | package com.zerofall.ezstorage.block;
import com.zerofall.ezstorage.EZStorage;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
public class EZBlockContainer
extends StorageMultiblock implements ITileEntityProvider {
protected EZBlockContainer(String name, Material materialIn) {
super(name, materialIn);
setBlockName(name);
setCreativeTab(EZStorage.instance.creativeTab);
this.isBlockContainer = true;
}
public void breakBlock(World world, int x, int y, int z, Block block, int metadata) {
super.breakBlock(world, x, y, z, block, metadata);
world.removeTileEntity(x, y, z);
}
public boolean onBlockEventReceived(World world, int x, int y, int z, int eventId, int eventParam) {
super.onBlockEventReceived(world, x, y, z, eventId, eventParam);
TileEntity tileentity = world.getTileEntity(x, y, z);
return tileentity==null ? false : tileentity.receiveClientEvent(eventId, eventParam);
}
public TileEntity createNewTileEntity(World worldIn, int meta) {
return null;
}
}
| 35.058824 | 102 | 0.756711 |
c3cdee639e1fa85586b65ef0ba54c2f97087c21f | 7,939 | /*
* Copyright (c) 2004 Sun Microsystems, Inc. All rights reserved. U.S.
* Government Rights - Commercial software. Government users are subject
* to the Sun Microsystems, Inc. standard license agreement and
* applicable provisions of the FAR and its supplements. Use is subject
* to license terms.
*
* This distribution may include materials developed by third parties.
* Sun, Sun Microsystems, the Sun logo, Java and J2EE are trademarks
* or registered trademarks of Sun Microsystems, Inc. in the U.S. and
* other countries.
*
* Copyright (c) 2004 Sun Microsystems, Inc. Tous droits reserves.
*
* Droits du gouvernement americain, utilisateurs gouvernementaux - logiciel
* commercial. Les utilisateurs gouvernementaux sont soumis au contrat de
* licence standard de Sun Microsystems, Inc., ainsi qu'aux dispositions
* en vigueur de la FAR (Federal Acquisition Regulations) et des
* supplements a celles-ci. Distribue par des licences qui en
* restreignent l'utilisation.
*
* Cette distribution peut comprendre des composants developpes par des
* tierces parties. Sun, Sun Microsystems, le logo Sun, Java et J2EE
* sont des marques de fabrique ou des marques deposees de Sun
* Microsystems, Inc. aux Etats-Unis et dans d'autres pays.
*/
package org.riverock.portlet.jsf;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
/**
* User: SMaslyukov
* Date: 17.07.2007
* Time: 17:22:49
*
* <p>supported filters: <code>package</code> and
* <code>protection</code>.</p>
*/
public class MessageFactory {
//
// Protected Constants
//
//
// Class Variables
//
//
// Instance Variables
//
// Attribute Instance Variables
// Relationship Instance Variables
//
// Constructors and Initializers
//
private MessageFactory() {
}
//
// Class methods
//
//
// General Methods
//
public static String substituteParams(Locale locale, String msgtext,
Object[] params) {
String localizedStr = null;
if ((params == null) || (msgtext == null)) {
return msgtext;
}
StringBuffer b = new StringBuffer(100);
MessageFormat mf = new MessageFormat(msgtext);
if (locale != null) {
mf.setLocale(locale);
b.append(mf.format(params));
localizedStr = b.toString();
}
return localizedStr;
}
/**
* This version of getMessage() is used in the RI for localizing RI
* specific messages.
*/
public static FacesMessage getMessage(String messageId, Object[] params) {
Locale locale = null;
FacesContext context = FacesContext.getCurrentInstance();
// context.getViewRoot() may not have been initialized at this point.
if ((context != null) && (context.getViewRoot() != null)) {
locale = context.getViewRoot()
.getLocale();
if (locale == null) {
locale = Locale.getDefault();
}
} else {
locale = Locale.getDefault();
}
return getMessage(locale, messageId, params);
}
public static FacesMessage getMessage(Locale locale, String messageId,
Object[] params) {
FacesMessage result = null;
String summary = null;
String detail = null;
String bundleName = null;
ResourceBundle bundle = null;
// see if we have a user-provided bundle
if (null != (bundleName = getApplication()
.getMessageBundle())) {
if (null != (bundle =
ResourceBundle.getBundle(bundleName, locale,
getCurrentLoader(bundleName)))) {
// see if we have a hit
try {
summary = bundle.getString(messageId);
} catch (MissingResourceException e) {
}
}
}
// we couldn't find a summary in the user-provided bundle
if (null == summary) {
// see if we have a summary in the app provided bundle
bundle =
ResourceBundle.getBundle(FacesMessage.FACES_MESSAGES, locale,
getCurrentLoader(bundleName));
if (null == bundle) {
throw new NullPointerException();
}
// see if we have a hit
try {
summary = bundle.getString(messageId);
} catch (MissingResourceException e) {
}
}
// we couldn't find a summary anywhere! Return null
if (null == summary) {
return null;
}
// At this point, we have a summary and a bundle.
if ((null == summary) || (null == bundle)) {
throw new NullPointerException();
}
summary = substituteParams(locale, summary, params);
try {
detail =
substituteParams(locale,
bundle.getString(messageId + "_detail"), params);
} catch (MissingResourceException e) {
}
return (new FacesMessage(summary, detail));
}
//
// Methods from MessageFactory
//
public static FacesMessage getMessage(FacesContext context, String messageId) {
return getMessage(context, messageId, null);
}
public static FacesMessage getMessage(FacesContext context,
String messageId, Object[] params) {
if ((context == null) || (messageId == null)) {
throw new NullPointerException(
"One or more parameters could be null");
}
Locale locale = null;
// viewRoot may not have been initialized at this point.
if ((context != null) && (context.getViewRoot() != null)) {
locale = context.getViewRoot()
.getLocale();
} else {
locale = Locale.getDefault();
}
if (null == locale) {
throw new NullPointerException();
}
FacesMessage message = getMessage(locale, messageId, params);
if (message != null) {
return message;
}
locale = Locale.getDefault();
return (getMessage(locale, messageId, params));
}
public static FacesMessage getMessage(FacesContext context,
String messageId, Object param0) {
return getMessage(context, messageId, new Object[] { param0 });
}
public static FacesMessage getMessage(FacesContext context,
String messageId, Object param0, Object param1) {
return getMessage(context, messageId, new Object[] { param0, param1 });
}
public static FacesMessage getMessage(FacesContext context,
String messageId, Object param0, Object param1, Object param2) {
return getMessage(context, messageId,
new Object[] { param0, param1, param2 });
}
public static FacesMessage getMessage(FacesContext context,
String messageId, Object param0, Object param1, Object param2,
Object param3) {
return getMessage(context, messageId,
new Object[] { param0, param1, param2, param3 });
}
protected static Application getApplication() {
return (FacesContext.getCurrentInstance().getApplication());
}
protected static ClassLoader getCurrentLoader(Object fallbackClass) {
ClassLoader loader = Thread.currentThread()
.getContextClassLoader();
if (loader == null) {
loader = fallbackClass.getClass()
.getClassLoader();
}
return loader;
}
}
| 31.255906 | 83 | 0.598438 |
105b30002a04a2804d3c2b07b09d0d52b0c01ff2 | 1,053 | package Scov.module.impl.player;
import java.awt.Color;
import Scov.api.annotations.Handler;
import Scov.events.player.EventMotionUpdate;
import Scov.module.Module;
import net.minecraft.network.play.client.C03PacketPlayer;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
public class Zoot extends Module {
public Zoot() {
super("Zoot", 0, ModuleCategory.PLAYER);
}
@Handler
public void onMotionUpdate(final EventMotionUpdate event) {
for (Potion potion : Potion.potionTypes) {
PotionEffect effect;
if (event.isPre() && potion != null && ((effect = mc.thePlayer.getActivePotionEffect(potion)) != null && potion.isBadEffect()
|| mc.thePlayer.isBurning() && !mc.thePlayer.isInWater() && mc.thePlayer.onGround)) {
for (int i = 0; mc.thePlayer.isBurning() ? i < 20 : i < effect.getDuration() / 20; i++) {
mc.thePlayer.sendQueue.addToSendQueue(new C03PacketPlayer(true));
}
}
}
}
public void onEnable() {
super.onEnable();
}
public void onDisable() {
super.onDisable();
}
}
| 27 | 128 | 0.709402 |
90c95868031fbc4d2cd655836c2b0fdee5d6aa7f | 1,293 | /*
* Copyright (c) 2010 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
/*
* Copyright (c) 2015 Tarun Gupta.
* Licensed under the simplified BSD license.
* See Documentation/Licenses/BSD-simplified.txt for more information.
*/
package com.isode.stroke.parser;
import com.isode.stroke.parser.XMLParser;
import com.isode.stroke.eventloop.EventLoop;
import com.isode.stroke.parser.XMLParserClient;
import com.isode.stroke.parser.AttributeMap;
import com.isode.stroke.parser.ElementParser;
import com.isode.stroke.parser.PlatformXMLParserFactory;
public class ParserTester<ParserType extends XMLParserClient> implements XMLParserClient {
private XMLParser xmlParser_;
private ParserType parser_;
public ParserTester(ParserType parser) {
this.parser_ = parser;
xmlParser_ = PlatformXMLParserFactory.createXMLParser(this);
}
public boolean parse(String data) {
return xmlParser_.parse(data);
}
public void handleStartElement(String element, String ns, AttributeMap attributes) {
parser_.handleStartElement(element, ns, attributes);
}
public void handleEndElement(String element, String ns) {
parser_.handleEndElement(element, ns);
}
public void handleCharacterData(String data) {
parser_.handleCharacterData(data);
}
}
| 26.9375 | 90 | 0.784223 |
1d99760d6ae787acaa90a1fb6e4e0fa9241def1f | 166 | package com.todolist.todolist.controller;
import org.springframework.web.bind.annotation.RestController;
@RestController("/notes")
public class NotesController {
}
| 20.75 | 62 | 0.819277 |
4df094cfe7ffc8b1413197719880fff4a300c2cf | 690 | package com.github.liaoheng.common.util;
/**
* 网络本地异常
*
* @author liaoheng
* @version 2015-07-01 15:35
*/
@SystemExceptionNoVessel
public class NetLocalException extends NetException {
public NetLocalException(String errorMessage, Throwable e) {
super(errorMessage, e);
}
public NetLocalException(String errorMessage) {
super(errorMessage);
}
public NetLocalException(Throwable e) {
super(e);
}
public NetLocalException(Throwable e,Object code) {
super(e);
mErrorBody = code;
}
public NetLocalException(String errorMessage, Object code) {
super(errorMessage);
mErrorBody = code;
}
}
| 20.294118 | 64 | 0.657971 |
65a84c16ba247be0dd3cab3ae48eaab38eab791f | 1,995 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
package com.mojang.serialization.codecs;
import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.DataResult;
import com.mojang.serialization.DynamicOps;
import com.mojang.serialization.MapCodec;
import com.mojang.serialization.MapLike;
import com.mojang.serialization.RecordBuilder;
import java.util.Objects;
import java.util.stream.Stream;
public final class PairMapCodec<F, S> extends MapCodec<Pair<F, S>> {
private final MapCodec<F> first;
private final MapCodec<S> second;
public PairMapCodec(final MapCodec<F> first, final MapCodec<S> second) {
this.first = first;
this.second = second;
}
@Override
public <T> DataResult<Pair<F, S>> decode(final DynamicOps<T> ops, final MapLike<T> input) {
return first.decode(ops, input).flatMap(p1 ->
second.decode(ops, input).map(p2 ->
Pair.of(p1, p2)
)
);
}
@Override
public <T> RecordBuilder<T> encode(final Pair<F, S> input, final DynamicOps<T> ops, final RecordBuilder<T> prefix) {
return first.encode(input.getFirst(), ops, second.encode(input.getSecond(), ops, prefix));
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final PairMapCodec<?, ?> pairCodec = (PairMapCodec<?, ?>) o;
return Objects.equals(first, pairCodec.first) && Objects.equals(second, pairCodec.second);
}
@Override
public int hashCode() {
return Objects.hash(first, second);
}
@Override
public String toString() {
return "PairMapCodec[" + first + ", " + second + ']';
}
@Override
public <T> Stream<T> keys(final DynamicOps<T> ops) {
return Stream.concat(first.keys(ops), second.keys(ops));
}
}
| 30.692308 | 120 | 0.638095 |
75b5409cab1a5b6c9684d836bdd3cb3c51e50dfa | 16,249 | /*
* Copyright (c) 2002-2021 Manorrock.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 copyright holder 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 cloud.piranha.extension.webxml;
import cloud.piranha.webapp.api.AuthenticationManager;
import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.TRACE;
import static java.util.stream.Collectors.toSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.lang.System.Logger;
import jakarta.servlet.DispatcherType;
import jakarta.servlet.FilterRegistration;
import jakarta.servlet.MultipartConfigElement;
import jakarta.servlet.ServletRegistration;
import cloud.piranha.webapp.api.LocaleEncodingManager;
import cloud.piranha.webapp.api.MimeTypeManager;
import cloud.piranha.webapp.api.SecurityManager;
import cloud.piranha.webapp.api.WebApplication;
import cloud.piranha.webapp.api.WelcomeFileManager;
/**
* The web.xml / web-fragment.xml processor.
*
* @author Manfred Riem (mriem@manorrock.com)
*/
public class WebXmlProcessor {
/**
* Stores the logger.
*/
private static final Logger LOGGER = System.getLogger(WebXmlProcessor.class.getName());
/**
* Stores the empty string array.
*/
private static final String[] STRING_ARRAY = new String[0];
/**
* Process the web.xml into the web application.
*
* @param webXml the web.xml
* @param webApplication the web application.
*/
public void process(WebXml webXml, WebApplication webApplication) {
LOGGER.log(TRACE, "Started WebXmlProcessor.process");
processContextParameters(webApplication, webXml);
processDefaultContextPath(webApplication, webXml);
processDenyUncoveredHttpMethods(webApplication, webXml);
processDisplayName(webApplication, webXml);
processDistributable(webApplication, webXml);
processErrorPages(webApplication, webXml);
processFilters(webApplication, webXml);
processFilterMappings(webApplication, webXml);
processListeners(webApplication, webXml);
processMimeMappings(webApplication, webXml);
processRequestCharacterEncoding(webApplication, webXml);
processResponseCharacterEncoding(webApplication, webXml);
processRoleNames(webApplication, webXml);
processSecurityConstraints(webApplication, webXml);
processServlets(webApplication, webXml);
processServletMappings(webApplication, webXml);
processWebApp(webApplication, webXml);
processWelcomeFiles(webApplication, webXml);
processLocaleEncodingMapping(webApplication, webXml);
processSessionConfig(webApplication, webXml);
LOGGER.log(TRACE, "Finished WebXmlProcessor.process");
}
/**
* Process the context parameters.
*
* @param webApplication the web application.
* @param webXml the web.xml.
*/
private void processContextParameters(WebApplication webApplication, WebXml webXml) {
for (WebXmlContextParam contextParam : webXml.getContextParams()) {
webApplication.setInitParameter(contextParam.name(), contextParam.value());
}
}
/**
* Process the default context path.
*
* @param webApplication the web application.
* @param webXml the web.xml.
*/
private void processDefaultContextPath(WebApplication webApplication, WebXml webXml) {
if (webXml.getDefaultContextPath() != null) {
webApplication.setContextPath(webXml.getDefaultContextPath());
}
}
/**
* Process the deny uncovered HTTP methods flag.
*
* @param webApplication the web application.
* @param webXml the web.xml.
*/
private void processDenyUncoveredHttpMethods(WebApplication webApplication, WebXml webXml) {
webApplication.setDenyUncoveredHttpMethods(webXml.getDenyUncoveredHttpMethods());
}
/**
* Process the display name flag.
*
* @param webApplication the web application.
* @param webXml the web.xml.
*/
private void processDisplayName(WebApplication webApplication, WebXml webXml) {
webApplication.setServletContextName(webXml.getDisplayName());
}
/**
* Process the distributable flag.
*
* @param webApplication the web application.
* @param webXml the web.xml.
*/
private void processDistributable(WebApplication webApplication, WebXml webXml) {
webApplication.setDistributable(webXml.isDistributable());
}
/**
* Process the error pages.
*
* @param webApplication the web application.
* @param webXml the web.xml.
*/
private void processErrorPages(WebApplication webApplication, WebXml webXml) {
for (WebXmlErrorPage errorPage : webXml.getErrorPages()) {
if (errorPage.errorCode() != null && !errorPage.errorCode().isEmpty()) {
webApplication.addErrorPage(Integer.parseInt(errorPage.errorCode()), errorPage.location());
} else if (errorPage.exceptionType() != null && !errorPage.exceptionType().isEmpty()) {
webApplication.addErrorPage(errorPage.exceptionType(), errorPage.location());
}
}
}
/**
* Process the filter mappings mappings.
*
* @param webApplication the web application.
* @param webXml the web.xml.
*/
private void processFilterMappings(WebApplication webApplication, WebXml webXml) {
webXml.getFilterMappings().forEach(filterMapping -> {
// Filter is mapped to a URL pattern, e.g. /path/customer
webApplication.addFilterMapping(
toDispatcherTypes(filterMapping.getDispatchers()),
filterMapping.getFilterName(),
true,
filterMapping.getUrlPatterns().toArray(STRING_ARRAY));
// Filter is mapped to a named Servlet, e.g. FacesServlet
webApplication.addFilterMapping(
toDispatcherTypes(filterMapping.getDispatchers()),
filterMapping.getFilterName(),
true,
filterMapping.getServletNames().stream().map(e -> "servlet:// " + e).toArray(String[]::new));
});
}
private Set<DispatcherType> toDispatcherTypes(List<String> dispatchers) {
if (dispatchers == null) {
return null;
}
return dispatchers.stream()
.map(DispatcherType::valueOf)
.collect(toSet());
}
/**
* Process the filters.
*
* @param webApplication the web application.
* @param webXml the web.xml.
*/
private void processFilters(WebApplication webApplication, WebXml webXml) {
webXml.getFilters().forEach(filter -> {
FilterRegistration.Dynamic dynamic = null;
if (filter.getClassName() != null) {
dynamic = webApplication.addFilter(filter.getFilterName(), filter.getClassName());
} else if (filter.getServletName() != null) {
dynamic = webApplication.addFilter(filter.getFilterName(), filter.getServletName());
}
if (dynamic != null && filter.isAsyncSupported()) {
dynamic.setAsyncSupported(true);
}
if (dynamic != null) {
for (WebXmlFilterInitParam initParam : filter.getInitParams()) {
dynamic.setInitParameter(initParam.name(), initParam.value());
}
}
});
}
/**
* Process the listeners.
*
* @param webApplication the web application.
* @param webXml the web.xml.
*/
private void processListeners(WebApplication webApplication, WebXml webXml) {
for (WebXmlListener listener : webXml.getListeners()) {
webApplication.addListener(listener.className());
}
}
/**
* Process the mime mappings.
*
* @param webApplication the web application.
* @param webXml the web.xml.
*/
private void processMimeMappings(WebApplication webApplication, WebXml webXml) {
if (webApplication.getAttribute(MimeTypeManager.class.getName()) instanceof MimeTypeManager manager) {
webXml.getMimeMappings().forEach(mapping -> {
manager.addMimeType(mapping.extension(), mapping.mimeType());
});
}
}
/**
* Process the request character encoding.
*
* @param webApplication the web application.
* @param webXml the web.xml.
*/
private void processRequestCharacterEncoding(WebApplication webApplication, WebXml webXml) {
if (webXml.getRequestCharacterEncoding() != null) {
webApplication.setRequestCharacterEncoding(webXml.getRequestCharacterEncoding());
}
}
/**
* Process the response character encoding.
*
* @param webApplication the web application.
* @param webXml the web.xml.
*/
private void processResponseCharacterEncoding(WebApplication webApplication, WebXml webXml) {
if (webXml.getResponseCharacterEncoding() != null) {
webApplication.setResponseCharacterEncoding(webXml.getResponseCharacterEncoding());
}
}
private void processRoleNames(WebApplication webApplication, WebXml webXml) {
webApplication.getManager(SecurityManager.class).declareRoles(webXml.getRoleNames());
}
/**
* Process the servlet mappings.
*
* @param webApplication the web application.
* @param webXml the web.xml.
*/
private void processServletMappings(WebApplication webApplication, WebXml webXml) {
for (WebXmlServletMapping mapping : webXml.getServletMappings()) {
webApplication.addServletMapping(
mapping.servletName(), mapping.urlPattern());
}
}
/**
* Process the web app. This is basically only the version contained within
* it.
*
* @param webApplication the web application.
* @param webXml the web.xml.
*/
private void processWebApp(WebApplication webApplication, WebXml webXml) {
if (webXml.getMajorVersion() != -1) {
webApplication.setEffectiveMajorVersion(webXml.getMajorVersion());
}
if (webXml.getMinorVersion() != -1) {
webApplication.setEffectiveMinorVersion(webXml.getMinorVersion());
}
}
/**
* Process the servlets.
*
* @param webApplication the web application.
* @param webXml the web.xml.
*/
private void processServlets(WebApplication webApplication, WebXml webXml) {
LOGGER.log(DEBUG, "Configuring Servlets");
for (WebXmlServlet servlet : webXml.getServlets()) {
LOGGER.log(DEBUG, () -> "Configuring Servlet: " + servlet.getServletName());
ServletRegistration.Dynamic dynamic = webApplication.addServlet(servlet.getServletName(), servlet.getClassName());
String jspFile = servlet.getJspFile();
if (!isEmpty(jspFile)) {
webApplication.addJspFile(servlet.getServletName(), jspFile);
}
if (servlet.isAsyncSupported()) {
dynamic.setAsyncSupported(true);
}
WebXmlServletMultipartConfig multipartConfig = servlet.getMultipartConfig();
if (multipartConfig != null) {
dynamic.setMultipartConfig(
new MultipartConfigElement(
multipartConfig.getLocation(),
multipartConfig.getMaxFileSize(),
multipartConfig.getMaxRequestSize(),
multipartConfig.getFileSizeThreshold()));
}
servlet.getInitParams().forEach(initParam -> {
ServletRegistration servletRegistration = webApplication.getServletRegistration(servlet.getServletName());
if (servletRegistration != null) {
servletRegistration.setInitParameter(initParam.name(), initParam.value());
}
});
LOGGER.log(DEBUG, () -> "Configured Servlet: " + servlet.getServletName());
}
}
/**
* Process the welcome files.
*
* @param webApplication the web application.
* @param webXml the web.xml.
*/
private void processWelcomeFiles(WebApplication webApplication, WebXml webXml) {
LOGGER.log(DEBUG, "Adding welcome files");
Iterator<String> iterator = webXml.getWelcomeFiles().iterator();
WelcomeFileManager welcomeFileManager = webApplication.getManager(WelcomeFileManager.class);
while (iterator.hasNext()) {
String welcomeFile = iterator.next();
LOGGER.log(DEBUG, () -> "Adding welcome file: " + welcomeFile);
welcomeFileManager.addWelcomeFile(welcomeFile);
}
}
private void processLocaleEncodingMapping(WebApplication webApplication, WebXml webXml) {
Map<String, String> localeMapping = webXml.getLocaleEncodingMapping();
if (localeMapping == null) {
return;
}
LocaleEncodingManager localeEncodingManager = webApplication.getManager(LocaleEncodingManager.class);
if (localeEncodingManager == null) {
return;
}
localeMapping.forEach(localeEncodingManager::addCharacterEncoding);
}
/**
* Process the session config.
*
* @param webApplication the web application.
* @param webXml the web.xml.
*/
private void processSessionConfig(WebApplication webApplication, WebXml webXml) {
WebXmlSessionConfig sessionConfig = webXml.getSessionConfig();
if (sessionConfig == null) {
return;
}
webApplication.setSessionTimeout(sessionConfig.sessionTimeout());
}
private boolean isEmpty(String string) {
return string == null || string.isEmpty();
}
/**
* Process the security constraints.
*
* @param webApplication the web application.
* @param webXml the web.xml.
*/
private void processSecurityConstraints(WebApplication webApplication, WebXml webXml) {
AuthenticationManager manager = webApplication.getManager(AuthenticationManager.class);
for (WebXmlSecurityConstraint constraint : webXml.getSecurityConstraints()) {
for (WebXmlSecurityConstraint.WebResourceCollection collection : constraint.getWebResourceCollections()) {
for (String urlPattern : collection.getUrlPatterns()) {
manager.addSecurityMapping(urlPattern);
}
}
}
}
}
| 38.143192 | 126 | 0.658871 |
4a0a193a7802d294e947feb015a9d7713deaa6da | 603 | package org.beanplant.JavaText.handlers;
/**
* The EventHandler interface. Any part of the application that wishes to catch
* events that may be fired by a user must extend this class, and register
* themselves as an EventHandler in the CommandParser class
*
* @author the_DJDJ
*/
public interface EventHandler {
/**
* The method called when an event is fired. Classes must extend this method
* and then handle their event in their own way.
*
* @param event a String with information on which event was fired
*/
public void fireEvent(String event);
}
| 28.714286 | 80 | 0.703151 |
7a1e9d2c9a1547cbf475492d9e7068fa90523706 | 11,067 | package org.bc.jcajce.provider.asymmetric.ec;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.EllipticCurve;
import org.bc.asn1.ASN1ObjectIdentifier;
import org.bc.asn1.ASN1OctetString;
import org.bc.asn1.ASN1Primitive;
import org.bc.asn1.DERBitString;
import org.bc.asn1.DERNull;
import org.bc.asn1.DEROctetString;
import org.bc.asn1.x509.AlgorithmIdentifier;
import org.bc.asn1.x509.SubjectPublicKeyInfo;
import org.bc.asn1.x9.X962Parameters;
import org.bc.asn1.x9.X9ECParameters;
import org.bc.asn1.x9.X9ECPoint;
import org.bc.asn1.x9.X9IntegerConverter;
import org.bc.asn1.x9.X9ObjectIdentifiers;
import org.bc.crypto.params.ECDomainParameters;
import org.bc.crypto.params.ECPublicKeyParameters;
import org.bc.jcajce.provider.asymmetric.util.KeyUtil;
import org.bc.jcajce.provider.config.ProviderConfiguration;
import org.bc.jce.interfaces.ECPointEncoder;
import org.bc.jce.provider.BouncyCastleProvider;
import org.bc.jce.spec.ECNamedCurveSpec;
import org.bc.math.ec.ECCurve;
import org.bc.math.ec.ECPoint;
public class BCECPublicKey implements ECPublicKey, org.bc.jce.interfaces.ECPublicKey, ECPointEncoder {
static final long serialVersionUID = 2422789860422731812L;
private String algorithm = "EC";
private boolean withCompression;
private transient ECPoint q;
private transient ECParameterSpec ecSpec;
private transient ProviderConfiguration configuration;
public BCECPublicKey(String var1, BCECPublicKey var2) {
this.algorithm = var1;
this.q = var2.q;
this.ecSpec = var2.ecSpec;
this.withCompression = var2.withCompression;
this.configuration = var2.configuration;
}
public BCECPublicKey(String var1, ECPublicKeySpec var2, ProviderConfiguration var3) {
this.algorithm = var1;
this.ecSpec = var2.getParams();
this.q = EC5Util.convertPoint(this.ecSpec, var2.getW(), false);
this.configuration = var3;
}
public BCECPublicKey(String var1, org.bc.jce.spec.ECPublicKeySpec var2, ProviderConfiguration var3) {
this.algorithm = var1;
this.q = var2.getQ();
if (var2.getParams() != null) {
ECCurve var4 = var2.getParams().getCurve();
EllipticCurve var5 = EC5Util.convertCurve(var4, var2.getParams().getSeed());
this.ecSpec = EC5Util.convertSpec(var5, var2.getParams());
} else {
if (this.q.getCurve() == null) {
org.bc.jce.spec.ECParameterSpec var6 = var3.getEcImplicitlyCa();
this.q = var6.getCurve().createPoint(this.q.getX().toBigInteger(), this.q.getY().toBigInteger(), false);
}
this.ecSpec = null;
}
this.configuration = var3;
}
public BCECPublicKey(String var1, ECPublicKeyParameters var2, ECParameterSpec var3, ProviderConfiguration var4) {
ECDomainParameters var5 = var2.getParameters();
this.algorithm = var1;
this.q = var2.getQ();
if (var3 == null) {
EllipticCurve var6 = EC5Util.convertCurve(var5.getCurve(), var5.getSeed());
this.ecSpec = this.createSpec(var6, var5);
} else {
this.ecSpec = var3;
}
this.configuration = var4;
}
public BCECPublicKey(String var1, ECPublicKeyParameters var2, org.bc.jce.spec.ECParameterSpec var3, ProviderConfiguration var4) {
ECDomainParameters var5 = var2.getParameters();
this.algorithm = var1;
this.q = var2.getQ();
EllipticCurve var6;
if (var3 == null) {
var6 = EC5Util.convertCurve(var5.getCurve(), var5.getSeed());
this.ecSpec = this.createSpec(var6, var5);
} else {
var6 = EC5Util.convertCurve(var3.getCurve(), var3.getSeed());
this.ecSpec = EC5Util.convertSpec(var6, var3);
}
this.configuration = var4;
}
public BCECPublicKey(String var1, ECPublicKeyParameters var2, ProviderConfiguration var3) {
this.algorithm = var1;
this.q = var2.getQ();
this.ecSpec = null;
this.configuration = var3;
}
public BCECPublicKey(ECPublicKey var1, ProviderConfiguration var2) {
this.algorithm = var1.getAlgorithm();
this.ecSpec = var1.getParams();
this.q = EC5Util.convertPoint(this.ecSpec, var1.getW(), false);
}
BCECPublicKey(String var1, SubjectPublicKeyInfo var2, ProviderConfiguration var3) {
this.algorithm = var1;
this.configuration = var3;
this.populateFromPubKeyInfo(var2);
}
private ECParameterSpec createSpec(EllipticCurve var1, ECDomainParameters var2) {
return new ECParameterSpec(var1, new java.security.spec.ECPoint(var2.getG().getX().toBigInteger(), var2.getG().getY().toBigInteger()), var2.getN(), var2.getH().intValue());
}
private void populateFromPubKeyInfo(SubjectPublicKeyInfo var1) {
X962Parameters var2 = new X962Parameters((ASN1Primitive)var1.getAlgorithm().getParameters());
ECCurve var3;
EllipticCurve var4;
if (var2.isNamedCurve()) {
ASN1ObjectIdentifier var5 = (ASN1ObjectIdentifier)var2.getParameters();
X9ECParameters var6 = ECUtil.getNamedCurveByOid(var5);
var3 = var6.getCurve();
var4 = EC5Util.convertCurve(var3, var6.getSeed());
this.ecSpec = new ECNamedCurveSpec(ECUtil.getCurveName(var5), var4, new java.security.spec.ECPoint(var6.getG().getX().toBigInteger(), var6.getG().getY().toBigInteger()), var6.getN(), var6.getH());
} else if (var2.isImplicitlyCA()) {
this.ecSpec = null;
var3 = this.configuration.getEcImplicitlyCa().getCurve();
} else {
X9ECParameters var11 = X9ECParameters.getInstance(var2.getParameters());
var3 = var11.getCurve();
var4 = EC5Util.convertCurve(var3, var11.getSeed());
this.ecSpec = new ECParameterSpec(var4, new java.security.spec.ECPoint(var11.getG().getX().toBigInteger(), var11.getG().getY().toBigInteger()), var11.getN(), var11.getH().intValue());
}
DERBitString var12 = var1.getPublicKeyData();
byte[] var13 = var12.getBytes();
Object var7 = new DEROctetString(var13);
if (var13[0] == 4 && var13[1] == var13.length - 2 && (var13[2] == 2 || var13[2] == 3)) {
int var8 = (new X9IntegerConverter()).getByteLength(var3);
if (var8 >= var13.length - 3) {
try {
var7 = (ASN1OctetString)ASN1Primitive.fromByteArray(var13);
} catch (IOException var10) {
throw new IllegalArgumentException("error recovering public key");
}
}
}
X9ECPoint var14 = new X9ECPoint(var3, (ASN1OctetString)var7);
this.q = var14.getPoint();
}
public String getAlgorithm() {
return this.algorithm;
}
public String getFormat() {
return "X.509";
}
public byte[] getEncoded() {
X962Parameters var1;
ECCurve var5;
if (this.ecSpec instanceof ECNamedCurveSpec) {
ASN1ObjectIdentifier var3 = ECUtil.getNamedCurveOid(((ECNamedCurveSpec)this.ecSpec).getName());
if (var3 == null) {
var3 = new ASN1ObjectIdentifier(((ECNamedCurveSpec)this.ecSpec).getName());
}
var1 = new X962Parameters(var3);
} else if (this.ecSpec == null) {
var1 = new X962Parameters(DERNull.INSTANCE);
} else {
var5 = EC5Util.convertCurve(this.ecSpec.getCurve());
X9ECParameters var4 = new X9ECParameters(var5, EC5Util.convertPoint(var5, this.ecSpec.getGenerator(), this.withCompression), this.ecSpec.getOrder(), BigInteger.valueOf((long)this.ecSpec.getCofactor()), this.ecSpec.getCurve().getSeed());
var1 = new X962Parameters(var4);
}
var5 = this.engineGetQ().getCurve();
ASN1OctetString var6 = (ASN1OctetString)(new X9ECPoint(var5.createPoint(this.getQ().getX().toBigInteger(), this.getQ().getY().toBigInteger(), this.withCompression))).toASN1Primitive();
SubjectPublicKeyInfo var2 = new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, var1), var6.getOctets());
return KeyUtil.getEncodedSubjectPublicKeyInfo(var2);
}
private void extractBytes(byte[] var1, int var2, BigInteger var3) {
byte[] var4 = var3.toByteArray();
if (var4.length < 32) {
byte[] var5 = new byte[32];
System.arraycopy(var4, 0, var5, var5.length - var4.length, var4.length);
var4 = var5;
}
for(int var6 = 0; var6 != 32; ++var6) {
var1[var2 + var6] = var4[var4.length - 1 - var6];
}
}
public ECParameterSpec getParams() {
return this.ecSpec;
}
public org.bc.jce.spec.ECParameterSpec getParameters() {
return this.ecSpec == null ? null : EC5Util.convertSpec(this.ecSpec, this.withCompression);
}
public java.security.spec.ECPoint getW() {
return new java.security.spec.ECPoint(this.q.getX().toBigInteger(), this.q.getY().toBigInteger());
}
public ECPoint getQ() {
if (this.ecSpec == null) {
return (ECPoint)(this.q instanceof ECPoint.Fp ? new ECPoint.Fp((ECCurve)null, this.q.getX(), this.q.getY()) : new ECPoint.F2m((ECCurve)null, this.q.getX(), this.q.getY()));
} else {
return this.q;
}
}
public ECPoint engineGetQ() {
return this.q;
}
org.bc.jce.spec.ECParameterSpec engineGetSpec() {
return this.ecSpec != null ? EC5Util.convertSpec(this.ecSpec, this.withCompression) : this.configuration.getEcImplicitlyCa();
}
public String toString() {
StringBuffer var1 = new StringBuffer();
String var2 = System.getProperty("line.separator");
var1.append("EC Public Key").append(var2);
var1.append(" X: ").append(this.q.getX().toBigInteger().toString(16)).append(var2);
var1.append(" Y: ").append(this.q.getY().toBigInteger().toString(16)).append(var2);
return var1.toString();
}
public void setPointFormat(String var1) {
this.withCompression = !"UNCOMPRESSED".equalsIgnoreCase(var1);
}
public boolean equals(Object var1) {
if (!(var1 instanceof BCECPublicKey)) {
return false;
} else {
BCECPublicKey var2 = (BCECPublicKey)var1;
return this.engineGetQ().equals(var2.engineGetQ()) && this.engineGetSpec().equals(var2.engineGetSpec());
}
}
public int hashCode() {
return this.engineGetQ().hashCode() ^ this.engineGetSpec().hashCode();
}
private void readObject(ObjectInputStream var1) throws IOException, ClassNotFoundException {
var1.defaultReadObject();
byte[] var2 = (byte[])var1.readObject();
this.populateFromPubKeyInfo(SubjectPublicKeyInfo.getInstance(ASN1Primitive.fromByteArray(var2)));
this.configuration = BouncyCastleProvider.CONFIGURATION;
}
private void writeObject(ObjectOutputStream var1) throws IOException {
var1.defaultWriteObject();
var1.writeObject(this.getEncoded());
}
}
| 39.666667 | 245 | 0.677239 |
8c5d9003b79701e31dc2c0acd85c2b1d6b6228e1 | 414 | package org.stagemonitor.core.metrics.metrics2;
import org.stagemonitor.configuration.converter.AbstractValueConverter;
public class MetricNameValueConverter extends AbstractValueConverter<MetricName> {
@Override
public MetricName convert(String s) throws IllegalArgumentException {
return MetricName.name(s).build();
}
@Override
public String toString(MetricName value) {
return value.getName();
}
}
| 25.875 | 82 | 0.809179 |
68e8cdcf694497dc3384a220a456aa4a11156120 | 480 | package modelos;
import java.util.HashMap;
public class Banco {
private HashMap<String, Produto> tabela;
public Banco(){
tabela = new HashMap<String, Produto>();
inicializar();
}
public HashMap<String, Produto> getTabela(){
return tabela;
}
private void inicializar() {
Produto prod = new Produto();
prod.setCodigo("111");
prod.setDescricao("Caneta azul");
prod.setPreco(12);
prod.setQuant(150);
tabela.put(prod.getCodigo(), prod);
}
}
| 15.483871 | 45 | 0.670833 |
05be80e9492586f4323476f18f5374246a0d973f | 269 | package db.sharding.common.dao;
import db.sharding.common.domain.Book;
import org.springframework.stereotype.Repository;
import org.springframework.data.repository.CrudRepository;
@Repository
public interface BookRepository extends CrudRepository<Book, Integer> {
}
| 24.454545 | 71 | 0.836431 |
5805fddc6aac97bc0d4c2b2365d275050b7babe0 | 1,158 | package com.communote.server.web.fe.portal.blog.forms;
import com.communote.server.persistence.user.InviteUserForm;
/**
* Formular to hold information to invite a user to a blog.
*
* @author Communote GmbH - <a href="http://www.communote.com/">http://www.communote.com/</a>, Torstenn Lunze
*/
public class BlogMemberInviteForm extends InviteUserForm {
/** The role. */
private String role;
/** The blog id. */
private Long blogId;
/**
* Gets the blog id.
*
* @return the blog id
*/
public Long getBlogId() {
return blogId;
}
/**
* Gets the role.
*
* @return the role
*/
public String getRole() {
return role;
}
/**
* Sets the blog id.
*
* @param blogId
* the new blog id
*/
public void setBlogId(Long blogId) {
this.blogId = blogId;
}
/**
* Sets the role.
*
* @param role
* the new role
*/
public void setRole(String role) {
this.role = role == null ? null : role.trim();
}
}
| 20.315789 | 110 | 0.517271 |
01d5a4f8a5aff460b7efce38788797db2c5f7127 | 1,323 | /*
* Copyright 2020 Google LLC. 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.mlkit.samples.nl.smartreply.java;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.google.mlkit.samples.nl.smartreply.R;
import com.google.mlkit.samples.nl.smartreply.java.chat.ChatFragment;
/** Default launcher activity. */
public class MainActivityJava extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_smartreply_activity);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, ChatFragment.newInstance())
.commitNow();
}
}
}
| 33.075 | 75 | 0.741497 |
382632ee74bcbcf325c6c0c95a00744bf665deaf | 659 | package com.shoes.scarecrow.persistence.service;
import com.shoes.scarecrow.persistence.domain.User;
import com.shoes.scarecrow.persistence.mappers.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author wangyucheng
* @description
* @create 2018/2/12 10:17
*/
@Service
public class UserService {
@Autowired
protected UserMapper userMapper;
public int saveUser(User user){
return userMapper.insert(user);
}
public User getUser(String userName, String passWord) {
return userMapper.getUserByNameAndPassword(userName,passWord);
}
} | 23.535714 | 70 | 0.754173 |
7ff523cd2266898566386ae940abd3c105cb856c | 3,206 | /*
* Copyright 2000-2010 JetBrains s.r.o.
*
* 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.jetbrains.idea.maven.model;
import java.io.File;
import java.io.Serializable;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
public class MavenProjectProblem implements Serializable {
public enum ProblemType {
SYNTAX, STRUCTURE, DEPENDENCY, PARENT, SETTINGS_OR_PROFILES
}
private final String myPath;
private final String myDescription;
private final ProblemType myType;
public static MavenProjectProblem createStructureProblem(String path, String description) {
return createProblem(path, description, MavenProjectProblem.ProblemType.STRUCTURE);
}
public static MavenProjectProblem createSyntaxProblem(String path, MavenProjectProblem.ProblemType type) {
return createProblem(path, MessageFormat.format("''{0}'' has syntax errors", new File(path).getName()) , type);
}
public static MavenProjectProblem createProblem(String path, String description, MavenProjectProblem.ProblemType type) {
return new MavenProjectProblem(path, description, type);
}
public static Collection<MavenProjectProblem> createProblemsList() {
return createProblemsList(Collections.<MavenProjectProblem>emptySet());
}
public static Collection<MavenProjectProblem> createProblemsList(Collection<? extends MavenProjectProblem> copyThis) {
return new LinkedHashSet<MavenProjectProblem>(copyThis);
}
public MavenProjectProblem(String path, String description, ProblemType type) {
myPath = path;
myDescription = description;
myType = type;
}
public String getPath() {
return myPath;
}
public String getDescription() {
return myDescription;
}
public ProblemType getType() {
return myType;
}
@Override
public String toString() {
return myType + ":" + myDescription + ":" + myPath;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MavenProjectProblem that = (MavenProjectProblem)o;
if (myDescription != null ? !myDescription.equals(that.myDescription) : that.myDescription != null) return false;
if (myType != that.myType) return false;
if (myPath != null ? !myPath.equals(that.myPath) : that.myPath != null) return false;
return true;
}
@Override
public int hashCode() {
int result = myPath != null ? myPath.hashCode() : 0;
result = 31 * result + (myDescription != null ? myDescription.hashCode() : 0);
result = 31 * result + (myType != null ? myType.hashCode() : 0);
return result;
}
}
| 32.383838 | 122 | 0.729881 |
7f43c95c3d54a97ff100e1aa2311da4b12bed132 | 354 | package com.alibaba.tesla.appmanager.domain.res.apppackage;
import lombok.Builder;
import lombok.Data;
/**
* @ClassName:AppPackageReleaseRes
* @author yangjie.dyj@alibaba-inc.com
* @DATE: 2020-11-11
* @Description:
**/
@Builder
@Data
public class AppPackageReleaseRes {
/**
* AppPackage发布id
*/
private Long appPackageRelaseId;
}
| 17.7 | 59 | 0.711864 |
04510329405fdc40bbb6e16a5c66fa99a4e0d97b | 5,733 | package com.haoyang.lovelyreader.tre.ui;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.haoyang.lovelyreader.R;
import com.haoyang.lovelyreader.tre.base.BaseActivity;
import com.haoyang.lovelyreader.tre.bean.UserBean;
import com.haoyang.lovelyreader.tre.bean.api.ApiRequest;
import com.haoyang.lovelyreader.tre.bean.api.UserLoginParam;
import com.haoyang.lovelyreader.tre.helper.DBHelper;
import com.haoyang.lovelyreader.tre.helper.UrlConfig;
import com.haoyang.lovelyreader.tre.http.MyRequestEntity;
import com.haoyang.lovelyreader.tre.http.RequestCallback;
import com.haoyang.lovelyreader.tre.util.Utils;
import com.mjiayou.trecorelib.http.RequestSender;
import com.mjiayou.trecorelib.util.SharedUtils;
import com.mjiayou.trecorelib.util.ToastUtils;
import com.mjiayou.trecorelib.util.UserUtils;
/**
* Created by xin on 18/9/22.
*/
public class LoginActivity extends BaseActivity {
private ImageView ivBack;
private EditText etPhone;
private EditText etPassword;
private TextView tvLogin;
private TextView tvFindPwd;
private TextView tvRegister;
@Override
protected int getLayoutId() {
return R.layout.activity_login;
}
@Override
protected void afterOnCreate(Bundle savedInstanceState) {
// findViewById
ivBack = (ImageView) findViewById(R.id.ivBack);
etPhone = (EditText) findViewById(R.id.etPhone);
etPassword = (EditText) findViewById(R.id.etPassword);
tvLogin = (TextView) findViewById(R.id.tvLogin);
tvFindPwd = (TextView) findViewById(R.id.tvFindPwd);
tvRegister = (TextView) findViewById(R.id.tvRegister);
initView();
}
@Override
public void initView() {
super.initView();
// 如果保存登录信息,则自动填充
String lastUsername = SharedUtils.get().getAccountUsername();
String lastPassword = SharedUtils.get().getAccountPassword();
if (!TextUtils.isEmpty(lastUsername)) {
etPhone.setText(lastUsername);
}
if (!TextUtils.isEmpty(lastPassword)) {
etPassword.setText(lastPassword);
}
// ivBack
ivBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
// tvLogin
tvLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String phone = etPhone.getText().toString();
final String password = etPassword.getText().toString();
if (TextUtils.isEmpty(phone)) {
ToastUtils.show("请输入手机号码");
return;
}
if (!Utils.isMobileNO(phone)) {
ToastUtils.show("请输入正确的手机号码");
return;
}
if (TextUtils.isEmpty(password)) {
ToastUtils.show("请输入密码");
return;
}
UserLoginParam userLoginParamBean = new UserLoginParam();
userLoginParamBean.setPhone(phone);
userLoginParamBean.setPwd(password);
String content = ApiRequest.getContent(userLoginParamBean);
MyRequestEntity requestEntity = new MyRequestEntity(UrlConfig.apiUserLogin);
requestEntity.setContentWithHeader(content);
RequestSender.get().send(requestEntity, new RequestCallback<UserBean>() {
@Override
public void onStart() {
showLoading(true);
}
@Override
public void onSuccess(int code, UserBean bean) {
showLoading(false);
if (bean != null) {
ToastUtils.show("登录成功");
// 保存登录的用户名和密码,下次自动填充
SharedUtils.get().setAccountUsername(phone);
SharedUtils.get().setAccountPassword(password);
// 保存用户信息
DBHelper.setUserBean(bean);
// 通知登录成功
UserUtils.doLogin(bean.getToken());
// 页面跳转
startActivity(new Intent(mContext, MainActivity.class));
finish();
}
}
@Override
public void onFailure(int code, String msg) {
showLoading(false);
ToastUtils.show(msg);
}
});
}
});
// tvRegister
tvRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mIntent = new Intent(mContext, RegisterActivity.class);
mIntent.putExtra(RegisterActivity.EXTRA_PAGE_TYPE, RegisterActivity.PAGE_TYPE_REGISTER);
startActivity(mIntent);
}
});
// tvFindPwd
tvFindPwd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mIntent = new Intent(mContext, RegisterActivity.class);
mIntent.putExtra(RegisterActivity.EXTRA_PAGE_TYPE, RegisterActivity.PAGE_TYPE_FIND_PWD);
startActivity(mIntent);
}
});
}
}
| 35.388889 | 104 | 0.573696 |
2e9bd84ecae2394dd5e5de2235b96b32aa59fd2f | 4,652 | package co.com.codesoftware.beans.productos;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import co.com.codesoftware.logica.ProductosLogica;
import co.com.codesoftware.logica.ReferenciaLogica;
import co.com.codesoftware.server.nsigemco.ReferenciaEntity;
import co.com.codesoftware.server.productos.ProductoSimpleEntity;
import co.com.codesoftware.servicio.usuario.UsuarioEntity;
import co.com.codesoftware.utilities.ErrorEnum;
import co.com.codesoftware.utilities.GeneralBean;
@ManagedBean
@ViewScoped
public class ActualizaProductoBean implements GeneralBean {
private UsuarioEntity objetoSesion;
private ProductoSimpleEntity producto;
private Map<String, Integer> listaMapSubCate;
private ErrorEnum enumer;
public UsuarioEntity getObjetoSesion() {
return objetoSesion;
}
public void setObjetoSesion(UsuarioEntity objetoSesion) {
this.objetoSesion = objetoSesion;
}
@PostConstruct
public void init() {
try {
this.objetoSesion = (UsuarioEntity) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
.get("dataSession");
Integer idDska = (Integer) FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
.get("idProdSelect");
ProductosLogica objLogica = new ProductosLogica();
this.producto = objLogica.consultaProdXId(idDska);
this.buscaSubCategorias();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Funcion la cual busca subcategorias o referencias basado en una categoria
*/
public void buscaSubCategorias() {
ReferenciaLogica objLogica = new ReferenciaLogica();
try {
List<ReferenciaEntity> listRefe = objLogica.obtieneReferenciasXcate(producto.getCategoria());
this.listaMapSubCate = null;
if (listRefe != null) {
for (ReferenciaEntity referencia : listRefe) {
if (this.listaMapSubCate == null) {
this.listaMapSubCate = new HashMap<String, Integer>();
}
this.listaMapSubCate.put(referencia.getDescripcion(), referencia.getId());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Funcion con la cual actualizo el producto
*/
public void actualizaProducto() {
try {
boolean valida = this.validaDatos();
if(valida){
ProductosLogica objLogica = new ProductosLogica();
String rta = objLogica.actualizaCamposProducto(producto);
if("Ok".equalsIgnoreCase(rta)){
this.setEnumer(ErrorEnum.SUCCESS);
this.messageBean("Producto actualizado correctamente");
}else{
this.setEnumer(ErrorEnum.ERROR);
this.messageBean("Error al actualizar el producto: "+ rta);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Funcion con la cual valido los datos que el usuario esta dando
* @return
*/
public boolean validaDatos(){
try {
if("".equalsIgnoreCase(producto.getCodigoExt()) & producto.getCodigoExt() == null){
this.setEnumer(ErrorEnum.ERROR);
this.messageBean("El campo codigo externo no puede ser nulo");
return false;
}else if("".equalsIgnoreCase(producto.getDescripcion()) & producto.getDescripcion()== null) {
this.setEnumer(ErrorEnum.ERROR);
this.messageBean("El campo codigo externo no puede ser nulo");
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public ProductoSimpleEntity getProducto() {
return producto;
}
public void setProducto(ProductoSimpleEntity producto) {
this.producto = producto;
}
public Map<String, Integer> getListaMapSubCate() {
return listaMapSubCate;
}
public void setListaMapSubCate(Map<String, Integer> listaMapSubCate) {
this.listaMapSubCate = listaMapSubCate;
}
/**
* Metodo generico para mostrar mensajes de error o advertencia
*
* @param message
*/
public void messageBean(String message) {
switch (this.enumer) {
case ERROR:
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", message));
break;
case FATAL:
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_FATAL, "Fatal!", "Error de sistema"));
break;
case SUCCESS:
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_INFO, "Ok!", message));
break;
default:
break;
}
}
public ErrorEnum getEnumer() {
return enumer;
}
public void setEnumer(ErrorEnum enumer) {
this.enumer = enumer;
}
}
| 27.526627 | 109 | 0.733233 |
fb8d003172fc656760c52476316ddea481236938 | 3,451 | /*
* MIT License
*
* Copyright (c) 2018 Dimitar Zabaznoski
*
* 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 mk.webfactory.dz.maskededittext;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class TextOpTest {
@Test
public void testSubstringFromEmpty() throws Exception {
final String empty = "";
assertEquals("", empty.substring(0, 0));
}
@Test
public void testSubstringFromNToN() throws Exception {
final String abc = "abc";
assertEquals("", abc.substring(0, 0));
}
@Test
public void testCharAddition() throws Exception {
char a = 'a';
char b = (char) (a + 1);
assertEquals('b', b);
assertNotEquals(a, b);
}
@Test
public void testCharDefaultValueInclusion() throws Exception { //Not working
char[] charArray = new char[3];
charArray[1] = 'A';
final String actualString = String.valueOf(charArray);
final String expectedString = "A";
assertNotEquals(expectedString, actualString);
}
@Test
public void testCharDefaultValueOmission() throws Exception {
char[] charArray = new char[3];
charArray[1] = 'A';
StringBuilder stringBuilder = new StringBuilder();
for (final char charValue : charArray) {
if (charValue != Character.UNASSIGNED) {
stringBuilder.append(charValue);
}
}
final String actualString = stringBuilder.toString();
final String expectedString = "A";
assertEquals(expectedString, actualString);
}
@Test
public void testCharSequenceDefaultValueOmission() throws Exception { //Not working
CharSequence charSequence = new StringBuilder()
.append(Character.UNASSIGNED)
.append('A')
.append(Character.UNASSIGNED)
.toString();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < charSequence.length(); i++) {
if (charSequence.charAt(i) != Character.UNASSIGNED) {
stringBuilder.append(charSequence.charAt(i));
}
}
final String actualString = stringBuilder.toString();
final String expectedString = "A";
assertNotEquals(expectedString, actualString);
}
}
| 32.866667 | 87 | 0.660388 |
646cd6e006719bfffd4c2e2850a11ffd53e4e20d | 505 | package com.open.lcp.biz.comment.service.dao.db;
import org.nutz.dao.entity.annotation.SQL;
import com.open.lcp.biz.comment.service.dao.db.entity.IpCityAllEntity;
import com.open.lcp.core.env.LcpResource;
import com.open.lcp.orm.jade.annotation.DAO;
@DAO(catalog = LcpResource.dbAnnotationName_lcp_mysql_biz_comment_master)
public interface MysqlIpCityAllDao {
@SQL("select province,city from ip_city_all where :1 between start_ip and end_ip limit 1")
public IpCityAllEntity getCityByIp(long ip);
}
| 33.666667 | 91 | 0.813861 |
a26377eb9900a110db815a91ea6d98c4bfd557d5 | 784 | /* Idade.java
Programa que calcula a idade e mostra se a pessoa pode votar ou obter CNH
Autora: Caroline Braga
*/
import java.util.Scanner;
public class Idade {
public static void main (String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("Insira o ano de nascimento:");
int nascimento = input.nextInt();
System.out.println("Insira o ano atual:");
int anoAtual = input.nextInt();
input.close();
int idade;
idade = anoAtual - nascimento;
if (idade >= 16) {
System.out.println("Já pode votar");
if (idade >= 18)
System.out.println("Já pode solicitar carteira de habilitação");
}
} // fim do método main
} // fim da classe Idade
| 23.058824 | 80 | 0.59949 |
76c59ca4d5d70f42a4d2bf5f512b02a1c509792c | 63,229 | package ca.uhn.fhir.jpa.term;
import ca.uhn.fhir.context.support.TranslateConceptResult;
import ca.uhn.fhir.i18n.Msg;
import ca.uhn.fhir.jpa.api.model.TranslationRequest;
import ca.uhn.fhir.context.support.TranslateConceptResults;
import ca.uhn.fhir.jpa.entity.TermConceptMap;
import ca.uhn.fhir.jpa.entity.TermConceptMapGroup;
import ca.uhn.fhir.jpa.entity.TermConceptMapGroupElement;
import ca.uhn.fhir.jpa.entity.TermConceptMapGroupElementTarget;
import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException;
import org.hl7.fhir.instance.model.api.IIdType;
import org.hl7.fhir.r4.model.CanonicalType;
import org.hl7.fhir.r4.model.ConceptMap;
import org.hl7.fhir.r4.model.Enumerations;
import org.hl7.fhir.r4.model.UriType;
import org.hl7.fhir.r4.model.codesystems.HttpVerb;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import javax.annotation.Nonnull;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
public class TermConceptMappingSvcImplTest extends BaseTermR4Test {
private static final Logger ourLog = LoggerFactory.getLogger(TermConceptMappingSvcImplTest.class);
private IIdType myConceptMapId;
@Test
public void testCreateConceptMapWithVirtualSourceSystem() {
ConceptMap conceptMap = createConceptMap();
conceptMap.getGroup().forEach(t -> t.setSource(null));
conceptMap.setSource(new CanonicalType("http://hl7.org/fhir/uv/livd/StructureDefinition/loinc-livd"));
persistConceptMap(conceptMap, HttpVerb.POST);
}
@Test
public void testCreateConceptMapWithVirtualSourceSystemWithClientAssignedId() {
ConceptMap conceptMap = createConceptMap();
conceptMap.getGroup().forEach(t -> t.setSource(null));
conceptMap.setSource(new CanonicalType("http://hl7.org/fhir/uv/livd/StructureDefinition/loinc-livd"));
conceptMap.setId("ConceptMap/cm");
persistConceptMap(conceptMap, HttpVerb.PUT);
}
@Test
public void testByCodeSystemsAndSourceCodeOneToMany() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
TranslationRequest translationRequest = new TranslationRequest();
translationRequest.getCodeableConcept().addCoding()
.setSystem(CS_URL)
.setCode("12345");
translationRequest.setTargetSystem(new UriType(CS_URL_3));
List<TranslateConceptResult> targets = myConceptMappingSvc.translate(translationRequest).getResults();
assertNotNull(targets);
assertEquals(2, targets.size());
assertFalse(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationCache());
TranslateConceptResult target = targets.get(0);
ourLog.info("target(0):\n" + target.toString());
assertEquals("56789", target.getCode());
assertEquals("Target Code 56789", target.getDisplay());
assertEquals(CS_URL_3, target.getSystem());
assertEquals("Version 4", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.EQUAL.toCode(), target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
target = targets.get(1);
ourLog.info("target(1):\n" + target.toString());
assertEquals("67890", target.getCode());
assertEquals("Target Code 67890", target.getDisplay());
assertEquals(CS_URL_3, target.getSystem());
assertEquals("Version 4", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.WIDER.toCode(), target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
// Test caching.
targets = myConceptMappingSvc.translate(translationRequest).getResults();
assertNotNull(targets);
assertEquals(2, targets.size());
assertTrue(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationCache());
}
});
}
@Test
public void testByCodeSystemsAndSourceCodeOneToOne() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
TranslationRequest translationRequest = new TranslationRequest();
translationRequest.getCodeableConcept().addCoding()
.setSystem(CS_URL)
.setCode("12345");
translationRequest.setTargetSystem(new UriType(CS_URL_2));
List<TranslateConceptResult> targets = myConceptMappingSvc.translate(translationRequest).getResults();
assertNotNull(targets);
assertEquals(1, targets.size());
assertFalse(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationCache());
TranslateConceptResult target = targets.get(0);
ourLog.info("ConceptMap.group.element.target:\n" + target.toString());
assertEquals("34567", target.getCode());
assertEquals("Target Code 34567", target.getDisplay());
assertEquals(CS_URL_2, target.getSystem());
assertEquals("Version 2", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.EQUAL.toCode(), target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
// Test caching.
targets = myConceptMappingSvc.translate(translationRequest).getResults();
assertNotNull(targets);
assertEquals(1, targets.size());
assertTrue(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationCache());
}
});
}
@Test
public void testByCodeSystemsAndSourceCodeUnmapped() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
TranslationRequest translationRequest = new TranslationRequest();
translationRequest.getCodeableConcept().addCoding()
.setSystem(CS_URL)
.setCode("BOGUS");
translationRequest.setTargetSystem(new UriType(CS_URL_3));
List<TranslateConceptResult> targets = myConceptMappingSvc.translate(translationRequest).getResults();
assertNotNull(targets);
assertTrue(targets.isEmpty());
}
});
}
@Test
public void testConceptMapWithNoSourceAndTargetValueSet() {
ConceptMap conceptMap = new ConceptMap();
conceptMap.setUrl(CM_URL);
conceptMap.setSource(null);
conceptMap.setTarget(null);
ConceptMap.ConceptMapGroupComponent group = conceptMap.addGroup()
.setSource(CS_URL)
.setTarget(CS_URL_2);
group.addElement()
.setCode("12345")
.addTarget()
.setCode("34567");
group.addElement()
.setCode("888")
.addTarget()
.setCode("999");
myConceptMapDao.create(conceptMap);
TranslationRequest translationRequest = new TranslationRequest()
.addCode(CS_URL, "12345")
.setTargetSystem(new UriType(CS_URL_2));
TranslateConceptResults resp = myConceptMappingSvc.translate(translationRequest);
assertEquals(1, resp.size());
assertEquals("34567", resp.getResults().get(0).getCode());
}
@Test
public void testUsingPredicatesWithCodeOnly() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
/*
* Provided:
* source code
*/
TranslationRequest translationRequest = new TranslationRequest();
translationRequest.getCodeableConcept().addCoding()
.setCode("12345");
List<TranslateConceptResult> targets = myConceptMappingSvc.translate(translationRequest).getResults();
assertNotNull(targets);
assertEquals(3, targets.size());
assertFalse(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationCache());
TranslateConceptResult target = targets.get(0);
ourLog.info("target(0):\n" + target.toString());
assertEquals("34567", target.getCode());
assertEquals("Target Code 34567", target.getDisplay());
assertEquals(CS_URL_2, target.getSystem());
assertEquals("Version 2", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.EQUAL.toCode(), target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
target = targets.get(1);
ourLog.info("target(1):\n" + target.toString());
assertEquals("56789", target.getCode());
assertEquals("Target Code 56789", target.getDisplay());
assertEquals(CS_URL_3, target.getSystem());
assertEquals("Version 4", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.EQUAL.toCode(), target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
target = targets.get(2);
ourLog.info("target(2):\n" + target.toString());
assertEquals("67890", target.getCode());
assertEquals("Target Code 67890", target.getDisplay());
assertEquals(CS_URL_3, target.getSystem());
assertEquals("Version 4", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.WIDER.toCode(), target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
// Test caching.
targets = myConceptMappingSvc.translate(translationRequest).getResults();
assertNotNull(targets);
assertEquals(3, targets.size());
assertTrue(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationCache());
}
});
}
@Test
public void testUsingPredicatesWithSourceAndTargetSystem2() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
/*
* Provided:
* source code
* source code system
* target code system #2
*/
TranslationRequest translationRequest = new TranslationRequest();
translationRequest.getCodeableConcept().addCoding()
.setSystem(CS_URL)
.setCode("12345");
translationRequest.setTargetSystem(new UriType(CS_URL_2));
List<TranslateConceptResult> targets = myConceptMappingSvc.translate(translationRequest).getResults();
assertNotNull(targets);
assertEquals(1, targets.size());
assertFalse(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationCache());
TranslateConceptResult target = targets.get(0);
ourLog.info("target:\n" + target.toString());
assertEquals("34567", target.getCode());
assertEquals("Target Code 34567", target.getDisplay());
assertEquals(CS_URL_2, target.getSystem());
assertEquals("Version 2", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.EQUAL.toCode(), target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
// Test caching.
targets = myConceptMappingSvc.translate(translationRequest).getResults();
assertNotNull(targets);
assertEquals(1, targets.size());
assertTrue(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationCache());
}
});
}
@Test
public void testUsingPredicatesWithSourceAndTargetSystem3() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
/*
* Provided:
* source code
* source code system
* target code system #3
*/
TranslationRequest translationRequest = new TranslationRequest();
translationRequest.getCodeableConcept().addCoding()
.setSystem(CS_URL)
.setCode("12345");
translationRequest.setTargetSystem(new UriType(CS_URL_3));
List<TranslateConceptResult> targets = myConceptMappingSvc.translate(translationRequest).getResults();
assertNotNull(targets);
assertEquals(2, targets.size());
assertFalse(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationCache());
TranslateConceptResult target = targets.get(0);
ourLog.info("target(0):\n" + target.toString());
assertEquals("56789", target.getCode());
assertEquals("Target Code 56789", target.getDisplay());
assertEquals(CS_URL_3, target.getSystem());
assertEquals("Version 4", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.EQUAL.toCode(), target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
target = targets.get(1);
ourLog.info("target(1):\n" + target.toString());
assertEquals("67890", target.getCode());
assertEquals("Target Code 67890", target.getDisplay());
assertEquals(CS_URL_3, target.getSystem());
assertEquals("Version 4", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.WIDER.toCode(), target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
// Test caching.
targets = myConceptMappingSvc.translate(translationRequest).getResults();
assertNotNull(targets);
assertEquals(2, targets.size());
assertTrue(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationCache());
}
});
}
@Test
public void testUsingPredicatesWithSourceSystem() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
/*
* Provided:
* source code
* source code system
*/
TranslationRequest translationRequest = new TranslationRequest();
translationRequest.getCodeableConcept().addCoding()
.setSystem(CS_URL)
.setCode("12345");
List<TranslateConceptResult> targets = myConceptMappingSvc.translate(translationRequest).getResults();
assertNotNull(targets);
assertEquals(3, targets.size());
assertFalse(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationCache());
TranslateConceptResult target = targets.get(0);
ourLog.info("target(0):\n" + target.toString());
assertEquals("34567", target.getCode());
assertEquals("Target Code 34567", target.getDisplay());
assertEquals(CS_URL_2, target.getSystem());
assertEquals("Version 2", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.EQUAL.toCode(), target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
target = targets.get(1);
ourLog.info("target(1):\n" + target.toString());
assertEquals("56789", target.getCode());
assertEquals("Target Code 56789", target.getDisplay());
assertEquals(CS_URL_3, target.getSystem());
assertEquals("Version 4", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.EQUAL.toCode(), target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
target = targets.get(2);
ourLog.info("target(2):\n" + target.toString());
assertEquals("67890", target.getCode());
assertEquals("Target Code 67890", target.getDisplay());
assertEquals(CS_URL_3, target.getSystem());
assertEquals("Version 4", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.WIDER.toCode(), target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
// Test caching.
targets = myConceptMappingSvc.translate(translationRequest).getResults();
assertNotNull(targets);
assertEquals(3, targets.size());
assertTrue(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationCache());
}
});
}
@Test
public void testUsingPredicatesWithSourceSystemAndVersion1() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
/*
* Provided:
* source code
* source code system
* source code system version #1
*/
TranslationRequest translationRequest = new TranslationRequest();
translationRequest.getCodeableConcept().addCoding()
.setSystem(CS_URL)
.setCode("12345")
.setVersion("Version 1");
List<TranslateConceptResult> targets = myConceptMappingSvc.translate(translationRequest).getResults();
assertNotNull(targets);
assertEquals(1, targets.size());
assertFalse(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationCache());
TranslateConceptResult target = targets.get(0);
ourLog.info("target:\n" + target.toString());
assertEquals("34567", target.getCode());
assertEquals("Target Code 34567", target.getDisplay());
assertEquals(CS_URL_2, target.getSystem());
assertEquals("Version 2", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.EQUAL.toCode(), target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
// Test caching.
targets = myConceptMappingSvc.translate(translationRequest).getResults();
assertNotNull(targets);
assertEquals(1, targets.size());
assertTrue(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationCache());
}
});
}
@Test
public void testUsingPredicatesWithSourceSystemAndVersion3() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
/*
* Provided:
* source code
* source code system
* source code system version #3
*/
TranslationRequest translationRequest = new TranslationRequest();
translationRequest.getCodeableConcept().addCoding()
.setSystem(CS_URL)
.setCode("12345")
.setVersion("Version 3");
List<TranslateConceptResult> targets = myConceptMappingSvc.translate(translationRequest).getResults();
assertNotNull(targets);
assertEquals(2, targets.size());
assertFalse(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationCache());
TranslateConceptResult target = targets.get(0);
ourLog.info("target(0):\n" + target.toString());
assertEquals("56789", target.getCode());
assertEquals("Target Code 56789", target.getDisplay());
assertEquals(CS_URL_3, target.getSystem());
assertEquals("Version 4", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.EQUAL.toCode(), target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
target = targets.get(1);
ourLog.info("target(1):\n" + target.toString());
assertEquals("67890", target.getCode());
assertEquals("Target Code 67890", target.getDisplay());
assertEquals(CS_URL_3, target.getSystem());
assertEquals("Version 4", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.WIDER.toCode(), target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
// Test caching.
targets = myConceptMappingSvc.translate(translationRequest).getResults();
assertNotNull(targets);
assertEquals(2, targets.size());
assertTrue(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationCache());
}
});
}
@Test
public void testUsingPredicatesWithSourceValueSet() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
/*
* Provided:
* source code
* source value set
*/
TranslationRequest translationRequest = new TranslationRequest();
translationRequest.getCodeableConcept().addCoding()
.setCode("12345");
translationRequest.setSource(new UriType(VS_URL));
List<TranslateConceptResult> targets = myConceptMappingSvc.translate(translationRequest).getResults();
assertNotNull(targets);
assertEquals(3, targets.size());
assertFalse(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationCache());
TranslateConceptResult target = targets.get(0);
ourLog.info("target(0):\n" + target.toString());
assertEquals("34567", target.getCode());
assertEquals("Target Code 34567", target.getDisplay());
assertEquals(CS_URL_2, target.getSystem());
assertEquals("Version 2", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.EQUAL.toCode(), target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
target = targets.get(1);
ourLog.info("target(1):\n" + target.toString());
assertEquals("56789", target.getCode());
assertEquals("Target Code 56789", target.getDisplay());
assertEquals(CS_URL_3, target.getSystem());
assertEquals("Version 4", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.EQUAL.toCode(), target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
target = targets.get(2);
ourLog.info("target(2):\n" + target.toString());
assertEquals("67890", target.getCode());
assertEquals("Target Code 67890", target.getDisplay());
assertEquals(CS_URL_3, target.getSystem());
assertEquals("Version 4", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.WIDER.toCode(), target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
// Test caching.
targets = myConceptMappingSvc.translate(translationRequest).getResults();
assertNotNull(targets);
assertEquals(3, targets.size());
assertTrue(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationCache());
}
});
}
@Test
public void testUsingPredicatesWithTargetValueSet() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
/*
* Provided:
* source code
* target value set
*/
TranslationRequest translationRequest = new TranslationRequest();
translationRequest.getCodeableConcept().addCoding()
.setCode("12345");
translationRequest.setTarget(new UriType(VS_URL_2));
List<TranslateConceptResult> targets = myConceptMappingSvc.translate(translationRequest).getResults();
assertNotNull(targets);
assertEquals(3, targets.size());
assertFalse(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationCache());
TranslateConceptResult target = targets.get(0);
ourLog.info("target(0):\n" + target.toString());
assertEquals("34567", target.getCode());
assertEquals("Target Code 34567", target.getDisplay());
assertEquals(CS_URL_2, target.getSystem());
assertEquals("Version 2", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.EQUAL.toCode(), target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
target = targets.get(1);
ourLog.info("target(1):\n" + target.toString());
assertEquals("56789", target.getCode());
assertEquals("Target Code 56789", target.getDisplay());
assertEquals(CS_URL_3, target.getSystem());
assertEquals("Version 4", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.EQUAL.toCode(), target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
target = targets.get(2);
ourLog.info("target(2):\n" + target.toString());
assertEquals("67890", target.getCode());
assertEquals("Target Code 67890", target.getDisplay());
assertEquals(CS_URL_3, target.getSystem());
assertEquals("Version 4", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.WIDER.toCode(), target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
// Test caching.
targets = myConceptMappingSvc.translate(translationRequest).getResults();
assertNotNull(targets);
assertEquals(3, targets.size());
assertTrue(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationCache());
}
});
}
@Test
public void testWithReverse() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
/*
* Provided:
* source code
* source code system
* target code system
* reverse = true
*/
TranslationRequest translationRequest = new TranslationRequest();
translationRequest.getCodeableConcept().addCoding()
.setSystem(CS_URL_2)
.setCode("34567");
translationRequest.setTargetSystem(new UriType(CS_URL_4));
translationRequest.setReverse(true);
TranslateConceptResults elements = myConceptMappingSvc.translateWithReverse(translationRequest);
assertNotNull(elements);
assertEquals(1, elements.size());
assertFalse(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationWithReverseCache());
TranslateConceptResult element = elements.getResults().get(0);
ourLog.info("element:\n" + element.toString());
assertEquals("78901", element.getCode());
assertEquals("Source Code 78901", element.getDisplay());
assertEquals(CS_URL_4, element.getSystem());
assertEquals("Version 5", element.getSystemVersion());
assertEquals(VS_URL, element.getValueSet());
assertEquals(CM_URL, element.getConceptMapUrl());
// Test caching.
elements = myConceptMappingSvc.translateWithReverse(translationRequest);
assertNotNull(elements);
assertEquals(1, elements.size());
assertTrue(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationWithReverseCache());
}
});
}
@Test
public void testWithReverseByCodeSystemsAndSourceCodeUnmapped() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
TranslationRequest translationRequest = new TranslationRequest();
translationRequest.getCodeableConcept().addCoding()
.setSystem(CS_URL_3)
.setCode("BOGUS");
translationRequest.setTargetSystem(new UriType(CS_URL));
TranslateConceptResults elements = myConceptMappingSvc.translateWithReverse(translationRequest);
assertNotNull(elements);
assertTrue(elements.isEmpty());
}
});
}
@Test
public void testWithReverseUsingPredicatesWithCodeOnly() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
/*
* Provided:
* source code
* reverse = true
*/
TranslationRequest translationRequest = new TranslationRequest();
translationRequest.getCodeableConcept().addCoding()
.setCode("34567");
translationRequest.setReverse(true);
TranslateConceptResults elements = myConceptMappingSvc.translateWithReverse(translationRequest);
assertNotNull(elements);
assertEquals(2, elements.size());
assertFalse(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationWithReverseCache());
TranslateConceptResult element = elements.getResults().get(0);
ourLog.info("element:\n" + element.toString());
assertEquals("12345", element.getCode());
assertEquals("Source Code 12345", element.getDisplay());
assertEquals(CS_URL, element.getSystem());
assertEquals("Version 1", element.getSystemVersion());
assertEquals(VS_URL, element.getValueSet());
assertEquals(CM_URL, element.getConceptMapUrl());
element = elements.getResults().get(1);
ourLog.info("element:\n" + element.toString());
assertEquals("78901", element.getCode());
assertEquals("Source Code 78901", element.getDisplay());
assertEquals(CS_URL_4, element.getSystem());
assertEquals("Version 5", element.getSystemVersion());
assertEquals(VS_URL, element.getValueSet());
assertEquals(CM_URL, element.getConceptMapUrl());
// Test caching.
elements = myConceptMappingSvc.translateWithReverse(translationRequest);
assertNotNull(elements);
assertEquals(2, elements.size());
assertTrue(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationWithReverseCache());
}
});
}
@Test
public void testWithReverseUsingPredicatesWithSourceAndTargetSystem1() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
/*
* Provided:
* source code
* source code system
* target code system #1
* reverse = true
*/
TranslationRequest translationRequest = new TranslationRequest();
translationRequest.getCodeableConcept().addCoding()
.setSystem(CS_URL_2)
.setCode("34567");
translationRequest.setTargetSystem(new UriType(CS_URL));
translationRequest.setReverse(true);
TranslateConceptResults elements = myConceptMappingSvc.translateWithReverse(translationRequest);
assertNotNull(elements);
assertEquals(1, elements.size());
assertFalse(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationWithReverseCache());
TranslateConceptResult element = elements.getResults().get(0);
ourLog.info("element:\n" + element.toString());
assertEquals("12345", element.getCode());
assertEquals("Source Code 12345", element.getDisplay());
assertEquals(CS_URL, element.getSystem());
assertEquals("Version 1", element.getSystemVersion());
assertEquals(VS_URL, element.getValueSet());
assertEquals(CM_URL, element.getConceptMapUrl());
// Test caching.
elements = myConceptMappingSvc.translateWithReverse(translationRequest);
assertNotNull(elements);
assertEquals(1, elements.size());
assertTrue(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationWithReverseCache());
}
});
}
@Test
public void testWithReverseUsingPredicatesWithSourceAndTargetSystem4() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
/*
* Provided:
* source code
* source code system
* target code system #4
* reverse = true
*/
TranslationRequest translationRequest = new TranslationRequest();
translationRequest.getCodeableConcept().addCoding()
.setSystem(CS_URL_2)
.setCode("34567");
translationRequest.setTargetSystem(new UriType(CS_URL_4));
translationRequest.setReverse(true);
TranslateConceptResults elements = myConceptMappingSvc.translateWithReverse(translationRequest);
assertNotNull(elements);
assertEquals(1, elements.size());
assertFalse(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationWithReverseCache());
TranslateConceptResult element = elements.getResults().get(0);
ourLog.info("element:\n" + element.toString());
assertEquals("78901", element.getCode());
assertEquals("Source Code 78901", element.getDisplay());
assertEquals(CS_URL_4, element.getSystem());
assertEquals("Version 5", element.getSystemVersion());
assertEquals(VS_URL, element.getValueSet());
assertEquals(CM_URL, element.getConceptMapUrl());
// Test caching.
elements = myConceptMappingSvc.translateWithReverse(translationRequest);
assertNotNull(elements);
assertEquals(1, elements.size());
assertTrue(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationWithReverseCache());
}
});
}
@Test
public void testWithReverseUsingPredicatesWithSourceSystem() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
/*
* Provided:
* source code
* source code system
* reverse = true
*/
TranslationRequest translationRequest = new TranslationRequest();
translationRequest.getCodeableConcept().addCoding()
.setSystem(CS_URL_2)
.setCode("34567");
translationRequest.setReverse(true);
TranslateConceptResults elements = myConceptMappingSvc.translateWithReverse(translationRequest);
assertNotNull(elements);
assertEquals(2, elements.size());
assertFalse(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationWithReverseCache());
TranslateConceptResult element = elements.getResults().get(0);
ourLog.info("element:\n" + element.toString());
assertEquals("12345", element.getCode());
assertEquals("Source Code 12345", element.getDisplay());
assertEquals(CS_URL, element.getSystem());
assertEquals("Version 1", element.getSystemVersion());
assertEquals(VS_URL, element.getValueSet());
assertEquals(CM_URL, element.getConceptMapUrl());
element = elements.getResults().get(1);
ourLog.info("element:\n" + element.toString());
assertEquals("78901", element.getCode());
assertEquals("Source Code 78901", element.getDisplay());
assertEquals(CS_URL_4, element.getSystem());
assertEquals("Version 5", element.getSystemVersion());
assertEquals(VS_URL, element.getValueSet());
assertEquals(CM_URL, element.getConceptMapUrl());
// Test caching.
elements = myConceptMappingSvc.translateWithReverse(translationRequest);
assertNotNull(elements);
assertEquals(2, elements.size());
assertTrue(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationWithReverseCache());
}
});
}
@Test
public void testWithReverseUsingPredicatesWithSourceSystemAndVersion() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
/*
* Provided:
* source code
* source code system
* source code system version
* reverse = true
*/
TranslationRequest translationRequest = new TranslationRequest();
translationRequest.getCodeableConcept().addCoding()
.setSystem(CS_URL_2)
.setCode("34567")
.setVersion("Version 2");
translationRequest.setReverse(true);
TranslateConceptResults elements = myConceptMappingSvc.translateWithReverse(translationRequest);
assertNotNull(elements);
assertEquals(2, elements.size());
assertFalse(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationWithReverseCache());
TranslateConceptResult element = elements.getResults().get(0);
ourLog.info("element:\n" + element.toString());
assertEquals("12345", element.getCode());
assertEquals("Source Code 12345", element.getDisplay());
assertEquals(CS_URL, element.getSystem());
assertEquals("Version 1", element.getSystemVersion());
assertEquals(VS_URL, element.getValueSet());
assertEquals(CM_URL, element.getConceptMapUrl());
element = elements.getResults().get(1);
ourLog.info("element:\n" + element.toString());
assertEquals("78901", element.getCode());
assertEquals("Source Code 78901", element.getDisplay());
assertEquals(CS_URL_4, element.getSystem());
assertEquals("Version 5", element.getSystemVersion());
assertEquals(VS_URL, element.getValueSet());
assertEquals(CM_URL, element.getConceptMapUrl());
// Test caching.
elements = myConceptMappingSvc.translateWithReverse(translationRequest);
assertNotNull(elements);
assertEquals(2, elements.size());
assertTrue(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationWithReverseCache());
}
});
}
@Test
public void testWithReverseUsingPredicatesWithSourceValueSet() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
/*
* Provided:
* source code
* source value set
* reverse = true
*/
TranslationRequest translationRequest = new TranslationRequest();
translationRequest.getCodeableConcept().addCoding()
.setCode("34567");
translationRequest.setSource(new UriType(VS_URL_2));
translationRequest.setReverse(true);
TranslateConceptResults elements = myConceptMappingSvc.translateWithReverse(translationRequest);
assertNotNull(elements);
assertEquals(2, elements.size());
assertFalse(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationWithReverseCache());
TranslateConceptResult element = elements.getResults().get(0);
ourLog.info("element:\n" + element.toString());
assertEquals("12345", element.getCode());
assertEquals("Source Code 12345", element.getDisplay());
assertEquals(CS_URL, element.getSystem());
assertEquals("Version 1", element.getSystemVersion());
assertEquals(VS_URL, element.getValueSet());
assertEquals(CM_URL, element.getConceptMapUrl());
element = elements.getResults().get(1);
ourLog.info("element:\n" + element.toString());
assertEquals("78901", element.getCode());
assertEquals("Source Code 78901", element.getDisplay());
assertEquals(CS_URL_4, element.getSystem());
assertEquals("Version 5", element.getSystemVersion());
assertEquals(VS_URL, element.getValueSet());
assertEquals(CM_URL, element.getConceptMapUrl());
// Test caching.
elements = myConceptMappingSvc.translateWithReverse(translationRequest);
assertNotNull(elements);
assertEquals(2, elements.size());
assertTrue(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationWithReverseCache());
}
});
}
@Test
public void testWithReverseUsingPredicatesWithTargetValueSet() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
/*
* Provided:
* source code
* target value set
* reverse = true
*/
TranslationRequest translationRequest = new TranslationRequest();
translationRequest.getCodeableConcept().addCoding()
.setCode("34567");
translationRequest.setTarget(new UriType(VS_URL));
translationRequest.setReverse(true);
TranslateConceptResults elements = myConceptMappingSvc.translateWithReverse(translationRequest);
assertNotNull(elements);
assertEquals(2, elements.size());
assertFalse(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationWithReverseCache());
TranslateConceptResult element = elements.getResults().get(0);
ourLog.info("element:\n" + element.toString());
assertEquals("12345", element.getCode());
assertEquals("Source Code 12345", element.getDisplay());
assertEquals(CS_URL, element.getSystem());
assertEquals("Version 1", element.getSystemVersion());
assertEquals(VS_URL, element.getValueSet());
assertEquals(CM_URL, element.getConceptMapUrl());
element = elements.getResults().get(1);
ourLog.info("element:\n" + element.toString());
assertEquals("78901", element.getCode());
assertEquals("Source Code 78901", element.getDisplay());
assertEquals(CS_URL_4, element.getSystem());
assertEquals("Version 5", element.getSystemVersion());
assertEquals(VS_URL, element.getValueSet());
assertEquals(CM_URL, element.getConceptMapUrl());
// Test caching.
elements = myConceptMappingSvc.translateWithReverse(translationRequest);
assertNotNull(elements);
assertEquals(2, elements.size());
assertTrue(TermConceptMappingSvcImpl.isOurLastResultsFromTranslationWithReverseCache());
}
});
}
@Test
public void testDuplicateConceptMapUrls() {
createAndPersistConceptMap();
try {
createAndPersistConceptMap();
fail();
} catch (UnprocessableEntityException e) {
assertEquals(Msg.code(840) + "Can not create multiple ConceptMap resources with ConceptMap.url \"http://example.com/my_concept_map\", already have one with resource ID: ConceptMap/" + myConceptMapId.getIdPart(), e.getMessage());
}
}
@Test
public void testDuplicateConceptMapUrlsAndVersions() {
createAndPersistConceptMap("v1");
try {
createAndPersistConceptMap("v1");
fail();
} catch (UnprocessableEntityException e) {
assertEquals(Msg.code(841) + "Can not create multiple ConceptMap resources with ConceptMap.url \"http://example.com/my_concept_map\" and ConceptMap.version \"v1\", already have one with resource ID: ConceptMap/" + myConceptMapId.getIdPart(), e.getMessage());
}
}
@Test
public void testStoreTermConceptMapAndChildren() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
Pageable page = PageRequest.of(0, 1);
List<TermConceptMap> optionalConceptMap = myTermConceptMapDao.getTermConceptMapEntitiesByUrlOrderByMostRecentUpdate(page, CM_URL);
assertEquals(1, optionalConceptMap.size());
TermConceptMap conceptMap = optionalConceptMap.get(0);
ourLog.info("ConceptMap:\n" + conceptMap.toString());
assertEquals(VS_URL, conceptMap.getSource());
assertEquals(VS_URL_2, conceptMap.getTarget());
assertEquals(CM_URL, conceptMap.getUrl());
assertEquals(3, conceptMap.getConceptMapGroups().size());
TermConceptMapGroup group = conceptMap.getConceptMapGroups().get(0);
ourLog.info("ConceptMap.group(0):\n" + group.toString());
assertEquals(CS_URL, group.getSource());
assertEquals("Version 1", group.getSourceVersion());
assertEquals(VS_URL, group.getSourceValueSet());
assertEquals(CS_URL_2, group.getTarget());
assertEquals("Version 2", group.getTargetVersion());
assertEquals(VS_URL_2, group.getTargetValueSet());
assertEquals(CM_URL, group.getConceptMapUrl());
assertEquals(2, group.getConceptMapGroupElements().size());
TermConceptMapGroupElement element = group.getConceptMapGroupElements().get(0);
ourLog.info("ConceptMap.group(0).element(0):\n" + element.toString());
assertEquals("12345", element.getCode());
assertEquals("Source Code 12345", element.getDisplay());
assertEquals(CS_URL, element.getSystem());
assertEquals("Version 1", element.getSystemVersion());
assertEquals(VS_URL, element.getValueSet());
assertEquals(CM_URL, element.getConceptMapUrl());
assertEquals(1, element.getConceptMapGroupElementTargets().size());
TermConceptMapGroupElementTarget target = element.getConceptMapGroupElementTargets().get(0);
ourLog.info("ConceptMap.group(0).element(0).target(0):\n" + target.toString());
assertEquals("34567", target.getCode());
assertEquals("Target Code 34567", target.getDisplay());
assertEquals(CS_URL_2, target.getSystem());
assertEquals("Version 2", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.EQUAL, target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
element = group.getConceptMapGroupElements().get(1);
ourLog.info("ConceptMap.group(0).element(1):\n" + element.toString());
assertEquals("23456", element.getCode());
assertEquals("Source Code 23456", element.getDisplay());
assertEquals(CS_URL, element.getSystem());
assertEquals("Version 1", element.getSystemVersion());
assertEquals(VS_URL, element.getValueSet());
assertEquals(CM_URL, element.getConceptMapUrl());
assertEquals(2, element.getConceptMapGroupElementTargets().size());
target = element.getConceptMapGroupElementTargets().get(0);
ourLog.info("ConceptMap.group(0).element(1).target(0):\n" + target.toString());
assertEquals("45678", target.getCode());
assertEquals("Target Code 45678", target.getDisplay());
assertEquals(CS_URL_2, target.getSystem());
assertEquals("Version 2", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.WIDER, target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
// We had deliberately added a duplicate, and here it is...
target = element.getConceptMapGroupElementTargets().get(1);
ourLog.info("ConceptMap.group(0).element(1).target(1):\n" + target.toString());
assertEquals("45678", target.getCode());
assertEquals("Target Code 45678", target.getDisplay());
assertEquals(CS_URL_2, target.getSystem());
assertEquals("Version 2", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.WIDER, target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
group = conceptMap.getConceptMapGroups().get(1);
ourLog.info("ConceptMap.group(1):\n" + group.toString());
assertEquals(CS_URL, group.getSource());
assertEquals("Version 3", group.getSourceVersion());
assertEquals(CS_URL_3, group.getTarget());
assertEquals("Version 4", group.getTargetVersion());
assertEquals(CM_URL, group.getConceptMapUrl());
assertEquals(1, group.getConceptMapGroupElements().size());
element = group.getConceptMapGroupElements().get(0);
ourLog.info("ConceptMap.group(1).element(0):\n" + element.toString());
assertEquals("12345", element.getCode());
assertEquals("Source Code 12345", element.getDisplay());
assertEquals(CS_URL, element.getSystem());
assertEquals("Version 3", element.getSystemVersion());
assertEquals(VS_URL, element.getValueSet());
assertEquals(CM_URL, element.getConceptMapUrl());
assertEquals(2, element.getConceptMapGroupElementTargets().size());
target = element.getConceptMapGroupElementTargets().get(0);
ourLog.info("ConceptMap.group(1).element(0).target(0):\n" + target.toString());
assertEquals("56789", target.getCode());
assertEquals("Target Code 56789", target.getDisplay());
assertEquals(CS_URL_3, target.getSystem());
assertEquals("Version 4", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.EQUAL, target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
target = element.getConceptMapGroupElementTargets().get(1);
ourLog.info("ConceptMap.group(1).element(0).target(1):\n" + target.toString());
assertEquals("67890", target.getCode());
assertEquals("Target Code 67890", target.getDisplay());
assertEquals(CS_URL_3, target.getSystem());
assertEquals("Version 4", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.WIDER, target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
group = conceptMap.getConceptMapGroups().get(2);
ourLog.info("ConceptMap.group(2):\n" + group.toString());
assertEquals(CS_URL_4, group.getSource());
assertEquals("Version 5", group.getSourceVersion());
assertEquals(CS_URL_2, group.getTarget());
assertEquals("Version 2", group.getTargetVersion());
assertEquals(CM_URL, group.getConceptMapUrl());
assertEquals(1, group.getConceptMapGroupElements().size());
element = group.getConceptMapGroupElements().get(0);
ourLog.info("ConceptMap.group(2).element(0):\n" + element.toString());
assertEquals("78901", element.getCode());
assertEquals("Source Code 78901", element.getDisplay());
assertEquals(CS_URL_4, element.getSystem());
assertEquals("Version 5", element.getSystemVersion());
assertEquals(VS_URL, element.getValueSet());
assertEquals(CM_URL, element.getConceptMapUrl());
assertEquals(1, element.getConceptMapGroupElementTargets().size());
target = element.getConceptMapGroupElementTargets().get(0);
ourLog.info("ConceptMap.group(2).element(0).target(0):\n" + target.toString());
assertEquals("34567", target.getCode());
assertEquals("Target Code 34567", target.getDisplay());
assertEquals(CS_URL_2, target.getSystem());
assertEquals("Version 2", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.NARROWER, target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
}
});
}
@Test
public void testStoreTermConceptMapAndChildrenWithClientAssignedId() {
createAndPersistConceptMap();
ConceptMap conceptMap = myConceptMapDao.read(myConceptMapId);
ourLog.info("ConceptMap:\n" + myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(conceptMap));
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
Pageable page = PageRequest.of(0, 1);
List<TermConceptMap> optionalConceptMap = myTermConceptMapDao.getTermConceptMapEntitiesByUrlOrderByMostRecentUpdate(page, CM_URL);
assertEquals(1, optionalConceptMap.size());
TermConceptMap conceptMap = optionalConceptMap.get(0);
ourLog.info("ConceptMap:\n" + conceptMap.toString());
assertEquals(VS_URL, conceptMap.getSource());
assertEquals(VS_URL_2, conceptMap.getTarget());
assertEquals(CM_URL, conceptMap.getUrl());
assertEquals(3, conceptMap.getConceptMapGroups().size());
TermConceptMapGroup group = conceptMap.getConceptMapGroups().get(0);
ourLog.info("ConceptMap.group(0):\n" + group.toString());
assertEquals(CS_URL, group.getSource());
assertEquals("Version 1", group.getSourceVersion());
assertEquals(VS_URL, group.getSourceValueSet());
assertEquals(CS_URL_2, group.getTarget());
assertEquals("Version 2", group.getTargetVersion());
assertEquals(VS_URL_2, group.getTargetValueSet());
assertEquals(CM_URL, group.getConceptMapUrl());
assertEquals(2, group.getConceptMapGroupElements().size());
TermConceptMapGroupElement element = group.getConceptMapGroupElements().get(0);
ourLog.info("ConceptMap.group(0).element(0):\n" + element.toString());
assertEquals("12345", element.getCode());
assertEquals("Source Code 12345", element.getDisplay());
assertEquals(CS_URL, element.getSystem());
assertEquals("Version 1", element.getSystemVersion());
assertEquals(VS_URL, element.getValueSet());
assertEquals(CM_URL, element.getConceptMapUrl());
assertEquals(1, element.getConceptMapGroupElementTargets().size());
TermConceptMapGroupElementTarget target = element.getConceptMapGroupElementTargets().get(0);
ourLog.info("ConceptMap.group(0).element(0).target(0):\n" + target.toString());
assertEquals("34567", target.getCode());
assertEquals("Target Code 34567", target.getDisplay());
assertEquals(CS_URL_2, target.getSystem());
assertEquals("Version 2", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.EQUAL, target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
element = group.getConceptMapGroupElements().get(1);
ourLog.info("ConceptMap.group(0).element(1):\n" + element.toString());
assertEquals("23456", element.getCode());
assertEquals("Source Code 23456", element.getDisplay());
assertEquals(CS_URL, element.getSystem());
assertEquals("Version 1", element.getSystemVersion());
assertEquals(VS_URL, element.getValueSet());
assertEquals(CM_URL, element.getConceptMapUrl());
assertEquals(2, element.getConceptMapGroupElementTargets().size());
target = element.getConceptMapGroupElementTargets().get(0);
ourLog.info("ConceptMap.group(0).element(1).target(0):\n" + target.toString());
assertEquals("45678", target.getCode());
assertEquals("Target Code 45678", target.getDisplay());
assertEquals(CS_URL_2, target.getSystem());
assertEquals("Version 2", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.WIDER, target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
// We had deliberately added a duplicate, and here it is...
target = element.getConceptMapGroupElementTargets().get(1);
ourLog.info("ConceptMap.group(0).element(1).target(1):\n" + target.toString());
assertEquals("45678", target.getCode());
assertEquals("Target Code 45678", target.getDisplay());
assertEquals(CS_URL_2, target.getSystem());
assertEquals("Version 2", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.WIDER, target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
group = conceptMap.getConceptMapGroups().get(1);
ourLog.info("ConceptMap.group(1):\n" + group.toString());
assertEquals(CS_URL, group.getSource());
assertEquals("Version 3", group.getSourceVersion());
assertEquals(CS_URL_3, group.getTarget());
assertEquals("Version 4", group.getTargetVersion());
assertEquals(CM_URL, group.getConceptMapUrl());
assertEquals(1, group.getConceptMapGroupElements().size());
element = group.getConceptMapGroupElements().get(0);
ourLog.info("ConceptMap.group(1).element(0):\n" + element.toString());
assertEquals("12345", element.getCode());
assertEquals("Source Code 12345", element.getDisplay());
assertEquals(CS_URL, element.getSystem());
assertEquals("Version 3", element.getSystemVersion());
assertEquals(VS_URL, element.getValueSet());
assertEquals(CM_URL, element.getConceptMapUrl());
assertEquals(2, element.getConceptMapGroupElementTargets().size());
target = element.getConceptMapGroupElementTargets().get(0);
ourLog.info("ConceptMap.group(1).element(0).target(0):\n" + target.toString());
assertEquals("56789", target.getCode());
assertEquals("Target Code 56789", target.getDisplay());
assertEquals(CS_URL_3, target.getSystem());
assertEquals("Version 4", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.EQUAL, target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
target = element.getConceptMapGroupElementTargets().get(1);
ourLog.info("ConceptMap.group(1).element(0).target(1):\n" + target.toString());
assertEquals("67890", target.getCode());
assertEquals("Target Code 67890", target.getDisplay());
assertEquals(CS_URL_3, target.getSystem());
assertEquals("Version 4", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.WIDER, target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
group = conceptMap.getConceptMapGroups().get(2);
ourLog.info("ConceptMap.group(2):\n" + group.toString());
assertEquals(CS_URL_4, group.getSource());
assertEquals("Version 5", group.getSourceVersion());
assertEquals(CS_URL_2, group.getTarget());
assertEquals("Version 2", group.getTargetVersion());
assertEquals(CM_URL, group.getConceptMapUrl());
assertEquals(1, group.getConceptMapGroupElements().size());
element = group.getConceptMapGroupElements().get(0);
ourLog.info("ConceptMap.group(2).element(0):\n" + element.toString());
assertEquals("78901", element.getCode());
assertEquals("Source Code 78901", element.getDisplay());
assertEquals(CS_URL_4, element.getSystem());
assertEquals("Version 5", element.getSystemVersion());
assertEquals(VS_URL, element.getValueSet());
assertEquals(CM_URL, element.getConceptMapUrl());
assertEquals(1, element.getConceptMapGroupElementTargets().size());
target = element.getConceptMapGroupElementTargets().get(0);
ourLog.info("ConceptMap.group(2).element(0).target(0):\n" + target.toString());
assertEquals("34567", target.getCode());
assertEquals("Target Code 34567", target.getDisplay());
assertEquals(CS_URL_2, target.getSystem());
assertEquals("Version 2", target.getSystemVersion());
assertEquals(Enumerations.ConceptMapEquivalence.NARROWER, target.getEquivalence());
assertEquals(VS_URL_2, target.getValueSet());
assertEquals(CM_URL, target.getConceptMapUrl());
}
});
}
private void createAndPersistConceptMap() {
ConceptMap conceptMap = createConceptMap();
conceptMap.setId("ConceptMap/cm");
persistConceptMap(conceptMap, HttpVerb.POST);
}
private void createAndPersistConceptMap(String version) {
ConceptMap conceptMap = createConceptMap();
conceptMap.setId("ConceptMap/cm");
conceptMap.setVersion(version);
persistConceptMap(conceptMap, HttpVerb.POST);
}
@SuppressWarnings("EnumSwitchStatementWhichMissesCases")
private void persistConceptMap(ConceptMap theConceptMap, HttpVerb theVerb) {
switch (theVerb) {
case POST:
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
myConceptMapId = myConceptMapDao.create(theConceptMap, mySrd).getId().toUnqualifiedVersionless();
}
});
break;
case PUT:
new TransactionTemplate(myTxManager).execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(@Nonnull TransactionStatus theStatus) {
myConceptMapId = myConceptMapDao.update(theConceptMap, mySrd).getId().toUnqualifiedVersionless();
}
});
break;
default:
throw new IllegalArgumentException("HTTP verb is not supported: " + theVerb);
}
}
}
| 39.791693 | 261 | 0.745876 |
922facec2296744f0680ca646929b169436a70b8 | 5,088 | package com.hbm.blocks.bomb;
import java.util.Random;
import com.hbm.blocks.ModBlocks;
import com.hbm.potion.HbmPotion;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFire;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.init.Blocks;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class Balefire extends BlockFire {
public Balefire(String s) {
super();
this.setUnlocalizedName(s);
this.setRegistryName(s);
this.setCreativeTab(null);
ModBlocks.ALL_BLOCKS.add(this);
}
public void updateTick(World worldIn, BlockPos pos, IBlockState state, Random rand) {
if (worldIn.getGameRules().getBoolean("doFireTick")) {
if (!worldIn.isAreaLoaded(pos, 2))
return; // Forge: prevent loading unloaded chunks when spreading
// fire
if (!this.canPlaceBlockAt(worldIn, pos)) {
worldIn.setBlockToAir(pos);
}
Block block = worldIn.getBlockState(pos.down()).getBlock();
boolean flag = block.isFireSource(worldIn, pos.down(), EnumFacing.UP);
int i = ((Integer) state.getValue(AGE)).intValue();
/* if (!flag && worldIn.isRaining() && this.canDie(worldIn, pos) && rand.nextFloat() < 0.2F + (float)i * 0.03F)
{
worldIn.setBlockToAir(pos);
}
else*/
{
/* if (i < 15)
{
state = state.withProperty(AGE, Integer.valueOf(i + rand.nextInt(3) / 2));
worldIn.setBlockState(pos, state, 4);
}*/
worldIn.scheduleUpdate(pos, this, this.tickRate(worldIn) + rand.nextInt(10));
if (!flag) {
if (!this.canNeighborCatchFire(worldIn, pos)) {
if (!worldIn.getBlockState(pos.down()).isSideSolid(worldIn, pos.down(), EnumFacing.UP) || i > 3) {
worldIn.setBlockToAir(pos);
}
return;
}
/* if (!this.canCatchFire(worldIn, pos.down(), EnumFacing.UP) && i == 15 && rand.nextInt(4) == 0)
{
worldIn.setBlockToAir(pos);
return;
}*/
}
boolean flag1 = worldIn.isBlockinHighHumidity(pos);
int j = 0;
if (flag1) {
j = -50;
}
this.tryCatchFire(worldIn, pos.east(), 300 + j, rand, i, EnumFacing.WEST);
this.tryCatchFire(worldIn, pos.west(), 300 + j, rand, i, EnumFacing.EAST);
this.tryCatchFire(worldIn, pos.down(), 250 + j, rand, i, EnumFacing.UP);
this.tryCatchFire(worldIn, pos.up(), 250 + j, rand, i, EnumFacing.DOWN);
this.tryCatchFire(worldIn, pos.north(), 300 + j, rand, i, EnumFacing.SOUTH);
this.tryCatchFire(worldIn, pos.south(), 300 + j, rand, i, EnumFacing.NORTH);
for (int k = -1; k <= 1; ++k) {
for (int l = -1; l <= 1; ++l) {
for (int i1 = -1; i1 <= 4; ++i1) {
if (k != 0 || i1 != 0 || l != 0) {
int j1 = 100;
if (i1 > 1) {
j1 += (i1 - 1) * 100;
}
BlockPos blockpos = pos.add(k, i1, l);
int k1 = this.getNeighborEncouragement(worldIn, blockpos);
if (k1 > 0) {
int l1 = (k1 + 40 + worldIn.getDifficulty().getDifficultyId() * 7) / (i + 30);
/* if (flag1)
{
l1 /= 2;
}*/
if (l1 > 0 && rand.nextInt(j1) <= l1/* && (!worldIn.isRaining() || !this.canDie(worldIn, blockpos))*/) {
int i2 = i + rand.nextInt(5) / 4;
if (i2 > 15) {
i2 = 15;
}
worldIn.setBlockState(blockpos, state.withProperty(AGE, Integer.valueOf(i2)), 3);
}
}
}
}
}
}
}
}
}
private boolean canNeighborCatchFire(World worldIn, BlockPos pos) {
for (EnumFacing enumfacing : EnumFacing.values()) {
if (this.canCatchFire(worldIn, pos.offset(enumfacing), enumfacing.getOpposite())) {
return true;
}
}
return false;
}
private int getNeighborEncouragement(World worldIn, BlockPos pos) {
if (!worldIn.isAirBlock(pos)) {
return 0;
} else {
int i = 0;
for (EnumFacing enumfacing : EnumFacing.values()) {
i = Math.max(worldIn.getBlockState(pos.offset(enumfacing)).getBlock().getFireSpreadSpeed(worldIn, pos.offset(enumfacing), enumfacing.getOpposite()), i);
}
return i;
}
}
private void tryCatchFire(World p_149841_1_, BlockPos pos, int p_149841_5_, Random p_149841_6_, int p_149841_7_, EnumFacing face) {
int j1 = p_149841_1_.getBlockState(pos).getBlock().getFlammability(p_149841_1_, pos, face);
if (p_149841_6_.nextInt(p_149841_5_) < j1) {
boolean flag = p_149841_1_.getBlockState(pos).getBlock() == Blocks.TNT;
p_149841_1_.setBlockState(pos, this.getDefaultState().withProperty(AGE, 15), 3);
if (flag) {
Blocks.TNT.onBlockDestroyedByPlayer(p_149841_1_, pos, p_149841_1_.getBlockState(pos));
}
}
}
@Override
public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, IBlockState state, Entity entityIn) {
entityIn.setFire(10);
if (entityIn instanceof EntityLivingBase)
((EntityLivingBase) entityIn).addPotionEffect(new PotionEffect(HbmPotion.radiation, 5 * 20, 9));
}
}
| 29.241379 | 156 | 0.637186 |
bea7987dbaac2955dfe501efcab93fb59b819f19 | 1,353 |
package org.proteosuite.model;
import java.util.LinkedList;
/**
*
* @author SPerkins
*/
public class Spectrum extends LinkedList<MzIntensityPair> {
private MzIntensityPair basePeak = new MzIntensityPair(0.0, 0.0);
private double retentionTimeInSeconds = 0.0;
private int spectrumIndex = -1;
private String spectrumID = null;
public int getSpectraCount() {
return super.size();
}
public void setBasePeak(MzIntensityPair basePeak) {
this.basePeak = basePeak;
}
public void setRetentionTimeInMinutes(double minutes) {
this.retentionTimeInSeconds = minutes * 60;
}
public void setRetentionTimeInSeconds(double seconds) {
this.retentionTimeInSeconds = seconds;
}
public double getRetentionTimeInSeconds() {
return retentionTimeInSeconds;
}
public MzIntensityPair getBasePeak() {
return basePeak;
}
public void setSpectrumIndex(int spectrumIndex) {
this.spectrumIndex = spectrumIndex;
}
public int getSpectrumIndex() {
return spectrumIndex;
}
public void setSpectrumID(String spectrumID) {
this.spectrumID = spectrumID;
}
public String getSpectrumID() {
return this.spectrumID;
}
}
| 24.6 | 70 | 0.633407 |
de2ac2f38d28dcc78d79846dadee14d5e2018a42 | 10,799 | /*
* Copyright 2012 International Business Machines Corp.
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. 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.ibm.jbatch.container.impl;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.ibm.jbatch.container.artifact.proxy.SkipProcessListenerProxy;
import com.ibm.jbatch.container.artifact.proxy.SkipReadListenerProxy;
import com.ibm.jbatch.container.artifact.proxy.SkipWriteListenerProxy;
import com.ibm.jbatch.container.exception.BatchContainerRuntimeException;
import com.ibm.jbatch.jsl.model.Chunk;
import com.ibm.jbatch.jsl.model.ExceptionClassFilter;
public class SkipHandler {
/**
*
* Logic for handling skipped records.
*
*/
private static final String className = SkipHandler.class.getName();
private static Logger logger = Logger.getLogger(SkipHandler.class.getPackage().getName());
public static final String SKIP_COUNT = "skip-limit";
public static final String SKIP_INCLUDE_EX = "include class";
public static final String SKIP_EXCLUDE_EX = "exclude class";
private List<SkipProcessListenerProxy> _skipProcessListener = null;
private List<SkipReadListenerProxy> _skipReadListener = null;
private List<SkipWriteListenerProxy> _skipWriteListener = null;
private long _jobId = 0;
private String _stepId = null;
private Set<String> _skipIncludeExceptions = null;
private Set<String> _skipExcludeExceptions = null;
private int _skipLimit = 0;
private long _skipCount = 0;
public SkipHandler(Chunk chunk, long l, String stepId)
{
_jobId = l;
_stepId = stepId;
initialize(chunk);
}
/**
* Add the user-defined SkipReadListeners.
*
*/
public void addSkipReadListener(List<SkipReadListenerProxy> skipReadListener)
{
_skipReadListener = skipReadListener;
}
/**
* Add the user-defined SkipWriteListeners.
*
*/
public void addSkipWriteListener(List<SkipWriteListenerProxy> skipWriteListener)
{
_skipWriteListener = skipWriteListener;
}
/**
* Add the user-defined SkipReadListeners.
*
*/
public void addSkipProcessListener(List<SkipProcessListenerProxy> skipProcessListener)
{
_skipProcessListener = skipProcessListener;
}
/**
* Read the skip exception lists from the BDS props.
*/
private void initialize(Chunk chunk)
{
final String mName = "initialize";
if(logger.isLoggable(Level.FINER))
logger.entering(className, mName);
try
{
if (chunk.getSkipLimit() != null){
_skipLimit = Integer.parseInt(chunk.getSkipLimit());
}
}
catch (NumberFormatException nfe)
{
throw new RuntimeException("NumberFormatException reading " + SKIP_COUNT, nfe);
}
if (_skipLimit > 0)
{
// Read the include/exclude exceptions.
_skipIncludeExceptions = new HashSet<String>();
_skipExcludeExceptions = new HashSet<String>();
//boolean done = false;
List<String> includeEx = new ArrayList<String>();
List<String> excludeEx = new ArrayList<String>();
if (chunk.getSkippableExceptionClasses() != null) {
if (chunk.getSkippableExceptionClasses().getIncludeList() != null) {
List<ExceptionClassFilter.Include> includes = chunk.getSkippableExceptionClasses().getIncludeList();
for (ExceptionClassFilter.Include include : includes){
_skipIncludeExceptions.add(include.getClazz().trim());
logger.finer("SKIPHANDLE: include: " + include.getClazz().trim());
}
if (_skipIncludeExceptions.size() == 0){
logger.finer("SKIPHANDLE: include element not present");
}
}
}
if (chunk.getSkippableExceptionClasses() != null) {
if (chunk.getSkippableExceptionClasses().getExcludeList() != null) {
List<ExceptionClassFilter.Exclude> excludes = chunk.getSkippableExceptionClasses().getExcludeList();
for (ExceptionClassFilter.Exclude exclude : excludes){
_skipExcludeExceptions.add(exclude.getClazz().trim());
logger.finer("SKIPHANDLE: exclude: " + exclude.getClazz().trim());
}
if (_skipExcludeExceptions.size() == 0){
logger.finer("SKIPHANDLE: exclude element not present");
}
}
}
if (logger.isLoggable(Level.FINE))
logger.logp(Level.FINE, className, mName,
"added include exception " + includeEx
+ "; added exclude exception " + excludeEx);
}
if(logger.isLoggable(Level.FINER))
logger.exiting(className, mName, this.toString());
}
/**
* Handle exception from a read failure.
*/
public void handleExceptionRead(Exception e)
{
final String mName = "handleException";
logger.finer("SKIPHANDLE: in skiphandler handle exception on a read");
if(logger.isLoggable(Level.FINER))
logger.logp(Level.FINE, className, mName, e.getClass().getName() + "; " + this.toString());
if (!isSkipLimitReached() && isSkippable(e))
{
// Skip it. Log it. Call the SkipListener.
++_skipCount;
logSkip(e);
if (_skipReadListener != null) {
for (SkipReadListenerProxy skipReadListenerProxy : _skipReadListener) {
skipReadListenerProxy.onSkipReadItem(e);
}
}
}
else
{
// No skip. Throw it back. don't throw it back - we might want to retry ...
if(logger.isLoggable(Level.FINER))
logger.logp(Level.FINE, className, mName, "No skip. Rethrow", e);
throw new BatchContainerRuntimeException(e);
}
if(logger.isLoggable(Level.FINER))
logger.exiting(className, mName, e);
}
/**
* Handle exception from a process failure.
*/
public void handleExceptionWithRecordProcess(Exception e, Object w)
{
final String mName = "handleExceptionWithRecordProcess";
if(logger.isLoggable(Level.FINER))
logger.logp(Level.FINE, className, mName, e.getClass().getName() + "; " + this.toString());
if (!isSkipLimitReached() && isSkippable(e))
{
// Skip it. Log it. Call the SkipProcessListener.
++_skipCount;
logSkip(e);
if (_skipProcessListener != null) {
for (SkipProcessListenerProxy skipProcessListenerProxy : _skipProcessListener) {
skipProcessListenerProxy.onSkipProcessItem(w, e);
}
}
}
else
{
// No skip. Throw it back.
if(logger.isLoggable(Level.FINER))
logger.logp(Level.FINE, className, mName, "No skip. Rethrow ", e);
throw new BatchContainerRuntimeException(e);
}
}
/**
* Handle exception from a write failure.
*/
public void handleExceptionWithRecordListWrite(Exception e, List<?> items)
{
final String mName = "handleExceptionWithRecordListWrite(Exception, List<?>)";
if(logger.isLoggable(Level.FINER))
logger.logp(Level.FINE, className, mName, e.getClass().getName() + "; " + this.toString());
if (!isSkipLimitReached() && isSkippable(e))
{
// Skip it. Log it. Call the SkipListener.
++_skipCount;
logSkip(e);
if (_skipWriteListener != null) {
for (SkipWriteListenerProxy skipWriteListenerProxy : _skipWriteListener) {
skipWriteListenerProxy.onSkipWriteItem(items, e);
}
}
}
else
{
System.out.println("## NO SKIP");
// No skip. Throw it back. - No, exit without throwing
if(logger.isLoggable(Level.FINER))
logger.logp(Level.FINE, className, mName, "No skip. Rethrow ", e);
throw new BatchContainerRuntimeException(e);
}
}
/**
* Check the skipCount and skippable exception lists to determine whether
* the given Exception is skippable.
*/
private boolean isSkippable(Exception e)
{
final String mName = "isSkippable";
String exClassName = e.getClass().getName();
boolean retVal = containsSkippable(_skipIncludeExceptions, e) && !containsSkippable(_skipExcludeExceptions, e);
if(logger.isLoggable(Level.FINE))
logger.logp(Level.FINE, className, mName, mName + ": " + retVal + ": " + exClassName);
return retVal;
}
/**
* Check whether given exception is in skippable exception list
*/
private boolean containsSkippable(Set<String> skipList, Exception e)
{
final String mName = "containsSkippable";
boolean retVal = false;
for ( Iterator it = skipList.iterator(); it.hasNext(); ) {
String exClassName = (String) it.next();
try {
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
if (retVal = tccl.loadClass(exClassName).isInstance(e))
break;
} catch (ClassNotFoundException cnf) {
logger.logp(Level.FINE, className, mName, cnf.getLocalizedMessage());
}
}
if(logger.isLoggable(Level.FINE))
logger.logp(Level.FINE, className, mName, mName + ": " + retVal );
return retVal;
}
/**
* Check if the skip limit has been reached.
*
* Note: if skip handling isn't enabled (i.e. not configured in xJCL), then this method
* will always return TRUE.
*/
private boolean isSkipLimitReached()
{
return (_skipCount >= _skipLimit);
}
private void logSkip(Exception e)
{
Object[] details = { _jobId, _stepId, e.getClass().getName() + ": " + e.getMessage() };
if(logger.isLoggable(Level.FINE))
logger.logp(Level.FINE, className, "logSkip", "Logging details: ", details);
}
public long getSkipCount()
{
return _skipCount;
}
public void setSkipCount(long skipCount)
{
final String mName = "setSkipCount";
_skipCount = skipCount;
if(logger.isLoggable(Level.FINE))
logger.logp(Level.FINE, className, mName, "setSkipCount: " + _skipCount);
}
public String toString()
{
return "SkipHandler{" + super.toString() + "}count:limit=" + _skipCount + ":" + _skipLimit;
}
}
| 29.997222 | 116 | 0.65932 |
290d6e72a403156b54330993ce9413b948bd59f1 | 1,036 | /**
*
*/
package net.rn.clouds.chat.dao;
import java.util.Collection;
import java.util.List;
import biz.neustar.clouds.chat.model.Connection;
import net.rn.clouds.chat.model.ConnectionRequest;
/**
* @author Noopur Pandey
*
*/
public interface ConnectionRequestDAO {
/**
* @param cloud1
* @param cloud2
* @return List<ConnectionRequest>
*/
public List<ConnectionRequest> getConnectionRequest(String cloud1, String cloud2);
/**
* @param connectionRequest
*/
public void requestConnection(ConnectionRequest connectionRequest);
/**
* @param children
* @return List<Connection>
*/
public List<ConnectionRequest> viewConnections(Collection<String> children);
/**
* @param connectionRequest
*/
public void updateRequest(ConnectionRequest connectionRequest);
/**
* @param connectionRequest
*/
public void deleteRequest(ConnectionRequest connectionRequest);
/**
* @param cloudNumber
* @return List<Connection>
*/
public List<Object[]> getNotification(String cloudNumbers);
}
| 19.923077 | 83 | 0.722973 |
6615471d62756cc2aa24e2995244bca471103802 | 2,140 | /*
* Copyright 2022 Accenture Global Solutions Limited
*
* 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.finos.tracdap.svc.orch.jobs;
import org.finos.tracdap.common.exception.ETracInternal;
import org.finos.tracdap.common.exception.EValidationGap;
import org.finos.tracdap.metadata.JobType;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
public class JobLogic {
private static final Map<JobType, Constructor<? extends IJobLogic>> JOB_TYPES;
static {
try {
JOB_TYPES = Map.ofEntries(
Map.entry(JobType.IMPORT_MODEL, ImportModelJob.class.getDeclaredConstructor()),
Map.entry(JobType.RUN_MODEL, RunModelJob.class.getDeclaredConstructor()));
}
catch (NoSuchMethodException e) {
throw new ETracInternal("Invalid job logic class, default constructor not available", e);
}
}
public static IJobLogic forJobType(JobType jobType) {
try {
var logicClass = JOB_TYPES.get(jobType);
// TODO: Is this the right error type?
if (logicClass == null) {
var err = String.format("Unrecognized job type: [%s]", jobType);
throw new EValidationGap(err);
}
return logicClass.newInstance();
}
catch ( InstantiationException |
IllegalAccessException |
InvocationTargetException e) {
throw new ETracInternal("Invalid job logic class, default constructor not available", e);
}
}
}
| 32.923077 | 101 | 0.669159 |
85b0bb6ce1bb165f1a1223f3d1ae2cafbb17c409 | 115 | package org.threehook.catena.networking.messaging.listening;
public interface Listener {
void subscribe();
}
| 16.428571 | 60 | 0.773913 |
5a64b1195bd73d0368254d5c817a46fda7c6d949 | 1,443 | package com.netflix.concurrency.limits.spectator;
import java.util.function.Supplier;
import com.netflix.concurrency.limits.MetricRegistry;
import com.netflix.spectator.api.DistributionSummary;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;
import com.netflix.spectator.api.patterns.PolledMeter;
public final class SpectatorMetricRegistry implements MetricRegistry {
private final Registry registry;
private final Id baseId;
public SpectatorMetricRegistry(Registry registry, Id baseId) {
this.registry = registry;
this.baseId = baseId;
}
@Override
public SampleListener registerDistribution(String id, String... tagNameValuePairs) {
DistributionSummary summary = registry.distributionSummary(suffixBaseId(id).withTags(tagNameValuePairs));
return value -> summary.record(value.longValue());
}
@Override
public void registerGauge(String id, Supplier<Number> supplier, String... tagNameValuePairs) {
Id metricId = suffixBaseId(id).withTags(tagNameValuePairs);
PolledMeter.remove(registry, metricId);
PolledMeter.using(registry)
.withId(metricId)
.monitorValue(supplier, ignore -> supplier.get().doubleValue());
}
private Id suffixBaseId(String suffix) {
return registry.createId(this.baseId.name() + "." + suffix).withTags(this.baseId.tags());
}
}
| 35.195122 | 113 | 0.719335 |
7fba42141998c9c1f9e2fb4e81a7f5168192dece | 838 | package com.duastone.stalactite.action.impl;
import com.duastone.stalactite.action.DocSubjectAction;
import com.duastone.stalactite.entity.DocSubject;
import org.springframework.stereotype.Repository;
import java.util.List;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;
/**
* Implement of {@link DocSubjectAction}
* Created by Fernando on 9/4/16.
*/
@Repository("docSubjectAction")
public class DocSubjectActionAchieve extends BaseActionAchieve<DocSubject> implements DocSubjectAction {
// Find doc Subject by mongodb Id
@Override
public DocSubject findById(String subjectId) {
return mongoTemplate.findOne(
query(where("_id").is(subjectId)),
DocSubject.class
);
}
}
| 29.928571 | 104 | 0.747017 |
ee3d2b7a5f7d81b29b779dea4a7d7d9c5c251265 | 13,400 | package org.bouncycastle.cert;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.ASN1GeneralizedTime;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.Extensions;
import org.bouncycastle.asn1.x509.ExtensionsGenerator;
import org.bouncycastle.asn1.x509.TBSCertList;
import org.bouncycastle.asn1.x509.Time;
import org.bouncycastle.asn1.x509.V2TBSCertListGenerator;
import org.bouncycastle.operator.ContentSigner;
/**
* class to produce an X.509 Version 2 CRL.
*/
public class X509v2CRLBuilder
{
private V2TBSCertListGenerator tbsGen;
private ExtensionsGenerator extGenerator;
/**
* Basic constructor.
*
* @param issuer the issuer this CRL is associated with.
* @param thisUpdate the date of this update.
*/
public X509v2CRLBuilder(
X500Name issuer,
Date thisUpdate)
{
tbsGen = new V2TBSCertListGenerator();
extGenerator = new ExtensionsGenerator();
tbsGen.setIssuer(issuer);
tbsGen.setThisUpdate(new Time(thisUpdate));
}
/**
* Basic constructor with Locale. You may need to use this constructor if the default locale
* doesn't use a Gregorian calender so that the Time produced is compatible with other ASN.1 implementations.
*
* @param issuer the issuer this CRL is associated with.
* @param thisUpdate the date of this update.
* @param dateLocale locale to be used for date interpretation.
*/
public X509v2CRLBuilder(
X500Name issuer,
Date thisUpdate,
Locale dateLocale)
{
tbsGen = new V2TBSCertListGenerator();
extGenerator = new ExtensionsGenerator();
tbsGen.setIssuer(issuer);
tbsGen.setThisUpdate(new Time(thisUpdate, dateLocale));
}
/**
* Basic constructor.
*
* @param issuer the issuer this CRL is associated with.
* @param thisUpdate the Time of this update.
*/
public X509v2CRLBuilder(
X500Name issuer,
Time thisUpdate)
{
tbsGen = new V2TBSCertListGenerator();
extGenerator = new ExtensionsGenerator();
tbsGen.setIssuer(issuer);
tbsGen.setThisUpdate(thisUpdate);
}
/**
* Create a builder for a version 2 CRL, initialised with another CRL.
*
* @param template template CRL to base the new one on.
*/
public X509v2CRLBuilder(X509CRLHolder template)
{
tbsGen = new V2TBSCertListGenerator();
tbsGen.setIssuer(template.getIssuer());
tbsGen.setThisUpdate(new Time(template.getThisUpdate()));
Date nextUpdate = template.getNextUpdate();
if (nextUpdate != null)
{
tbsGen.setNextUpdate(new Time(nextUpdate));
}
addCRL(template);
extGenerator = new ExtensionsGenerator();
Extensions exts = template.getExtensions();
for (Enumeration en = exts.oids(); en.hasMoreElements();)
{
extGenerator.addExtension(exts.getExtension((ASN1ObjectIdentifier)en.nextElement()));
}
}
/**
* Return if the extension indicated by OID is present.
*
* @param oid the OID for the extension of interest.
* @return the Extension, or null if it is not present.
*/
public boolean hasExtension(ASN1ObjectIdentifier oid)
{
return doGetExtension(oid) != null;
}
/**
* Return the current value of the extension for OID.
*
* @param oid the OID for the extension we want to fetch.
* @return true if a matching extension is present, false otherwise.
*/
public Extension getExtension(ASN1ObjectIdentifier oid)
{
return doGetExtension(oid);
}
private Extension doGetExtension(ASN1ObjectIdentifier oid)
{
Extensions exts = extGenerator.generate();
return exts.getExtension(oid);
}
/**
* Set the date by which the next CRL will become available.
*
* @param date date of next CRL update.
* @return the current builder.
*/
public X509v2CRLBuilder setNextUpdate(
Date date)
{
return this.setNextUpdate(new Time(date));
}
/**
* Set the date by which the next CRL will become available.
*
* @param date date of next CRL update.
* @param dateLocale locale to be used for date interpretation.
* @return the current builder.
*/
public X509v2CRLBuilder setNextUpdate(
Date date,
Locale dateLocale)
{
return this.setNextUpdate(new Time(date, dateLocale));
}
/**
* Set the date by which the next CRL will become available.
*
* @param date date of next CRL update.
* @return the current builder.
*/
public X509v2CRLBuilder setNextUpdate(
Time date)
{
tbsGen.setNextUpdate(date);
return this;
}
/**
* Add a CRL entry with the just reasonCode extension.
*
* @param userCertificateSerial serial number of revoked certificate.
* @param revocationDate date of certificate revocation.
* @param reason the reason code, as indicated in CRLReason, i.e CRLReason.keyCompromise, or 0 if not to be used.
* @return the current builder.
*/
public X509v2CRLBuilder addCRLEntry(BigInteger userCertificateSerial, Date revocationDate, int reason)
{
tbsGen.addCRLEntry(new ASN1Integer(userCertificateSerial), new Time(revocationDate), reason);
return this;
}
/**
* Add a CRL entry with an invalidityDate extension as well as a reasonCode extension. This is used
* where the date of revocation might be after issues with the certificate may have occurred.
*
* @param userCertificateSerial serial number of revoked certificate.
* @param revocationDate date of certificate revocation.
* @param reason the reason code, as indicated in CRLReason, i.e CRLReason.keyCompromise, or 0 if not to be used.
* @param invalidityDate the date on which the private key for the certificate became compromised or the certificate otherwise became invalid.
* @return the current builder.
*/
public X509v2CRLBuilder addCRLEntry(BigInteger userCertificateSerial, Date revocationDate, int reason, Date invalidityDate)
{
tbsGen.addCRLEntry(new ASN1Integer(userCertificateSerial), new Time(revocationDate), reason, new ASN1GeneralizedTime(invalidityDate));
return this;
}
/**
* Add a CRL entry with extensions.
*
* @param userCertificateSerial serial number of revoked certificate.
* @param revocationDate date of certificate revocation.
* @param extensions extension set to be associated with this CRLEntry.
* @return the current builder.
*/
public X509v2CRLBuilder addCRLEntry(BigInteger userCertificateSerial, Date revocationDate, Extensions extensions)
{
tbsGen.addCRLEntry(new ASN1Integer(userCertificateSerial), new Time(revocationDate), extensions);
return this;
}
/**
* Add the CRLEntry objects contained in a previous CRL.
*
* @param other the X509CRLHolder to source the other entries from.
* @return the current builder.
*/
public X509v2CRLBuilder addCRL(X509CRLHolder other)
{
TBSCertList revocations = other.toASN1Structure().getTBSCertList();
if (revocations != null)
{
for (Enumeration en = revocations.getRevokedCertificateEnumeration(); en.hasMoreElements();)
{
tbsGen.addCRLEntry(ASN1Sequence.getInstance(((ASN1Encodable)en.nextElement()).toASN1Primitive()));
}
}
return this;
}
/**
* Add a given extension field for the standard extensions tag (tag 3)
*
* @param oid the OID defining the extension type.
* @param isCritical true if the extension is critical, false otherwise.
* @param value the ASN.1 structure that forms the extension's value.
* @return this builder object.
*/
public X509v2CRLBuilder addExtension(
ASN1ObjectIdentifier oid,
boolean isCritical,
ASN1Encodable value)
throws CertIOException
{
CertUtils.addExtension(extGenerator, oid, isCritical, value);
return this;
}
/**
* Add a given extension field for the standard extensions tag (tag 3) using a byte encoding of the
* extension value.
*
* @param oid the OID defining the extension type.
* @param isCritical true if the extension is critical, false otherwise.
* @param encodedValue a byte array representing the encoding of the extension value.
* @return this builder object.
*/
public X509v2CRLBuilder addExtension(
ASN1ObjectIdentifier oid,
boolean isCritical,
byte[] encodedValue)
throws CertIOException
{
extGenerator.addExtension(oid, isCritical, encodedValue);
return this;
}
/**
* Add a given extension field for the standard extensions tag (tag 3).
*
* @param extension the full extension value.
* @return this builder object.
*/
public X509v2CRLBuilder addExtension(
Extension extension)
throws CertIOException
{
extGenerator.addExtension(extension);
return this;
}
/**
* Replace the extension field for the passed in extension's extension ID
* with a new version.
*
* @param oid the OID defining the extension type.
* @param isCritical true if the extension is critical, false otherwise.
* @param value the ASN.1 structure that forms the extension's value.
* @return this builder object.
* @throws CertIOException if there is an issue with the new extension value.
* @throws IllegalArgumentException if the extension to be replaced is not present.
*/
public X509v2CRLBuilder replaceExtension(
ASN1ObjectIdentifier oid,
boolean isCritical,
ASN1Encodable value)
throws CertIOException
{
try
{
extGenerator = CertUtils.doReplaceExtension(extGenerator, new Extension(oid, isCritical, value.toASN1Primitive().getEncoded(ASN1Encoding.DER)));
}
catch (IOException e)
{
throw new CertIOException("cannot encode extension: " + e.getMessage(), e);
}
return this;
}
/**
* Replace the extension field for the passed in extension's extension ID
* with a new version.
*
* @param extension the full extension value.
* @return this builder object.
* @throws CertIOException if there is an issue with the new extension value.
* @throws IllegalArgumentException if the extension to be replaced is not present.
*/
public X509v2CRLBuilder replaceExtension(
Extension extension)
throws CertIOException
{
extGenerator = CertUtils.doReplaceExtension(extGenerator, extension);
return this;
}
/**
* Replace a given extension field for the standard extensions tag (tag 3) with the passed in
* byte encoded extension value.
*
* @param oid the OID defining the extension type.
* @param isCritical true if the extension is critical, false otherwise.
* @param encodedValue a byte array representing the encoding of the extension value.
* @return this builder object.
* @throws CertIOException if there is an issue with the new extension value.
* @throws IllegalArgumentException if the extension to be replaced is not present.
*/
public X509v2CRLBuilder replaceExtension(
ASN1ObjectIdentifier oid,
boolean isCritical,
byte[] encodedValue)
throws CertIOException
{
extGenerator = CertUtils.doReplaceExtension(extGenerator, new Extension(oid, isCritical, encodedValue));
return this;
}
/**
* Remove the extension indicated by OID.
*
* @param oid the OID of the extension to be removed.
* @return this builder object.
* @throws IllegalArgumentException if the extension to be removed is not present.
*/
public X509v2CRLBuilder removeExtension(ASN1ObjectIdentifier oid)
{
extGenerator = CertUtils.doRemoveExtension(extGenerator, oid);
return this;
}
/**
* Generate an X.509 CRL, based on the current issuer and subject
* using the passed in signer.
*
* @param signer the content signer to be used to generate the signature validating the certificate.
* @return a holder containing the resulting signed certificate.
*/
public X509CRLHolder build(
ContentSigner signer)
{
tbsGen.setSignature(signer.getAlgorithmIdentifier());
if (!extGenerator.isEmpty())
{
tbsGen.setExtensions(extGenerator.generate());
}
return CertUtils.generateFullCRL(signer, tbsGen.generateTBSCertList());
}
}
| 32.843137 | 156 | 0.668731 |
2f7c86f3de7c34b2f02145045d5581ba3c1c6b0c | 5,472 | package de.fau.amos.virtualledger.server.banking.adorsys.api.bankAccountEndpoint;
import de.fau.amos.virtualledger.server.banking.adorsys.api.bankAccessEndpoint.DummyBankAccessBankingModelEntity;
import de.fau.amos.virtualledger.server.banking.adorsys.api.bankAccessEndpoint.DummyBankAccessEndpoint;
import de.fau.amos.virtualledger.server.banking.adorsys.api.bankAccessEndpoint.DummyBankAccessEndpointRepository;
import de.fau.amos.virtualledger.server.banking.model.BankAccountBankingModel;
import de.fau.amos.virtualledger.server.banking.model.BookingModel;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class DummyBankAccountEndpointTest {
private final int amountAccountsToGenerate = 5;
@Test
public void getBankAccountsAccountsExist() throws Exception {
// SETUP
String testUserId = "userId";
DummyBankAccessEndpoint dummyBankAccessEndpoint = mock(DummyBankAccessEndpoint.class);
DummyBankAccountBankingModelRepository dummyBankAccountBankingModelRepository = mock(DummyBankAccountBankingModelRepository.class);
DummyBankAccessEndpointRepository dummyBankAccessEndpointRepository = mock(DummyBankAccessEndpointRepository.class);
when(dummyBankAccessEndpoint.existsBankAccess(anyString())).thenReturn(true);
when(dummyBankAccountBankingModelRepository.existBankAccountsForAccessId(anyString())).thenReturn(true);
when(dummyBankAccountBankingModelRepository.findAllByAccessId(anyString())).thenReturn(generateBankingAccounts());
DummyBankAccountEndpoint dummyBankAccountEndpoint = new DummyBankAccountEndpoint(dummyBankAccountBankingModelRepository, dummyBankAccessEndpointRepository, dummyBankAccessEndpoint);
// ACT
List<BankAccountBankingModel> bankAccounts = dummyBankAccountEndpoint.getBankAccounts(
"bankAccessId");
// ASSERT
assertNotNull(bankAccounts);
assertTrue(bankAccounts.size() == amountAccountsToGenerate);
verify(dummyBankAccountBankingModelRepository, times(1)).findAllByAccessId(anyString());
}
@Test
public void getBankAccountsAccountsNotExist() throws Exception {
// SETUP
String testUserId = "userId";
DummyBankAccessEndpoint dummyBankAccessEndpoint = mock(DummyBankAccessEndpoint.class);
DummyBankAccountBankingModelRepository dummyBankAccountBankingModelRepository = mock(DummyBankAccountBankingModelRepository.class);
DummyBankAccessEndpointRepository dummyBankAccessEndpointRepository = mock(DummyBankAccessEndpointRepository.class);
when(dummyBankAccessEndpoint.existsBankAccess(anyString())).thenReturn(true);
when(dummyBankAccountBankingModelRepository.existBankAccountsForAccessId(anyString())).thenReturn(false);
DummyBankAccountEndpoint dummyBankAccountEndpoint = new DummyBankAccountEndpoint(dummyBankAccountBankingModelRepository, dummyBankAccessEndpointRepository, dummyBankAccessEndpoint);
// ACT
List<BankAccountBankingModel> bankAccounts = dummyBankAccountEndpoint.getBankAccounts(
"bankAccessId");
// ASSERT
assertNotNull(bankAccounts);
assertTrue(bankAccounts.size() >= 0);
verify(dummyBankAccountBankingModelRepository, times(1)).findAllByAccessId(anyString());
verify(dummyBankAccountBankingModelRepository, atLeastOnce()).save(any(List.class));
}
@Test
public void syncBankAccountsAccountsNotExist() throws Exception {
// SETUP
String testUserId = "userId";
DummyBankAccessEndpoint dummyBankAccessEndpoint = mock(DummyBankAccessEndpoint.class);
DummyBankAccountBankingModelRepository dummyBankAccountBankingModelRepository = mock(DummyBankAccountBankingModelRepository.class);
DummyBankAccessEndpointRepository dummyBankAccessEndpointRepository = mock(DummyBankAccessEndpointRepository.class);
DummyBankAccountEndpoint dummyBankAccountEndpoint = new DummyBankAccountEndpoint(dummyBankAccountBankingModelRepository, dummyBankAccessEndpointRepository, dummyBankAccessEndpoint);
// ACT
List<BookingModel> bookings = dummyBankAccountEndpoint.syncBankAccount(
"bankAccessId", "bankAccountId", "pin");
// ASSERT
assertNotNull(bookings);
assertTrue(bookings.size() >= 0);
}
private List<DummyBankAccountBankingModelEntity> generateBankingAccounts() {
List<DummyBankAccountBankingModelEntity> dummyBankAccountBankingModelEntityList = new ArrayList<>();
for (int i = 0; i < amountAccountsToGenerate; i++) {
DummyBankAccountBankingModelEntity accountEntity = new DummyBankAccountBankingModelEntity();
DummyBankAccessBankingModelEntity accessEntity = new DummyBankAccessBankingModelEntity();
accessEntity.setId("id");
accountEntity.setBankAccess(accessEntity);
dummyBankAccountBankingModelEntityList.add(accountEntity);
}
return dummyBankAccountBankingModelEntityList;
}
}
| 48 | 189 | 0.780154 |
2d1fc67954b58188ce04a0352abcaaa5781b14e7 | 1,206 | package com.huazie.frame.core.request;
import com.huazie.frame.common.FleaCommonConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* <p> Flea请求上下文 </p>
*
* @author huazie
* @version 1.0.0
* @since 1.0.0
*/
public class FleaRequestContext extends FleaCommonConfig {
public static final String REDIRECT_FLAG = "REDIRECT_FLAG"; // 重定向标识
public static final String REDIRECT_URL = "REDIRECT_URL"; // 重定向地址
private ServletRequest servletRequest;
private ServletResponse servletResponse;
public FleaRequestContext() {
}
public FleaRequestContext(ServletRequest servletRequest, ServletResponse servletResponse) {
this.servletRequest = servletRequest;
this.servletResponse = servletResponse;
}
public ServletRequest getServletRequest() {
return servletRequest;
}
public void setServletRequest(ServletRequest servletRequest) {
this.servletRequest = servletRequest;
}
public ServletResponse getServletResponse() {
return servletResponse;
}
public void setServletResponse(ServletResponse servletResponse) {
this.servletResponse = servletResponse;
}
}
| 24.612245 | 95 | 0.728027 |
a1324fe9d96ec63403d595397ee008a4eb5baf25 | 2,415 | package web.servlets;
import java.lang.StringBuffer;
import java.io.BufferedReader;
import java.util.Iterator;
import java.sql.SQLException;
import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import web.database.dataAccessObject.UsuariosDAO;
import web.database.valueObject.UsuarioVO;
import web.database.dataAccessObject.VJuegosDAO;
import web.database.valueObject.VJuegoVO;
import web.database.valueObject.ComentarioVO;
import web.database.valueObject.PuntuacionVO;
public abstract class AbstractServletCYV extends AbstractServletP {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AbstractServletCYV() {
super();
// TODO Auto-generated constructor stub
}
protected JSONArray getComentarios (Iterator<ComentarioVO> itr) throws ClassNotFoundException, SQLException{
JSONArray ja = new JSONArray();
while(itr.hasNext()){
ComentarioVO cVo = itr.next();
UsuarioVO uVo = UsuariosDAO.findUser(cVo.getUsuarioID());
VJuegoVO jVo = VJuegosDAO.findVJuego(cVo.getvJuego());
JSONObject comment = new JSONObject();
comment.element("nombreUsuario", uVo.getNickname());
comment.element("nombreReal", uVo.getNombre());
comment.element("idUsuario", cVo.getUsuarioID());
comment.element("juego", jVo.getTitulo());
comment.element("idJuego", cVo.getvJuego());
comment.element("fecha", (cVo.getFecha()).substring(0,10));
comment.element("contenido", cVo.getComentario());
ja.add(comment);
}
return ja;
}
protected JSONArray getValoraciones (Iterator<PuntuacionVO> itr) throws ClassNotFoundException, SQLException{
JSONArray ja = new JSONArray();
while(itr.hasNext()){
PuntuacionVO pVo = itr.next();
UsuarioVO uVo = UsuariosDAO.findUser(pVo.getUsuarioID());
VJuegoVO jVo = VJuegosDAO.findVJuego(pVo.getvJuego());
JSONObject puntuacion = new JSONObject();
puntuacion.element("nombreUsuario", uVo.getNickname());
puntuacion.element("nombreReal", uVo.getNombre());
puntuacion.element("idUsuario", pVo.getUsuarioID());
puntuacion.element("juego", jVo.getTitulo());
puntuacion.element("valoracion", puntuacionToString(pVo.getPuntuacion())+"Estrella");
puntuacion.element("idJuego", pVo.getvJuego());
puntuacion.element("fecha", (pVo.getFecha()).substring(0,10));
ja.add(puntuacion);
}
return ja;
}
}
| 34.014085 | 110 | 0.738302 |
47d27cfb740872752018ccac502820955e362fac | 778 | package com.flink.streaming.web.enums;
import lombok.Getter;
/**
* @author zhuhuipei
* @Description:
* @date 2020-09-25
* @time 21:45
*/
@Getter
public enum AlartLogStatusEnum {
SUCCESS(1, "成功"),
FAIL(0, "失败"),
;
private int code;
private String desc;
AlartLogStatusEnum(int code, String desc) {
this.code = code;
this.desc = desc;
}
public static AlartLogStatusEnum getAlartLogStatusEnum(Integer code) {
if (code == null) {
return null;
}
for (AlartLogStatusEnum alartLogStatusEnum : AlartLogStatusEnum.values()) {
if (alartLogStatusEnum.getCode() == code.intValue()) {
return alartLogStatusEnum;
}
}
return null;
}
}
| 18.52381 | 83 | 0.584833 |
a69289140f4320929cb07631908bf4aa665fa46e | 3,248 | /*
*
*/
package io.zino.mystore.storageEngine.fileStorageEngine;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import io.zino.mystore.storageEngine.StorageEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class DBFileEngine.
*/
final class DBFileEngine {
/** The Constant logger. */
final static Logger logger = LoggerFactory.getLogger(DBFileEngine.class);
/**
* Instantiates a new DB file engine.
*
* @param dbFile the db file
*/
DBFileEngine(RandomAccessFile dbFile) {
super();
this.dbFile = dbFile;
}
/** The write head. */
private AtomicLong writeHead = new AtomicLong(1L);
/** The dirty entry. */
public static AtomicInteger dirtyEntry = new AtomicInteger(0);
/** The db file. */
RandomAccessFile dbFile;
/**
* Load entry.
*
* @param head the head
* @return the storage entry
*/
synchronized StorageEntry loadEntry(long head) {
try {
this.dbFile.seek(head);
long version = this.dbFile.readLong();
long lastAccess = this.dbFile.readLong();
long touchCount = this.dbFile.readLong();
String nodeId = loadString();
String key = loadString();
String data = loadString();
return new StorageEntry(version, nodeId, key, data, lastAccess, touchCount);
} catch (IOException e) {
logger.error("Error on load Entry with Head " + head, e);
}
return null;
}
/**
* Load string.
*
* @return the string
* @throws IOException Signals that an I/O exception has occurred.
*/
private String loadString() throws IOException {
StringBuilder sb = new StringBuilder();
int size = this.dbFile.readInt();
for (int i = 0; i < size; i++) {
sb.append(this.dbFile.readChar());
}
return sb.toString();
}
/**
* Save entry.
*
* @param entry the entry
* @return the long
*/
synchronized long saveEntry(StorageEntry entry) {
final long wh = this.writeHead.longValue();
final long size = this.saveEntry(wh, entry);
if(size==-1){
logger.debug("saveEntry Failed! "+entry.toString());
return -1l;
}
long newWH = this.writeHead.addAndGet(size);
logger.debug("save Entry with key " + entry.getKey() + " with Head " + wh + " end is " + newWH);
return wh;
}
/**
* Save entry.
*
* @param head the head
* @param entry the entry
* @return the long
*/
private long saveEntry(long head, StorageEntry entry) {
try {
this.dbFile.seek(head);
this.dbFile.writeLong(entry.getVersion());
this.dbFile.writeLong(entry.getLastAccess());
this.dbFile.writeLong(entry.getTouchCount());
this.saveString(entry.getNodeId());
this.saveString(entry.getKey());
this.saveString(entry.getData());
return this.dbFile.getFilePointer() - head;
} catch (IOException e) {
logger.error("Error on saving on Head " + head + " Entry: " + entry.toString(), e);
return -1l;
}
}
/**
* Save string.
*
* @param string the string
* @throws IOException Signals that an I/O exception has occurred.
*/
private void saveString(String string) throws IOException {
this.dbFile.writeInt(string.length());
for (int c : string.toCharArray())
this.dbFile.writeChar(c);
}
}
| 23.366906 | 98 | 0.676108 |
9f3cacbea0293adac406a7591cf7daaf8670e9e2 | 1,906 | /**
* Copyright (C) 2017 GIP RECIA http://www.recia.fr
* @Author (C) 2013 Maxime Bossard <mxbossard@gmail.com>
* @Author (C) 2016 Julien Gribonvald <julien.gribonvald@recia.fr>
*
* 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.esco.portlet.changeetab.model;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
/**
* @author GIP RECIA 2013 - Maxime BOSSARD.
* @author GIP RECIA - Julien Gribonvald
*
*/
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class UniteAdministrativeImmatriculee extends Structure {
/** Etab code. */
@NonNull
private String code;
/**
* @param id Identifier
* @param code Code
* @param name Complete Name
* @param displayName Display Name
* @param description Description
* @param otherAttributes All other attributes
*/
public UniteAdministrativeImmatriculee(@NonNull String id, @NonNull String code, @NonNull String name, @NonNull String displayName,
String description, Map<String, List<String>> otherAttributes) {
super(id, name, displayName, description, otherAttributes);
// TODO Auto-generated constructor stub
this.code = code;
}
}
| 28.878788 | 132 | 0.746065 |
38ab00aaccc39f4cdd212107c2ca40f91095bc29 | 111 | /**
* MongoDB database migrations using MongoBee.
*/
package com.xebialabs.notification.config.dbmigrations;
| 22.2 | 55 | 0.783784 |
70bc40aba111b3cb3f5f847cff97ed202ec8e56b | 3,263 | /*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.hc.core5.http.io;
import java.io.IOException;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpException;
/**
* A server-side HTTP connection, which can be used for receiving
* requests and sending responses.
*
* @since 4.0
*/
public interface HttpServerConnection extends BHttpConnection {
/**
* Receives the request line and all headers available from this connection.
* The caller should examine the returned request and decide if to receive a
* request entity as well.
*
* @return a new HttpRequest object whose request line and headers are
* initialized.
* @throws HttpException in case of HTTP protocol violation
* @throws IOException in case of an I/O error
*/
ClassicHttpRequest receiveRequestHeader()
throws HttpException, IOException;
/**
* Receives the next request entity available from this connection and attaches it to
* an existing request.
* @param request the request to attach the entity to.
* @throws HttpException in case of HTTP protocol violation
* @throws IOException in case of an I/O error
*/
void receiveRequestEntity(ClassicHttpRequest request)
throws HttpException, IOException;
/**
* Sends the response line and headers of a response over this connection.
* @param response the response whose headers to send.
* @throws HttpException in case of HTTP protocol violation
* @throws IOException in case of an I/O error
*/
void sendResponseHeader(ClassicHttpResponse response)
throws HttpException, IOException;
/**
* Sends the response entity of a response over this connection.
* @param response the response whose entity to send.
* @throws HttpException in case of HTTP protocol violation
* @throws IOException in case of an I/O error
*/
void sendResponseEntity(ClassicHttpResponse response)
throws HttpException, IOException;
}
| 37.94186 | 89 | 0.694453 |
d3b6082c194b3c837139f38c223b828db639ca56 | 5,080 | /*
* Copyright (c) 2019 Absolute Apogee Technologies Ltd. All rights reserved.
*
* =============================================================================
* Revision History:
* Date Author Detail
* ----------- -------------- ------------------------------------------------
* 2019-Feb-03 GShokar Created
* =============================================================================
*/
package ca.aatl.app.invoicebook.dto;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author GShokar
*/
public class InvoiceItemDto {
private String invoiceNumber;
/**
* Get the value of invoiceNumber
*
* @return the value of invoiceNumber
*/
public String getInvoiceNumber() {
return invoiceNumber;
}
/**
* Set the value of invoiceNumber
*
* @param invoiceNumber new value of invoiceNumber
*/
public void setInvoiceNumber(String invoiceNumber) {
this.invoiceNumber = invoiceNumber;
}
private int lineNumber;
/**
* Get the value of lineNumber
*
* @return the value of lineNumber
*/
public int getLineNumber() {
return lineNumber;
}
/**
* Set the value of lineNumber
*
* @param lineNumber new value of lineNumber
*/
public void setLineNumber(int lineNumber) {
this.lineNumber = lineNumber;
}
private String uid;
/**
* Get the value of uid
*
* @return the value of uid
*/
public String getUid() {
return uid;
}
/**
* Set the value of uid
*
* @param uid new value of uid
*/
public void setUid(String uid) {
this.uid = uid;
}
private String description;
/**
* Get the value of description
*
* @return the value of description
*/
public String getDescription() {
return description;
}
/**
* Set the value of description
*
* @param description new value of description
*/
public void setDescription(String description) {
this.description = description;
}
private double quantity;
/**
* Get the value of quantity
*
* @return the value of quantity
*/
public double getQuantity() {
return quantity;
}
/**
* Set the value of quantity
*
* @param quantity new value of quantity
*/
public void setQuantity(double quantity) {
this.quantity = quantity;
}
private double rate;
/**
* Get the value of rate
*
* @return the value of rate
*/
public double getRate() {
return rate;
}
/**
* Set the value of rate
*
* @param rate new value of rate
*/
public void setRate(double rate) {
this.rate = rate;
}
private double amount;
/**
* Get the value of amount
*
* @return the value of amount
*/
public double getAmount() {
return amount;
}
/**
* Set the value of amount
*
* @param amount new value of amount
*/
public void setAmount(double amount) {
this.amount = amount;
}
private double taxAmount;
/**
* Get the value of taxAmount
*
* @return the value of taxAmount
*/
public double getTaxAmount() {
return taxAmount;
}
/**
* Set the value of taxAmount
*
* @param taxAmount new value of taxAmount
*/
public void setTaxAmount(double taxAmount) {
this.taxAmount = taxAmount;
}
private double totalAmount;
/**
* Get the value of totalAmount
*
* @return the value of totalAmount
*/
public double getTotalAmount() {
return totalAmount;
}
/**
* Set the value of totalAmount
*
* @param totalAmount new value of totalAmount
*/
public void setTotalAmount(double totalAmount) {
this.totalAmount = totalAmount;
}
private List<InvoiceItemTaxDto> taxes = new ArrayList<>();
/**
* Get the value of taxes
*
* @return the value of taxes
*/
public List<InvoiceItemTaxDto> getTaxes() {
return taxes;
}
/**
* Set the value of taxes
*
* @param taxes new value of taxes
*/
public void setTaxes(List<InvoiceItemTaxDto> taxes) {
this.taxes = taxes;
}
private SalesItemDto salesItem;
/**
* Get the value of salesItem
*
* @return the value of salesItem
*/
public SalesItemDto getSalesItem() {
return salesItem;
}
/**
* Set the value of salesItem
*
* @param salesItem new value of salesItem
*/
public void setSalesItem(SalesItemDto salesItem) {
this.salesItem = salesItem;
}
}
| 20.90535 | 81 | 0.513976 |
ad9db47d4ed57cd57e9269a973b7061894449b96 | 10,064 | package com.pavlovmedia.oss.osgi.http;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Stream;
import java.util.zip.GZIPInputStream;
import com.pavlovmedia.oss.osgi.utilities.convertible.ConvertibleAsset;
/**
*
* @author Shawn Dempsay {@literal <sdempsay@pavlovmedia.com>}
*
*/
public class HttpResponse {
/**
* The URL that creaeted this response
*/
public final URL srcUrl;
/**
* The HTTP Response code
*/
public final int responseCode;
/**
* A convertible InputStream that represents the underlying errorStream.
* This is Optional and won't be populated if there is no error stream
*/
public final Optional<ConvertibleAsset<InputStream>> errorStream;
/**
* A convertible InputStream that represents the underlying inputStream.
* This is Optional and won't be populated if there is no error stream
*/
public final Optional<ConvertibleAsset<InputStream>> responseStream;
/**
* This is a map of the response headers
*/
public final Map<String,List<String>> responseHeaders;
/**
* Constructor for an HTTP Response
*
* @param responseCode
* @param errorStream
* @param responseStream
* @param responseHeaders
*/
protected HttpResponse(final URL srcUrl,
final int responseCode,
final Optional<ConvertibleAsset<InputStream>> errorStream,
final Optional<ConvertibleAsset<InputStream>> responseStream,
final Map<String,List<String>> responseHeaders) {
this.srcUrl = srcUrl;
this.responseCode = responseCode;
this.errorStream = errorStream;
this.responseStream = responseStream;
this.responseHeaders = responseHeaders;
}
public boolean isGziped() {
return this.responseHeaders.getOrDefault("Content-Encoding", Collections.emptyList())
.contains("gzip");
}
private final AtomicReference<String> responseString = new AtomicReference<>();
private String readAndCache(final Optional<ConvertibleAsset<InputStream>> stream,
final AtomicReference<String> reference, final Consumer<Exception> onError) {
if (!stream.isPresent()) {
return "";
}
if (reference.get() != null) {
return reference.get();
}
ConvertibleAsset<InputStream> working = stream.get();
if (isGziped()) {
working = working.convert(gunzipInputStream(onError));
}
reference.set(working.convert(inputStreamToUTF8StringConverter(onError)));
return reference.get();
}
/**
* Gets the response stream as text
* returns an empty string if there is no response text
* @param onError
*/
public String getResponseText(final Consumer<Exception> onError) {
return readAndCache(this.responseStream, this.responseString, onError);
}
/**
* Gets the response stream as text
* returns an empty string if there is no response text
*/
public String getResponseText() {
return getResponseText(HttpResponse::ignoreError);
}
private final AtomicReference<String> errorString = new AtomicReference<String>();
/**
* Gets the error stream as text
* returns an empty string if there is no error text
*
* @param onError
*/
public String getErrorText(final Consumer<Exception> onError) {
return readAndCache(this.errorStream, this.errorString, onError);
}
/**
* Gets the error stream as text
* returns an empty string if there is no error text
*/
public String getErrorText() {
return this.errorStream.isPresent()
? this.errorStream.get().convert(inputStreamToUTF8StringConverter(HttpResponse::ignoreError))
: "";
}
/**
* This method will check to see if there is a valid response code, which
* is between 200 and 299, if not it returns false
*
* @deprecated The Exception Consumer was not needed and causing issues. Use the non-Exception Consumer method
* @param onError
*/
@Deprecated
public boolean isValidResponse(final Consumer<Exception> onError) {
return !(this.responseCode < 200 || this.responseCode >= 300);
}
/**
* This method will check to see if there is a valid response code, which
* is between 200 and 299, if not it returns false
* @return true : 200 >= x < 300
*/
public boolean isValidResponse() {
return !(this.responseCode < 200 || this.responseCode >= 300);
}
/**
* Will process the result of a response branching between valid responses and invalid responses
* @since 1.0.11
*
* @param onValidResponse calculates a response based on a valid status
* @param onInvalidResponse calculates a response based on an invalid status
*/
public <T> Optional<T> process(final Function<HttpResponse, Optional<T>> onValidResponse, final Function<HttpResponse, Optional<T>> onInvalidResponse) {
return isValidResponse()
? onValidResponse.apply(this)
: onInvalidResponse.apply(this);
}
/**
* A static version of {@link #process(Function, Function)} that is useful in mapping functions
* @since 1.0.11
*
* @param onValidResponse
* @param onInvalidResponse
*/
public static final <T> Function<HttpResponse,Optional<T>> processResponse(final Function<HttpResponse, Optional<T>> onValidResponse, final Function<HttpResponse, Optional<T>> onInvalidResponse) {
return httpResponse -> httpResponse.process(onValidResponse, onInvalidResponse);
}
/**
* Will process the result of a response returning the value of onValidResponse for valid, and calling onInvalidResponse and returning {@link Optional#empty()}
* if the response is invalid
* @since 1.0.11
*
* @param onValidResponse
* @param onInvalidResponse
*/
public <T> Optional<T> process(final Function<HttpResponse, Optional<T>> onValidResponse, final Consumer<HttpResponse> onInvalidResponse) {
return process(onValidResponse, r -> {
onInvalidResponse.accept(this);
return Optional.empty();
});
}
/**
* A static version of {@link #process(Function, Consumer)} that is useful in mapping functions
* @since 1.0.11
*
* @param onValidResponse
* @param onInvalidResponse
*/
public static final <T> Function<HttpResponse,Optional<T>> processResponse(final Function<HttpResponse, Optional<T>> onValidResponse, final Consumer<HttpResponse> onInvalidResponse) {
return httpResponse -> httpResponse.process(onValidResponse, onInvalidResponse);
}
/**
* Static method that will give a converter to decode an UTF-8 input stream into a java string
* @param onError called if there is an error decoding the string
* @return the converted string, or an empty string if there is an error.
*/
public static Function<InputStream, String> inputStreamToUTF8StringConverter(final Consumer<Exception> onError) {
return is -> {
final InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
final Vector<Byte> byteVector = new Vector<>(1024);
try (BufferedReader reader = new BufferedReader(isr)) {
while (true) {
final int ch = reader.read();
if (-1 == ch) {
break;
}
byteVector.add((byte) ch);
}
return Stream.of(byteVectorToByteArray(byteVector))
.map(String::new)
.reduce((t, u) -> String.format("%s%s%s", t, System.lineSeparator(), u))
.orElse("No data");
} catch (final IOException e) {
onError.accept(e);
return "";
}
};
}
public static Function<InputStream, ConvertibleAsset<InputStream>> gunzipInputStream(final Consumer<Exception> onError) {
return in -> gunzipInputStream(in, onError);
}
public static ConvertibleAsset<InputStream> gunzipInputStream(final InputStream in, final Consumer<Exception> onError) {
try {
final Reader reader = new InputStreamReader(new GZIPInputStream(in));
final Vector<Byte> byteVector = new Vector<>(1024);
while (true) {
final int ch = reader.read();
if (-1 == ch) {
break;
}
byteVector.add((byte) ch);
}
return new ConvertibleAsset<>(new ByteArrayInputStream(byteVectorToByteArray(byteVector)));
} catch (final IOException e) {
onError.accept(e);
return new ConvertibleAsset<>(new ByteArrayInputStream(new byte[ ] { }));
}
}
public static byte[] byteVectorToByteArray(final Vector<Byte> byteVector) {
Objects.requireNonNull(byteVector);
final byte[] byteArray = new byte[byteVector.size()];
for (int i = 0; i < byteVector.size(); i++) {
byteArray[i] = byteVector.get(i).byteValue();
}
return byteArray;
}
/**
* A simple method used to just eat errors
* @param e
*/
private static void ignoreError(final Exception e) { }
}
| 35.066202 | 200 | 0.638812 |
f2318bfa799010d8c6aa8a3c65e519a267e85c0f | 4,797 | package com.intel.gkl.compression;
import com.intel.gkl.IntelGKLUtils;
import htsjdk.samtools.util.BlockCompressedInputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
/**
* Created by pnvaidya on 2/1/17.
*/
public class InflaterUnitTest {
private final static Logger log = LogManager.getLogger(InflaterUnitTest.class);
private final static String INPUT_FILE = IntelGKLUtils.pathToTestResource("HiSeq.1mb.1RG.2k_lines.bam");
final File inputFile = new File(INPUT_FILE);
long inputBytes = inputFile.length();
final IntelInflaterFactory intelInflaterFactoryInputTest = new IntelInflaterFactory();
final Inflater inflaterInputTest = intelInflaterFactoryInputTest.makeInflater(true);
@Test (enabled = true)
public void testInvalidInputsForSetInput() {
inflaterInputTest.reset();
final byte[] inputbuffer = new byte[(int)inputBytes];
try {
inflaterInputTest.setInput(null, 0, inputbuffer.length);
Assert.fail("NullPointerException expected.");
}catch (NullPointerException ne){}
try {
inflaterInputTest.setInput(inputbuffer, -1, inputbuffer.length);
Assert.fail("IllegalArgumentException expected.");
}catch (IllegalArgumentException ie){}
try {
inflaterInputTest.setInput(inputbuffer, 0, -1);
Assert.fail("IllegalArgumentException expected.");
}catch (IllegalArgumentException ie){}
inflaterInputTest.end();
}
@Test (enabled = true)
public void testInvalidInputsForInflate() {
final byte[] inputbuffer = new byte[(int)inputBytes];
final byte[] outputbuffer = new byte[(int)inputBytes];
try{
inflaterInputTest.reset();
inflaterInputTest.setInput(inputbuffer, 0, inputbuffer.length);
try {
inflaterInputTest.inflate(null);
Assert.fail("NullPointerException expected.");
} catch (NullPointerException ne) {}
try {
inflaterInputTest.inflate(null, 0, inputbuffer.length);
Assert.fail("NullPointerException expected.");
} catch (NullPointerException ne) {}
try {
inflaterInputTest.inflate(outputbuffer, -1, inputbuffer.length);
Assert.fail("IllegalArgumentException expected.");
} catch (IllegalArgumentException ie) {}
try {
inflaterInputTest.inflate(outputbuffer, 0, -1);
Assert.fail("IllegalArgumentException expected.");
} catch (IllegalArgumentException ie) {}
inflaterInputTest.end();
} catch (java.util.zip.DataFormatException e) {
e.printStackTrace();
}
}
@Test(enabled = true)
public void inflaterUnitTest() throws IOException {
int compressedBytes = 0;
final byte[] inputbuffer = new byte[(int)inputBytes];
final byte[] outputbuffer = new byte[(int)inputBytes];
final byte[] finalbuffer = new byte[(int)inputBytes];
long totalTime = 0;
for (int i = 1; i < 10; i++) {
final IntelInflaterFactory intelInflaterFactory = new IntelInflaterFactory();
final Inflater inflater = intelInflaterFactory.makeInflater(true);
final IntelDeflaterFactory intelDeflaterFactory = new IntelDeflaterFactory();
final Deflater deflater = intelDeflaterFactory.makeDeflater(i, true);
final BlockCompressedInputStream inputStream = new BlockCompressedInputStream(inputFile);
inputBytes = inputStream.read(inputbuffer, 0, inputbuffer.length);
deflater.reset();
deflater.setInput(inputbuffer, 0, inputbuffer.length);
deflater.finish();
compressedBytes = deflater.deflate(outputbuffer, 0, outputbuffer.length);
try {
inflater.reset();
inflater.setInput(outputbuffer, 0, compressedBytes);
final long start = System.currentTimeMillis();
inflater.inflate(finalbuffer, 0, inputbuffer.length);
totalTime = System.currentTimeMillis() - start;
log.info(String.format("Level: %d, time: %d", i, totalTime));
} catch (java.util.zip.DataFormatException e) {
e.printStackTrace();
}
Assert.assertEquals(inputbuffer, finalbuffer);
inflater.end();
deflater.end();
}
}
}
| 34.76087 | 108 | 0.634772 |
8e2fa23b37620dd544dc9f6c223637bae458b44f | 14,526 | package com.github.izhangzhihao.SpringMVCSeedProject.Test.RepositoryTest;
import com.github.izhangzhihao.SpringMVCSeedProject.Annotation.AuthorityType;
import com.github.izhangzhihao.SpringMVCSeedProject.Repository.BaseRepository;
import com.github.izhangzhihao.SpringMVCSeedProject.Repository.Query;
import com.github.izhangzhihao.SpringMVCSeedProject.Model.Teacher;
import com.github.izhangzhihao.SpringMVCSeedProject.Model.User;
import com.github.izhangzhihao.SpringMVCSeedProject.Test.TestUtils.BaseTest;
import com.github.izhangzhihao.SpringMVCSeedProject.Utils.PageResults;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.ParameterExpression;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static com.github.izhangzhihao.SpringMVCSeedProject.Utils.StringUtils.getRandomUUID;
import static java.util.Arrays.asList;
import static org.junit.Assert.*;
@SuppressWarnings({"unchecked", "SpringJavaAutowiredMembersInspection"})
public class BaseRepositoryTest extends BaseTest {
@Autowired
private BaseRepository<User> userRepository;
@Autowired
private BaseRepository<Teacher> teacherRepository;
@PersistenceContext
private EntityManager entityManager;
/**
* 对contains的单元测试
*/
@Test
public void containsExistTest() {
User user = getRandomUser();
userRepository.save(user);
assertTrue(userRepository.contains(user));
}
/**
* 对contains的单元测试
*/
@Test
public void containsNotExistTest() {
User user = getRandomUser();
assertFalse(userRepository.contains(user));
}
/**
* 对contains的单元测试 莫名其妙,用gradle能跑过的话idea内置的测试跑不过,idea内置测试跑得过的话gradle跑不过
*/
/*@SuppressWarnings("ConstantConditions")
@Test
public void containsNullTest() {
assertFalse(userRepository.contains(null));
}*/
/**
* 对detach的单元测试
*/
@Test
public void detachExistTest() {
User user = getRandomUser();
userRepository.save(user);
userRepository.detach(user);
boolean contains = userRepository.contains(user);
assertFalse(contains);
}
/**
* 对detach的单元测试
*/
@Test
public void detachNotExistTest() {
User user = getRandomUser();
userRepository.detach(user);
}
/**
* 对detach的单元测试
*/
@SuppressWarnings("ConstantConditions")
@Test(expected = Exception.class)
public void detachNullTest() {
userRepository.detach(null);
}
/**
* 对save的单元测试
*/
@Test
public void saveNewTest() {
userRepository.save(getRandomUser());
}
/**
* 对save的单元测试
*/
@Test
public void saveExistTest() {
final User user = getRandomUser();
userRepository.save(user);
userRepository.save(user);
}
/**
* 对save的单元测试
*/
@SuppressWarnings("ConstantConditions")
@Test(expected = Exception.class)
public void saveNullTest() {
userRepository.save(null);
}
/**
* 对saveAll的单元测试
*/
@Test
public void saveAllNewTest() {
List<User> userList = asList(getRandomUser()
, getRandomUser()
, getRandomUser()
);
userRepository.saveAll(userList);
}
/**
* 对saveAll的单元测试
*/
@Test
public void saveAllExistTest() {
List<User> userList = asList(getRandomUser()
, getRandomUser()
, getRandomUser()
);
userRepository.saveAll(userList);
userRepository.saveAll(userList);
}
/**
* 对saveAll的单元测试
*/
@SuppressWarnings("ConstantConditions")
@Test(expected = Exception.class)
public void saveAllNullTest() {
userRepository.saveAll(null);
}
/**
* 对delete的单元测试
*/
@Test
public void deleteExistTest() {
User user = getRandomUser();
userRepository.save(user);
userRepository.delete(user);
}
/**
* 对delete的单元测试
*/
@Test
public void deleteNotExistTest() {
userRepository.delete(getRandomUser());
}
/**
* 对delete的单元测试
*/
@SuppressWarnings("ConstantConditions")
@Test(expected = Exception.class)
public void deleteNullTest() {
userRepository.delete(null);
}
/**
* 对delete的单元测试
*/
@Test
public void deleteAllExistTest() {
List<User> userList = asList(getRandomUser()
, getRandomUser()
, getRandomUser()
);
userRepository.saveAll(userList);
userRepository.deleteAll(userList);
}
/**
* 对delete的单元测试
*/
@Test
public void deleteAllNotExistTest() {
List<User> userList = asList(getRandomUser()
, getRandomUser()
, getRandomUser()
);
userRepository.deleteAll(userList);
}
/**
* 对delete的单元测试
*/
@SuppressWarnings("ConstantConditions")
@Test(expected = Exception.class)
public void deleteAllNullTest() {
userRepository.deleteAll(null);
}
/**
* 对deleteById的单元测试
*/
public void deleteByExistIdTest() {
User user = getRandomUser();
userRepository.save(user);
userRepository.deleteById(User.class, user.getUserName());
}
/**
* 对deleteById的单元测试
*/
public void deleteByNotExistIdTest() {
userRepository.deleteById(User.class, getRandomUUID());
}
/**
* 对deleteById的单元测试
*/
@SuppressWarnings("ConstantConditions")
@Test(expected = Exception.class)
public void deleteByNullIdTest() {
userRepository.deleteById(User.class, null);
}
/**
* 对saveOrUpdate的单元测试
*/
@Test
public void saveOrUpdate_SaveTest() {
User user = getRandomUser();
userRepository.saveOrUpdate(user);
}
/**
* 对saveOrUpdate的单元测试
*/
@Test
public void saveOrUpdate_UpdateTest() {
User user = getRandomUser();
userRepository.save(user);
user.setPassWord("changed!");
userRepository.saveOrUpdate(user);
}
/**
* 对saveOrUpdate的单元测试
*/
@SuppressWarnings("ConstantConditions")
@Test(expected = Exception.class)
public void saveOrUpdate_NullTest() {
userRepository.saveOrUpdate(null);
}
/**
* 对saveOrUpdateAll的单元测试
*/
@Test
public void saveOrUpdateAll_SaveTest() {
List<User> userList = asList(getRandomUser()
, getRandomUser()
, getRandomUser()
);
userRepository.saveOrUpdateAll(userList);
}
/**
* 对saveOrUpdateAll的单元测试
*/
@Test
public void saveOrUpdateAll_UpdateTest() {
List<User> userList = asList(getRandomUser()
, getRandomUser()
, getRandomUser()
);
userRepository.saveAll(userList);
userRepository.saveOrUpdateAll(userList);
}
/**
* 对saveOrUpdateAll的单元测试
*/
@SuppressWarnings("ConstantConditions")
@Test(expected = Exception.class)
public void saveOrUpdateAll_NullTest() {
userRepository.saveOrUpdateAll(null);
}
/**
* 对saveOrUpdateAll的单元测试
*/
@Test
public void saveOrUpdateAll_NullListTest() {
userRepository.saveOrUpdateAll(new ArrayList<>());
}
/**
* 对getById的单元测试
*/
@Test
public void getByExistIntegerIdTest() {
Teacher teacher = new Teacher("name", "password");
teacherRepository.save(teacher);
assertEquals(teacher.getId(), teacherRepository.getById(Teacher.class, teacher.getId()).getId());
}
/**
* 对getById的单元测试
*/
@Test
public void getByNotExistIntegerIdTest() {
Teacher byId = teacherRepository.getById(Teacher.class, new Random().nextInt());
assertNull(byId);
}
/**
* 对getById的单元测试
*/
@Test
public void getByExistStringIdTest() {
User admin = getRandomUser();
userRepository.save(admin);
User byId = userRepository.getById(User.class, admin.getUserName());
assertEquals(byId, admin);
}
/**
* 对getById的单元测试
*/
@Test
public void getByNotExistStringIdTest() {
User byId = userRepository.getById(User.class, getRandomUUID());
assertNull(byId);
}
/**
* 对getAll的单元测试
*/
@Test
public void getAllTest() {
List<User> userList = userRepository.getAll(User.class);
System.out.println(userList);
if (userList.size() > 0) {
userList.forEach(System.out::println);
}
assertNotNull(userList);
}
/**
* 对getCount的单元测试
*/
@Test
public void getCountTest() {
int count = userRepository.getCount(User.class);
System.out.println(count);
}
/**
* 对getListByPage的单元测试
*/
@Test
public void getListByPageTest() {
PageResults<User> userPageResults = userRepository.getListByPage(User.class, -7, 2);
List<User> listByPage = userPageResults.getResults();
if (listByPage.size() > 0) {
listByPage.forEach(System.out::println);
}
System.out.println(userPageResults);
assertNotNull(listByPage);
}
/**
* 对getListByPageAndQuery的单元测试
*/
@Test
public void getListByPageAndQueryTest() throws Exception {
Query query = new Query(entityManager);
query.from(User.class)
.whereEqual("userName", "admin");
PageResults<User> listByPageAndQuery = userRepository.getListByPageAndQuery(1, 3, query);
System.out.println(listByPageAndQuery);
List<User> results = listByPageAndQuery.getResults();
if (!results.isEmpty()) {
results.forEach(System.out::println);
}
assertNotNull(results);
}
/**
* 对getListByPageAndQuery的单元测试
*/
@Test
public void getListByPageAndQueryTest2() throws Exception {
Query query = new Query(entityManager);
query.from(User.class)
.whereIsNotNull("userName");
PageResults<User> listByPageAndQuery = userRepository.getListByPageAndQuery(2, 5, query);
List<User> results = listByPageAndQuery.getResults();
System.out.println(listByPageAndQuery);
assertNotNull(results);
}
/**
* 对getPageResultsByQuery的单元测试
*/
@Test
public void getPageResultsByQueryTest() throws Exception {
Query query = new Query(entityManager);
query.from(User.class)
.whereEqual("userName", "admin");
PageResults<User> listByPageAndQuery = userRepository.getListByPageAndQuery(1, 5, query);
List<User> results = listByPageAndQuery.getResults();
assertNotNull(results);
}
/**
* 对getAllByQuery的单元测试
*/
@Test
public void getAllByQueryTest() {
Query query = new Query(User.class, entityManager);
ParameterExpression<Enum> parameter1 = query.createParameter(Enum.class);
ParameterExpression<String> parameter2 = query.createParameter(String.class);
List resultList = query.whereEqual("authorityType", parameter1)
.whereLike("passWord", parameter2)
.createTypedQuery()
.setParameter(parameter1, AuthorityType.College_Level_Admin)
.setParameter(parameter2, "BaseRepository")
.getResultList();
if (resultList != null) {
resultList.forEach(System.out::println);
}
}
/**
* 对getCountByQuery的单元测试
*/
@Test
public void getCountByQueryTest() {
Query query = new Query(entityManager);
query.from(User.class)
.whereEqual("authorityType", AuthorityType.College_Level_Admin);
int countByQuery = userRepository.getCountByQuery(query);
System.out.println(countByQuery);
}
/**
* 对executeSql的单元测试
*/
@Test
public void executeSqlTest() {
String sql = "insert into Teacher (id,name,password) values (?,?,?)";
Random random = new Random();
int i = teacherRepository.executeSql(sql, random.nextInt(), "admin", "admin");//这里数据库名要和大小写一致!!!
assertEquals(1, i);
}
/**
* 对queryByJpql的单元测试
*/
@Test
public void queryByJpqlTest() {
String jpql = "select o from User o where o.passWord = ?0 ";
PageResults<Object> results = userRepository.getListByPageAndJpql(2, 5, jpql, "BaseRepository");
results.getResults().forEach(System.out::println);
}
/**
* 对queryByJpql的单元测试
*/
@Test
public void queryByJpqlTest2() {
String jpql = "select o from User o where 1=1 ";
PageResults<Object> results = userRepository.getListByPageAndJpql(2, 5, jpql);
results.getResults().forEach(System.out::println);
}
/**
* 对getCountByJpql的单元测试
*/
@Test
public void getCountByJpqlTest() {
String jpql = "select COUNT(o) from User o where o.userName = ?0 ";
int result = userRepository.getCountByJpql(jpql, "admin");
assertEquals(result, 1);
}
/**
* 对getListByPageAndJpql的单元测试
*/
@Test
public void getListByPageAndJpqlTest() {
String jpql = "select o from User o where o.userName = ?0 ";
PageResults<Object> pageResults = userRepository.getListByPageAndJpql(1, 5, jpql, "admin");
assertNotNull(pageResults);
}
/**
* 对executeJpql的单元测试
*/
@Test
public void executeJpqlTest() {
String jpql = "update User u set u.passWord=?0 where u.userName = ?1 ";
int result = userRepository.executeJpql(jpql, "admin", "admin");
assertEquals(result, 1);
}
/**
* 对refresh的单元测试
*/
@Test(expected = Exception.class)
public void refreshExistTest() {
User randomUser = getRandomUser();
userRepository.save(randomUser);
userRepository.refresh(randomUser);
}
/**
* 对refresh的单元测试
*/
@Test(expected = Exception.class)
public void refreshNotExistTest() {
userRepository.refresh(getRandomUser());
}
/**
* 对flush的单元测试
*/
@Test
public void flushTest() {
userRepository.flush();
}
}
| 26.172973 | 105 | 0.61889 |
05c6701ab6dfd1ebc02b68d4c438c682fb55625f | 4,688 | /*
* 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 rocks.prestodb.rest;
import io.prestosql.spi.connector.*;
import io.prestosql.spi.type.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import static java.util.stream.Collectors.toList;
public class RestRecordSetProvider
implements ConnectorRecordSetProvider
{
private final Rest rest;
public RestRecordSetProvider(Rest rest)
{
this.rest = rest;
}
@Override
public RecordSet getRecordSet(
ConnectorTransactionHandle transactionHandle,
ConnectorSession session,
ConnectorSplit split,
ConnectorTableHandle table,
List<? extends ColumnHandle> columns)
{
RestConnectorSplit restSplit = Types.checkType(split, RestConnectorSplit.class, "split");
List<RestColumnHandle> restColumnHandles = (List<RestColumnHandle>) columns;
RestTableHandle tableHandle = (RestTableHandle) table;
SchemaTableName schemaTableName = tableHandle.getSchemaTableName();
Collection<? extends List<?>> rows = rest.getRows(schemaTableName);
ConnectorTableMetadata tableMetadata = rest.getTableMetadata(schemaTableName);
List<Integer> columnIndexes = restColumnHandles.stream()
.map(column -> {
int index = 0;
for (ColumnMetadata columnMetadata : tableMetadata.getColumns()) {
if (columnMetadata.getName().equalsIgnoreCase(column.getName())) {
return index;
}
index++;
}
throw new IllegalStateException("Unknown column: " + column.getName());
})
.collect(toList());
Collection<? extends List<?>> mappedRows = rows.stream()
.map(row -> columnIndexes.stream()
.map(index -> row.get(index))
.collect(toList()))
.collect(toList());
List<Type> mappedTypes = restColumnHandles.stream()
.map(RestColumnHandle::getType)
.collect(toList());
return new InMemoryRecordSet(mappedTypes, mappedRows);
}
//
// @Override
// public RecordSet getRecordSet(
// ConnectorTransactionHandle connectorTransactionHandle,
// ConnectorSession connectorSession,
// ConnectorSplit connectorSplit,
// List<? extends ColumnHandle> list)
// {
// RestConnectorSplit split = Types.checkType(connectorSplit, RestConnectorSplit.class, "split");
// // TODO fix below cast
// List<RestColumnHandle> restColumnHandles = (List<RestColumnHandle>) list;
//
// SchemaTableName schemaTableName = split.getTableHandle().getSchemaTableName();
// Collection<? extends List<?>> rows = rest.getRows(schemaTableName);
// ConnectorTableMetadata tableMetadata = rest.getTableMetadata(schemaTableName);
//
// List<Integer> columnIndexes = restColumnHandles.stream()
// .map(column -> {
// int index = 0;
// for (ColumnMetadata columnMetadata : tableMetadata.getColumns()) {
// if (columnMetadata.getName().equalsIgnoreCase(column.getName())) {
// return index;
// }
// index++;
// }
// throw new IllegalStateException("Unknown column: " + column.getName());
// })
// .collect(toList());
//
// Collection<? extends List<?>> mappedRows = rows.stream()
// .map(row -> columnIndexes.stream()
// .map(index -> row.get(index))
// .collect(toList()))
// .collect(toList());
//
// List<Type> mappedTypes = restColumnHandles.stream()
// .map(RestColumnHandle::getType)
// .collect(toList());
// return new InMemoryRecordSet(mappedTypes, mappedRows);
// }
}
| 39.394958 | 104 | 0.598976 |
e318d0fa1d688337567fb2cb6a6e68082e924384 | 987 | package crazypants.enderio.integration.tic.fluids;
import javax.annotation.Nonnull;
import com.enderio.core.common.fluid.BlockFluidEnder;
import crazypants.enderio.base.teleport.RandomTeleportUtil;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fluids.Fluid;
public class MoltenEnder extends BlockFluidEnder {
public MoltenEnder(@Nonnull Fluid fluid, @Nonnull Material material, int fogColor) { // 0xff0000
super(fluid, material, fogColor);
}
@Override
public void onEntityCollidedWithBlock(@Nonnull World world, @Nonnull BlockPos pos, @Nonnull IBlockState state, @Nonnull Entity entity) {
if (!world.isRemote && entity.timeUntilPortal == 0) {
RandomTeleportUtil.teleportEntity(world, entity, false);
}
super.onEntityCollidedWithBlock(world, pos, state, entity);
}
} | 34.034483 | 138 | 0.785208 |
20e26b5ece2b887c40fea417b25b67e45d5e6d0d | 5,203 | /*
* MIT License
*
* Copyright (c) 2022 MaxWainer
*
* 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 dev.framework.orm.benchmark;
import dev.framework.orm.api.ORMFacade;
import dev.framework.orm.api.ORMProvider;
import dev.framework.orm.api.credentials.ConnectionCredentials;
import dev.framework.orm.api.exception.MissingFacadeException;
import dev.framework.orm.api.exception.MissingRepositoryException;
import dev.framework.orm.api.exception.QueryNotCompletedException;
import dev.framework.orm.api.exception.UnsupportedQueryConcatenationQuery;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
// Benchmark Mode Cnt Score
// Error Units
// QueryBuildingBenchmark.benchmarkSubQuery thrpt 25 487.234 ±
// 29.876 ops/ms
// QueryBuildingBenchmark.benchmarkSubQuery avgt 25 0.003 ±
// 0.001 ms/op
// QueryBuildingBenchmark.benchmarkSubQuery sample 7576715 0.002 ±
// 0.001 ms/op
// QueryBuildingBenchmark.benchmarkSubQuery:benchmarkSubQuery·p0.00 sample 0.002
// ms/op
// QueryBuildingBenchmark.benchmarkSubQuery:benchmarkSubQuery·p0.50 sample 0.002
// ms/op
// QueryBuildingBenchmark.benchmarkSubQuery:benchmarkSubQuery·p0.90 sample 0.003
// ms/op
// QueryBuildingBenchmark.benchmarkSubQuery:benchmarkSubQuery·p0.95 sample 0.003
// ms/op
// QueryBuildingBenchmark.benchmarkSubQuery:benchmarkSubQuery·p0.99 sample 0.005
// ms/op
// QueryBuildingBenchmark.benchmarkSubQuery:benchmarkSubQuery·p0.999 sample 0.046
// ms/op
// QueryBuildingBenchmark.benchmarkSubQuery:benchmarkSubQuery·p0.9999 sample 0.561
// ms/op
// QueryBuildingBenchmark.benchmarkSubQuery:benchmarkSubQuery·p1.00 sample 58.065
// ms/op
// QueryBuildingBenchmark.benchmarkSubQuery ss 5 0.139 ±
// 0.168 ms/op
@BenchmarkMode(Mode.All)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 5, timeUnit = TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
public class QueryBuildingBenchmark {
private final ORMFacade facade;
public QueryBuildingBenchmark() {
try {
this.facade =
ORMProvider.instance()
.createFacade(
ConnectionCredentials.of(
"dev.framework.orm.implementation.sqlite.SQLiteORMFacade",
"jdbc:sqlite:database.db"));
facade.open();
} catch (MissingFacadeException | MissingRepositoryException e) {
throw new RuntimeException(e);
}
}
// @Benchmark
// public void facadeInit() throws MissingFacadeException {
// final ORMFacade facade =
// ORMProvider.instance().createFacade(ConnectionCredentials.of("", "jdbc:sqlite:database.db"));
// }
@Benchmark
public void benchmarkSubQuery() {
try {
final String query = facade
.queryFactory()
.select()
.columns("1", "2", "3", "4", "5", "6", "7", "8", "9", "10")
.from("one")
.whereAnd()
.subQuery(facade.queryFactory().select().everything().from("two"))
.append(" >= 10")
.buildQuery();
} catch (UnsupportedQueryConcatenationQuery | QueryNotCompletedException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws RunnerException {
final Options opt =
new OptionsBuilder().include(QueryBuildingBenchmark.class.getSimpleName()).build();
new Runner(opt).run();
}
}
| 41.293651 | 103 | 0.687104 |
1b75bff093bbd28c8889289e80096e0a07740faf | 1,402 | /*
* 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.unomi.api;
/**
* The interface for unomi plugins.
*/
public interface PluginType {
/**
* Retrieves the plugin identifier, corresponding to the identifier of the OSGi bundle implementing the plugin.
*
* @return the plugin identifier, corresponding to the identifier of the OSGi bundle implementing the plugin
*/
long getPluginId();
/**
* Associates this plugin with its associated OSGi bundle identifier.
*
* @param pluginId the OSGi bundle identifier associated with this plugin
*/
void setPluginId(long pluginId);
}
| 35.05 | 115 | 0.729672 |
3ed580695aa92ac1b1d92da8288b713918822da2 | 2,506 | /* Copyright (C) 2013-2019 TU Dortmund
* This file is part of LearnLib, http://www.learnlib.de/.
*
* 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.learnlib.api;
import org.checkerframework.checker.nullness.qual.NonNull;
/**
* A System Under Learning (SUL) where at any point in time the internal state can be observed.
*
* The main purpose of this interface is to check whether infinite words are accepted by the SUL.
*
* @param <S> the state type
* @param <I> the input type
* @param <O> the output type
*
* @author Jeroen Meijer
*/
public interface ObservableSUL<S, I, O> extends SUL<I, O> {
@NonNull
@Override
default ObservableSUL<S, I, O> fork() {
throw new UnsupportedOperationException();
}
/**
* Returns the current state of the system.
*
* Implementation note: it is important that the returned Object has a well-defined {@link Object#equals(Object)}
* method, and a good {@link Object#hashCode()} function.
*
* @return the current state of the system.
*/
@NonNull
S getState();
/**
* Returns whether each state retrieved with {@link #getState()} is a deep copy.
*
* A state is a deep copy if calls to either {@link #step(Object)}, {@link #pre()}, or {@link #post()} do not modify
* any state previously obtained with {@link #getState()}.
*
* More formally (assuming a perfect hash function): the result must be false if there is a case where in the
* following statements the assertion does not hold:
* {@code Object o = getState(); int hc = o.hashCode(); [step(...)|pre()|post()]; assert o.hashCode() == hc;}
*
* Furthermore, if states can be retrieved, but each state is not a deep copy, then this SUL <b>must</b> be
* forkable, i.e. if !{@link #deepCopies()} then {@link #canFork()} must hold.
*
* @return whether each state is a deep copy.
*/
default boolean deepCopies() {
return false;
}
}
| 36.318841 | 120 | 0.665603 |
6e0317b33381806822e8bf26f4cd38654af67f2d | 399 | package com.liyongquan.stack;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import static org.junit.Assert.*;
@Slf4j
public class MaxStackTest {
@Test
public void test() {
MaxStack ms = new MaxStack();
ms.push(5);
ms.push(1);
int max = ms.popMax();
log.info("{}", max);
int res = ms.peekMax();
log.info("{}",res);
}
} | 19.95 | 37 | 0.568922 |
228a96d2ba52abe5eaff3f162c92528dbc3c028f | 3,797 | /*
* Copyright 2015 Chidiebere Okwudire.
*
* 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.parse4cn1.util;
import com.codename1.io.Externalizable;
import com.codename1.io.Storage;
import com.codename1.io.Util;
import com.parse4cn1.Parse;
import com.parse4cn1.ParseConstants;
import com.parse4cn1.ParseException;
import com.parse4cn1.ParseObject;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
/**
* A wrapper around the {@link com.parse4cn1.ParseObject} class to make it
* externalizable.
*/
public class ExternalizableParseObject<T extends ParseObject> implements Externalizable {
private T parseObject;
private String className;
public ExternalizableParseObject() {
}
public ExternalizableParseObject(final T parseObject) {
if (parseObject == null) {
throw new NullPointerException("Null ParseObject cannot be serialized");
}
this.parseObject = parseObject;
className = parseObject.getClassName();
if (className == null) {
throw new NullPointerException("Object cannot be serialized (className is null)");
}
}
/**
* @return A unique class name.
*/
public static String getClassName() {
return "ExternalizableParseObject";
}
/**
* @return The {@link java.util.Date} wrapped by this object.
*/
public T getParseObject() {
return parseObject;
}
/**
* @see com.codename1.io.Externalizable
*/
public int getVersion() {
return Parse.getSerializationVersion();
}
/**
* @see com.codename1.io.Externalizable
*/
public void externalize(DataOutputStream out) throws IOException {
if (parseObject != null) {
try {
Util.writeUTF(className, out);
parseObject.externalize(out);
} catch (ParseException ex) {
Logger.getInstance().error(
"Unable to serialize ParseObject with objectId=" + parseObject.getObjectId());
throw new IOException(ex.getMessage());
}
}
}
/**
* @see com.codename1.io.Externalizable
*/
public void internalize(int version, DataInputStream in) throws IOException {
className = Util.readUTF(in);
if (className != null) {
parseObject = ParseObject.create(className);
try {
parseObject.internalize(version, in);
} catch (ParseException ex) {
Logger.getInstance().error(
"An error occurred while trying to deserialize ParseObject");
throw new IOException(ex.getMessage());
}
} else {
final String msg = "Unable to deserialize ParseObject "
+ "(null class name). Is class properly registered?";
Logger.getInstance().error(msg);
throw new RuntimeException(msg);
}
}
/**
* @see com.codename1.io.Externalizable
*/
// Note: This is a unique identifier for this class not individual objects serialized by it!
public String getObjectId() {
return getClassName();
}
}
| 31.380165 | 102 | 0.629444 |
b17df47189872196371e6c764fe2137fe312c373 | 1,449 | /**
* MuleSoft Examples
* Copyright 2014 MuleSoft, Inc.
*
* This product includes software developed at
* MuleSoft, Inc. (http://www.mulesoft.com/).
*/
package com.mulesoft.se.orders;
import java.io.ByteArrayOutputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.mule.api.transformer.TransformerException;
import org.mule.config.i18n.Message;
import org.mule.config.i18n.MessageFactory;
import org.mule.transformer.AbstractTransformer;
/**
* Converts an item to XML.
*
* @author Derek
*/
public class ItemAsXml extends AbstractTransformer {
/*
* (non-Javadoc)
*
* @see
* org.mule.transformer.AbstractTransformer#doTransform(java.lang.Object,
* java.lang.String)
*/
protected Object doTransform(Object payload, String encoding)
throws TransformerException {
try {
OrderItem item = (OrderItem) payload;
JAXBContext context = JAXBContext.newInstance(OrderItem.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
Boolean.TRUE);
ByteArrayOutputStream output = new ByteArrayOutputStream();
marshaller.marshal(item, output);
return new String(output.toByteArray());
} catch (JAXBException e) {
Message message = MessageFactory
.createStaticMessage("Unable to marshal OrderItem.");
throw new TransformerException(message, this, e);
}
}
} | 27.339623 | 74 | 0.750173 |
0bf611ebb3fe20e9883a56b3a0c67a8819ff030a | 884 | package mod.vemerion.programmerschest.computer.program;
import mod.vemerion.programmerschest.computer.Console;
import mod.vemerion.programmerschest.computer.filesystem.FileSystem;
import mod.vemerion.programmerschest.computer.filesystem.FileSystemException;
import net.minecraft.entity.player.PlayerEntity;
public class CdProgram extends Program {
public CdProgram(String[] args) {
super(args);
}
@Override
public boolean isClientOnlyProgram() {
return false;
}
@Override
public void run(Console console, FileSystem fileSystem, PlayerEntity user) {
if (needHelp()) {
console.println("Usage: cd [folder]. Change current folder. Use '..' to go up one folder.", user);
}
try {
fileSystem.cd(args.length < 2 ? "" : args[1]);
console.setPath(fileSystem.pwd(), user);
} catch (FileSystemException e) {
console.println(e.getMessage(), user);
}
}
}
| 26 | 101 | 0.739819 |
a405bccd04cef4036551c38233385e027a382d89 | 2,507 | /*
Derby - Class org.apache.derby.ui.common.CommonNames
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.derby.ui.common;
public class CommonNames {
//Network Server related
public static String DERBY_SERVER_CLASS="org.apache.derby.drda.NetworkServerControl";
public static String DERBY_SERVER="Derby Network Server";
public static String START_DERBY_SERVER="start";
public static String SHUTDOWN_DERBY_SERVER="shutdown";
//Tools related
public static String SYSINFO_CLASS="org.apache.derby.tools.sysinfo";
public static String SYSINFO="SYSINFO";
public static String IJ_CLASS="org.apache.derby.tools.ij";
public static String IJ="IJ";
public static String SQL_SCRIPT="SQL Script";
//actual information
public static String CORE_PATH="org.apache.derby.core";
public static String UI_PATH="org.apache.derby.ui";
public static String PLUGIN_NAME="Apache Derby Ui Plug-in";
//The next to be used with UI_PATH for adding nature. isrunning and decorator
public static String DERBY_NATURE=UI_PATH+"."+"derbyEngine";
public static String ISRUNNING="isrun";
public static String RUNDECORATOR=UI_PATH+"."+"DerbyIsRunningDecorator";
//Launch Config Types
public static String START_SERVER_LAUNCH_CONFIG_TYPE=UI_PATH+".startDerbyServerLaunchConfigurationType";
public static String STOP_SERVER_LAUNCH_CONFIG_TYPE=UI_PATH+".stopDerbyServerLaunchConfigurationType";
public static String IJ_LAUNCH_CONFIG_TYPE=UI_PATH+".ijDerbyLaunchConfigurationType";
public static String SYSINFO_LAUNCH_CONFIG_TYPE=UI_PATH+".sysinfoDerbyLaunchConfigurationType";
//JVM Poperties
public static String D_IJ_PROTOCOL=" -Dij.protocol=";
public static String DERBY_PROTOCOL="jdbc:derby:";
public static String D_SYSTEM_HOME=" -Dderby.system.home=";
}
| 41.098361 | 105 | 0.797766 |
d25c4a444405418149dba1ef560cb1845984577c | 427 | package org.seal.starsaber.sealstarsaberinitializer.initializer.Generator;
import io.spring.initializr.generator.ProjectRequest;
import java.util.Map;
/**
* @author seal
* @version v1.0
* @description
* @createTime 2018-09-30 13:29
* @email
*/
public class StarSaberGenerator{
public static void generator(ProjectRequest request, Map<String, Object> model){
}
public void starSaberGenerator(){
}
}
| 17.791667 | 84 | 0.730679 |
8167ad6cceb9471ac12b0568ae9ff1f763f23c4a | 506 | package org.redquark.demo.core.services.Impl;
import org.osgi.service.component.annotations.Component;
import static org.redquark.demo.core.constants.AppConstants.URL;
import org.redquark.demo.core.services.ReadJsonService;
import org.redquark.demo.core.utils.Network;
@Component(immediate = true, service = ReadJsonService.class)
public class ReadJsonDataImpl implements ReadJsonService {
@Override
public String getData() {
String response = Network.readJson(URL);
return response;
}
} | 25.3 | 64 | 0.79249 |
c90ff100fef3b1327488c4e77b30968daf95b8e4 | 2,406 |
package com.prowidesoftware.swift.model.mx.dic;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* Choice of proxy allowance.
*
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Proxy1Choice", propOrder = {
"prxy",
"prxyNotAllwd"
})
public class Proxy1Choice {
@XmlElement(name = "Prxy")
protected ProxyAppointmentInformation2 prxy;
@XmlElement(name = "PrxyNotAllwd")
@XmlSchemaType(name = "string")
protected ProxyNotAllowedCode prxyNotAllwd;
/**
* Gets the value of the prxy property.
*
* @return
* possible object is
* {@link ProxyAppointmentInformation2 }
*
*/
public ProxyAppointmentInformation2 getPrxy() {
return prxy;
}
/**
* Sets the value of the prxy property.
*
* @param value
* allowed object is
* {@link ProxyAppointmentInformation2 }
*
*/
public Proxy1Choice setPrxy(ProxyAppointmentInformation2 value) {
this.prxy = value;
return this;
}
/**
* Gets the value of the prxyNotAllwd property.
*
* @return
* possible object is
* {@link ProxyNotAllowedCode }
*
*/
public ProxyNotAllowedCode getPrxyNotAllwd() {
return prxyNotAllwd;
}
/**
* Sets the value of the prxyNotAllwd property.
*
* @param value
* allowed object is
* {@link ProxyNotAllowedCode }
*
*/
public Proxy1Choice setPrxyNotAllwd(ProxyNotAllowedCode value) {
this.prxyNotAllwd = value;
return this;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
@Override
public boolean equals(Object that) {
return EqualsBuilder.reflectionEquals(this, that);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
| 24.06 | 88 | 0.650873 |
4fa37cf4dd6f8d0510720e155d0726ab7bede4dc | 1,441 | /*
* 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 testify.bus;
import testify.streams.BiStream;
public enum Buses {
;
public static String dump(Bus bus) {
return String.format("Bus[%s]%n%s", bus.user(), dump(bus.biStream()));
}
public static String dump(SimpleBus bus) {
return String.format("%s%n%s", bus, dump(bus.biStream()));
}
static String dump(BiStream<String, String> bis) {
StringBuilder sb = new StringBuilder("{");
bis.forEach((k, v) -> sb.append("\n\t").append(k).append(" -> ").append(v));
if (sb.length() == 1) return "{}";
sb.append("\n}");
return sb.toString();
}
}
| 36.948718 | 84 | 0.671756 |
15fdfdc9d634131e50b82384f53fb50bad2ec96e | 12,298 | // Copyright (c) 2019, the R8 project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
package com.android.tools.r8.retrace.internal;
import static com.android.tools.r8.naming.MemberNaming.NoSignature.NO_SIGNATURE;
import static com.android.tools.r8.retrace.internal.RetraceUtils.synthesizeFileName;
import com.android.tools.r8.naming.ClassNamingForNameMapper;
import com.android.tools.r8.naming.ClassNamingForNameMapper.MappedRange;
import com.android.tools.r8.naming.ClassNamingForNameMapper.MappedRangesOfName;
import com.android.tools.r8.naming.MemberNaming;
import com.android.tools.r8.naming.mappinginformation.MappingInformation;
import com.android.tools.r8.references.ClassReference;
import com.android.tools.r8.references.Reference;
import com.android.tools.r8.references.TypeReference;
import com.android.tools.r8.retrace.RetraceClassResult;
import com.android.tools.r8.retrace.RetraceFrameResult;
import com.android.tools.r8.retrace.Retracer;
import com.android.tools.r8.utils.Pair;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.stream.Stream;
public class RetraceClassResultImpl implements RetraceClassResult {
private final ClassReference obfuscatedReference;
private final ClassNamingForNameMapper mapper;
private final Retracer retracer;
private RetraceClassResultImpl(
ClassReference obfuscatedReference, ClassNamingForNameMapper mapper, Retracer retracer) {
this.obfuscatedReference = obfuscatedReference;
this.mapper = mapper;
this.retracer = retracer;
}
static RetraceClassResultImpl create(
ClassReference obfuscatedReference, ClassNamingForNameMapper mapper, Retracer retracer) {
return new RetraceClassResultImpl(obfuscatedReference, mapper, retracer);
}
@Override
public RetraceFieldResultImpl lookupField(String fieldName) {
return lookupField(FieldDefinition.create(obfuscatedReference, fieldName));
}
@Override
public RetraceFieldResultImpl lookupField(String fieldName, TypeReference fieldType) {
return lookupField(
FieldDefinition.create(Reference.field(obfuscatedReference, fieldName, fieldType)));
}
@Override
public RetraceMethodResultImpl lookupMethod(String methodName) {
return lookupMethod(MethodDefinition.create(obfuscatedReference, methodName));
}
@Override
public RetraceMethodResultImpl lookupMethod(
String methodName, List<TypeReference> formalTypes, TypeReference returnType) {
return lookupMethod(
MethodDefinition.create(
Reference.method(obfuscatedReference, methodName, formalTypes, returnType)));
}
private RetraceFieldResultImpl lookupField(FieldDefinition fieldDefinition) {
return lookup(
fieldDefinition,
(mapper, name) -> {
List<MemberNaming> memberNamings = mapper.mappedFieldNamingsByName.get(name);
if (memberNamings == null || memberNamings.isEmpty()) {
return null;
}
return memberNamings;
},
RetraceFieldResultImpl::new);
}
private RetraceMethodResultImpl lookupMethod(MethodDefinition methodDefinition) {
return lookup(
methodDefinition,
(mapper, name) -> {
MappedRangesOfName mappedRanges = mapper.mappedRangesByRenamedName.get(name);
if (mappedRanges == null || mappedRanges.getMappedRanges().isEmpty()) {
return null;
}
return mappedRanges.getMappedRanges();
},
RetraceMethodResultImpl::new);
}
private <T, R, D extends Definition> R lookup(
D definition,
BiFunction<ClassNamingForNameMapper, String, T> lookupFunction,
ResultConstructor<T, R, D> constructor) {
List<Pair<ElementImpl, T>> mappings = new ArrayList<>();
internalStream()
.forEach(
element -> {
if (mapper != null) {
assert element.mapper != null;
T mappedElements = lookupFunction.apply(element.mapper, definition.getName());
if (mappedElements != null) {
mappings.add(new Pair<>(element, mappedElements));
return;
}
}
mappings.add(new Pair<>(element, null));
});
return constructor.create(this, mappings, definition, retracer);
}
@Override
public RetraceFrameResultImpl lookupFrame(String methodName) {
return lookupFrame(MethodDefinition.create(obfuscatedReference, methodName), -1);
}
@Override
public RetraceFrameResultImpl lookupFrame(String methodName, int position) {
return lookupFrame(MethodDefinition.create(obfuscatedReference, methodName), position);
}
@Override
public RetraceFrameResultImpl lookupFrame(
String methodName, int position, List<TypeReference> formalTypes, TypeReference returnType) {
return lookupFrame(
MethodDefinition.create(
Reference.method(obfuscatedReference, methodName, formalTypes, returnType)),
position);
}
private RetraceFrameResultImpl lookupFrame(MethodDefinition definition, int position) {
List<Pair<ElementImpl, List<MappedRange>>> mappings = new ArrayList<>();
internalStream()
.forEach(
element ->
mappings.add(
new Pair<>(element, getMappedRangesForFrame(element, definition, position))));
return new RetraceFrameResultImpl(this, mappings, definition, position, retracer);
}
private List<MappedRange> getMappedRangesForFrame(
ElementImpl element, MethodDefinition definition, int position) {
if (mapper == null) {
return null;
}
assert element.mapper != null;
MappedRangesOfName mappedRanges = mapper.mappedRangesByRenamedName.get(definition.getName());
if (mappedRanges == null || mappedRanges.getMappedRanges().isEmpty()) {
return null;
}
if (position <= 0) {
return mappedRanges.getMappedRanges();
}
List<MappedRange> mappedRangesForPosition = mappedRanges.allRangesForLine(position, false);
return mappedRangesForPosition.isEmpty()
? mappedRanges.getMappedRanges()
: mappedRangesForPosition;
}
@Override
public boolean hasRetraceResult() {
return mapper != null;
}
@Override
public Stream<Element> stream() {
return Stream.of(createElement());
}
private Stream<ElementImpl> internalStream() {
return Stream.of(createElement());
}
private ElementImpl createElement() {
return new ElementImpl(
this,
RetracedClassImpl.create(
mapper == null
? obfuscatedReference
: Reference.classFromTypeName(mapper.originalName)),
mapper);
}
@Override
public RetraceClassResultImpl forEach(Consumer<Element> resultConsumer) {
stream().forEach(resultConsumer);
return this;
}
private interface ResultConstructor<T, R, D> {
R create(
RetraceClassResultImpl classResult,
List<Pair<ElementImpl, T>> mappings,
D definition,
Retracer retracer);
}
@Override
public boolean isAmbiguous() {
// Currently we have no way of producing ambiguous class results.
return false;
}
public static class ElementImpl implements Element {
private final RetraceClassResultImpl classResult;
private final RetracedClassImpl classReference;
private final ClassNamingForNameMapper mapper;
public ElementImpl(
RetraceClassResultImpl classResult,
RetracedClassImpl classReference,
ClassNamingForNameMapper mapper) {
this.classResult = classResult;
this.classReference = classReference;
this.mapper = mapper;
}
@Override
public RetracedClassImpl getRetracedClass() {
return classReference;
}
@Override
public RetraceClassResultImpl getRetraceClassResult() {
return classResult;
}
@Override
public RetraceSourceFileResultImpl retraceSourceFile(String sourceFile) {
if (mapper != null && mapper.getAdditionalMappings().size() > 0) {
List<MappingInformation> mappingInformations =
mapper.getAdditionalMappings().get(NO_SIGNATURE);
if (mappingInformations != null) {
for (MappingInformation mappingInformation : mappingInformations) {
if (mappingInformation.isFileNameInformation()) {
return new RetraceSourceFileResultImpl(
mappingInformation.asFileNameInformation().getFileName(), false);
}
}
}
}
return new RetraceSourceFileResultImpl(
synthesizeFileName(
classReference.getTypeName(),
classResult.obfuscatedReference.getTypeName(),
sourceFile,
mapper != null),
true);
}
@Override
public RetraceFieldResultImpl lookupField(String fieldName) {
return lookupField(FieldDefinition.create(classReference.getClassReference(), fieldName));
}
private RetraceFieldResultImpl lookupField(FieldDefinition fieldDefinition) {
return lookup(
fieldDefinition,
(mapper, name) -> {
List<MemberNaming> memberNamings = mapper.mappedFieldNamingsByName.get(name);
if (memberNamings == null || memberNamings.isEmpty()) {
return null;
}
return memberNamings;
},
RetraceFieldResultImpl::new);
}
@Override
public RetraceMethodResultImpl lookupMethod(String methodName) {
return lookupMethod(MethodDefinition.create(classReference.getClassReference(), methodName));
}
private RetraceMethodResultImpl lookupMethod(MethodDefinition methodDefinition) {
return lookup(
methodDefinition,
(mapper, name) -> {
MappedRangesOfName mappedRanges = mapper.mappedRangesByRenamedName.get(name);
if (mappedRanges == null || mappedRanges.getMappedRanges().isEmpty()) {
return null;
}
return mappedRanges.getMappedRanges();
},
RetraceMethodResultImpl::new);
}
private <T, R, D extends Definition> R lookup(
D definition,
BiFunction<ClassNamingForNameMapper, String, T> lookupFunction,
ResultConstructor<T, R, D> constructor) {
List<Pair<ElementImpl, T>> mappings = ImmutableList.of();
if (mapper != null) {
T result = lookupFunction.apply(mapper, definition.getName());
if (result != null) {
mappings = ImmutableList.of(new Pair<>(this, result));
}
}
if (mappings.isEmpty()) {
mappings = ImmutableList.of(new Pair<>(this, null));
}
return constructor.create(classResult, mappings, definition, classResult.retracer);
}
@Override
public RetraceFrameResultImpl lookupFrame(String methodName) {
return lookupFrame(methodName, -1);
}
@Override
public RetraceFrameResultImpl lookupFrame(String methodName, int position) {
return lookupFrame(
MethodDefinition.create(classReference.getClassReference(), methodName), position);
}
@Override
public RetraceFrameResult lookupFrame(
String methodName,
int position,
List<TypeReference> formalTypes,
TypeReference returnType) {
return lookupFrame(
MethodDefinition.create(
Reference.method(
classReference.getClassReference(), methodName, formalTypes, returnType)),
position);
}
private RetraceFrameResultImpl lookupFrame(MethodDefinition definition, int position) {
MethodDefinition methodDefinition =
MethodDefinition.create(classReference.getClassReference(), definition.getName());
return new RetraceFrameResultImpl(
classResult,
ImmutableList.of(
new Pair<>(
this, classResult.getMappedRangesForFrame(this, methodDefinition, position))),
methodDefinition,
position,
classResult.retracer);
}
}
}
| 35.237822 | 99 | 0.689462 |
be217e1bd54406e9635d2eca746497dbfb5ac4da | 7,104 | package com.i5lu.boarder;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Component;
import java.awt.Composite;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.UIManager;
import javax.swing.border.AbstractBorder;
import javax.swing.border.Border;
import com.jtattoo.plaf.*;
public class JTBorderFactory {
private JTBorderFactory()
{ }
public static Border createTitleBorder(Icon icon)
{ return new TitleBorder(icon, "", 3, 4); }
public static Border createTitleBorder(String title)
{ return new TitleBorder(null, title, 3, 4); }
public static Border createTitleBorder(Icon icon, String title)
{ return new TitleBorder(icon, title, 3, 4); }
public static Border createTitleBorder(Icon icon, String title, int shadowSize)
{ return new TitleBorder(icon, title, Math.max(Math.min(shadowSize, 32), 0), 4); }
public static Border createTitleBorder(Icon icon, String title, int shadowSize, int innerSpace)
{ return new TitleBorder(icon, title, Math.max(Math.min(shadowSize, 32), 0), Math.max(Math.min(innerSpace, 32), 0)); }
//------------------------------------------------------------------------------------------------------------
// Border classes
//------------------------------------------------------------------------------------------------------------
public static class TitleBorder extends AbstractBorder {
private static final long serialVersionUID = -4951047628928709294L;
private Icon icon = null;
private String title = null;
private int shadowSize = 3;
private int innerSpace = 4;
public TitleBorder(Icon aIcon, String aTitle, int aShadowSize, int aInnerSpace) {
icon = aIcon;
title = aTitle;
shadowSize = aShadowSize;
innerSpace = aInnerSpace;
}
public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) {
Graphics2D g2D = (Graphics2D)g;
Composite composite = g2D.getComposite();
Color hiFrameColor = null;
Color loFrameColor = null;
Color hiBackColor = null;
Color loBackColor = null;
Color textColor = null;
if (UIManager.getLookAndFeel() instanceof AbstractLookAndFeel) {
hiFrameColor = AbstractLookAndFeel.getControlHighlight();
loFrameColor = AbstractLookAndFeel.getControlShadow();
hiBackColor = ColorHelper.brighter(AbstractLookAndFeel.getBackgroundColor(), 20);
loBackColor = ColorHelper.darker(AbstractLookAndFeel.getBackgroundColor(), 5);
textColor = AbstractLookAndFeel.getForegroundColor();
}
else {
hiFrameColor = Color.white;
loFrameColor = Color.gray;
hiBackColor = ColorHelper.brighter(c.getBackground(), 30.0f);
loBackColor = ColorHelper.darker(c.getBackground(), 10.0f);
textColor = c.getForeground();
}
int titleHeight = getBorderInsets(c).top - 3 - innerSpace;
g.setColor(loFrameColor);
g.drawRect(x, y, w - shadowSize - 1, h - shadowSize - 1);
g.setColor(hiFrameColor);
g.drawRect(x + 1, y + 1, w - shadowSize - 3, h - shadowSize - 3);
g.setColor(loFrameColor);
g.drawLine(x + 2, y + getBorderInsets(c).top - innerSpace - 1, x + w - shadowSize - 3, y + getBorderInsets(c).top - innerSpace - 1);
// paint the shadow
if (shadowSize > 0) {
g2D.setColor(new Color(0, 16, 0));
float alphaValue = 0.4f;
for (int i = 0; i < shadowSize; i++) {
AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alphaValue);
g2D.setComposite(alpha);
g.drawLine(x + w - shadowSize + i, y + shadowSize + 4, x + w - shadowSize + i, y + h - shadowSize - 1 + i);
g.drawLine(x + shadowSize + 2, y + h - shadowSize + i, x + w - shadowSize + i, y + h - shadowSize + i);
alphaValue -= (alphaValue / 2);
}
}
g2D.setComposite(composite);
Color[] colors = ColorHelper.createColorArr(hiBackColor, loBackColor, 48);
JTattooUtilities.fillVerGradient(g, colors, x + 2, y + 2, w - shadowSize - 4, titleHeight);
paintText(c, g, x, y, w, h, textColor, null);
}
private void paintText(Component c, Graphics g, int x, int y, int w, int h, Color textColor, Color shadowColor) {
boolean leftToRight = JTattooUtilities.isLeftToRight(c);
int sw = w - 8 - (2 * innerSpace);
if (leftToRight)
x += 4 + innerSpace;
else
x = w - 4 - innerSpace;
int titleHeight = getBorderInsets(c).top - 3 - innerSpace;
// paint the icon
if (icon != null) {
int yc = y + 2 + ((titleHeight - icon.getIconHeight()) / 2);
if (leftToRight) {
icon.paintIcon(c, g, x, yc);
x += icon.getIconWidth() + 4;
}
else {
icon.paintIcon(c, g, x - icon.getIconWidth(), yc);
x -= icon.getIconWidth() + 4;
}
sw -= icon.getIconWidth();
}
// paint the text
if ((title != null) && (title.trim().length() > 0)) {
g.setFont(c.getFont());
FontMetrics fm = g.getFontMetrics();
String theTitle = JTattooUtilities.getClippedText(title, fm, sw);
if (!leftToRight)
x -= fm.getStringBounds(theTitle, g).getWidth();
y += fm.getHeight();
if (shadowColor != null) {
g.setColor(shadowColor);
g.drawString(theTitle, x + 1, y + 1);
}
g.setColor(textColor);
if (c instanceof JComponent)
JTattooUtilities.drawString((JComponent)c, g, theTitle, x, y);
else
g.drawString(theTitle, x, y);
}
}
public Insets getBorderInsets(Component c) {
Graphics g = c.getGraphics();
if (g != null) {
FontMetrics fm = g.getFontMetrics(c.getFont());
int frameWidth = 2 + innerSpace;
int titleHeight = fm.getHeight() + (fm.getHeight() / 4);
if (icon != null)
titleHeight = Math.max(titleHeight, icon.getIconHeight() + (icon.getIconHeight() / 4));
return new Insets(titleHeight + frameWidth, frameWidth, frameWidth + shadowSize, frameWidth + shadowSize);
}
return new Insets(0, 0, 0, 0);
}
}
}
| 42.538922 | 144 | 0.542652 |
d96f3c71981c4cabe605dcaf511b9b5a0a358d1a | 4,206 | package org.semanticcloud.semanticEngine.controll;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import javax.annotation.PostConstruct;
import org.semanticcloud.semanticEngine.model.ontology.OntoProperty;
import org.semanticcloud.semanticEngine.model.PropertyOperator;
import org.semanticcloud.semanticEngine.model.ontology.properties.DateTimeProperty;
import org.semanticcloud.semanticEngine.model.ontology.properties.FloatProperty;
import org.semanticcloud.semanticEngine.model.ontology.properties.IntegerProperty;
import org.semanticcloud.semanticEngine.model.ontology.properties.OwlObjectProperty;
import org.semanticcloud.semanticEngine.model.ontology.properties.PropertyOperatorType;
import org.semanticcloud.semanticEngine.model.ontology.properties.StringProperty;
import org.springframework.stereotype.Service;
@Service
public class OperatorService {
private HashMap<Class, List<PropertyOperator>> operatorsMap = new HashMap<>();
public List<PropertyOperator> getOperators(OntoProperty property) {
return operatorsMap.get(property.getClass());
}
private void registerPropertyOperstors(Class clazz, List<PropertyOperator> operators) {
operatorsMap.put(clazz, operators);
}
@PostConstruct
private void init() {
registerPropertyOperstors(StringProperty.class, createStringPropertyRenderer());
registerPropertyOperstors(IntegerProperty.class, createIntegerPropertyRenderer());
registerPropertyOperstors(FloatProperty.class, createFloatPropertyRenderer());
registerPropertyOperstors(DateTimeProperty.class, createDateTimePropertyRenderer());
registerPropertyOperstors(OwlObjectProperty.class, createObjectPropertyRenderer());
}
private List<PropertyOperator> createStringPropertyRenderer() {
List<PropertyOperator> propertyOperators = new LinkedList<>();
propertyOperators.add(new PropertyOperator(PropertyOperatorType.EQUAL_TO.toString(), "is equal to ", true));
return propertyOperators;
}
private List<PropertyOperator> createIntegerPropertyRenderer() {
List<PropertyOperator> propertyOperators = new LinkedList<>();
propertyOperators.add(new PropertyOperator(PropertyOperatorType.EQUAL_TO.toString(), "is equal to ", true));
propertyOperators.add(new PropertyOperator(PropertyOperatorType.GREATER_THAN.toString(), "is greater than "));
propertyOperators.add(new PropertyOperator(PropertyOperatorType.LESS_THAN.toString(), "is less than "));
return propertyOperators;
}
private List<PropertyOperator> createFloatPropertyRenderer() {
List<PropertyOperator> propertyOperators = new LinkedList<>();
propertyOperators.add(new PropertyOperator(PropertyOperatorType.EQUAL_TO.toString(), "is equal to ", true));
propertyOperators.add(new PropertyOperator(PropertyOperatorType.GREATER_THAN.toString(), "is greater than "));
propertyOperators.add(new PropertyOperator(PropertyOperatorType.LESS_THAN.toString(), "is less than "));
return propertyOperators;
}
private List<PropertyOperator> createDateTimePropertyRenderer() {
List<PropertyOperator> propertyOperators = new LinkedList<>();
propertyOperators.add(new PropertyOperator(PropertyOperatorType.EQUAL_TO.toString(), "is equal to "));
propertyOperators.add(new PropertyOperator(PropertyOperatorType.GREATER_THAN.toString(), "is greater than "));
propertyOperators.add(new PropertyOperator(PropertyOperatorType.LESS_THAN.toString(), "is less than "));
return propertyOperators;
}
private List<PropertyOperator> createObjectPropertyRenderer() {
List<PropertyOperator> propertyOperators = new LinkedList<>();
propertyOperators.add(new PropertyOperator(PropertyOperatorType.EQUAL_TO_INDIVIDUAL.toString(), "is equal to individual "));
propertyOperators.add(new PropertyOperator(PropertyOperatorType.DESCRIBED_WITH.toString(), "is described with ", true));
propertyOperators.add(new PropertyOperator(PropertyOperatorType.CONSTRAINED_BY.toString(), "is constrained by"));
return propertyOperators;
}
}
| 52.575 | 132 | 0.775796 |
cd88805af8c1a8b90e3b3fcdb8d6284b3032f4a7 | 7,648 | package com.dian.controller.front;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONObject;
import com.dian.core.DianBaseController;
import com.dian.model.sys.SysUser;
import com.dian.service.sys.CommonService;
import core.cache.OpenIDCache;
import core.util.CacheUtil;
import core.util.DateUtils;
import core.util.DianUtils;
/**
*
*
* @author eyeshot
* @time 2017年09月06日
*/
@Controller
@RequestMapping("/web/")
public class Login extends DianBaseController<SysUser>{
Logger logger = Logger.getLogger(Login.class);
@Resource
private CommonService commonService;
public static Map<String, String> FULL_SESSION_POOL = new ConcurrentHashMap<String, String>();
@RequestMapping(value = "login")
public ModelAndView login() {
logger.info("got to Login page!");
ModelAndView mav = new ModelAndView();
mav.setViewName("wxlogin");
mav.addObject("msg", "hello kitty");
return mav;
}
@RequestMapping(value = "loginout")
public ModelAndView loginout(HttpServletRequest request, HttpServletResponse response)
{
String token = request.getParameter("token");
logger.info("got to Login page!");
ModelAndView mav = new ModelAndView();
mav.setViewName("wxlogin");
if(FULL_SESSION_POOL.containsKey(token))
{
FULL_SESSION_POOL.remove(token);
}
return mav;
}
@RequestMapping(value = "wxhome")
@ResponseBody
public ModelAndView home(HttpServletRequest request, HttpServletResponse response)
{
ModelAndView mav = new ModelAndView();
try
{
logger.info("got to home page!");
String token = request.getParameter("token");
logger.info("token: " + token);
if(token == null)
{
mav.setViewName("wxlogin");
return mav;
}
String openID = FULL_SESSION_POOL.get(token);
logger.info("openID: " + openID);
if(openID == null || openID.length() == 0)
{
mav.setViewName("wxlogin");
return mav;
}
String wxUserSql = "select nickname, headimg from wxuser where openid='"+openID+"'";
List<Object[]> wxUserList = commonService.doExecuteSql(wxUserSql);
String nickName = "";
String avatarurl = "";
if(wxUserList != null && wxUserList.size() > 0)
{
nickName = wxUserList.get(0)[0].toString();
avatarurl = wxUserList.get(0)[1].toString();
}
mav.setViewName("wxhome");
mav.addObject("nickname", nickName);
mav.addObject("headimg", avatarurl);
mav.addObject("token", token);
} catch(Exception e)
{
logger.error("go wxhome has error: " + e);
}
return mav;
}
@RequestMapping("/heart")
@ResponseBody
public void doHeart(HttpServletRequest request, HttpServletResponse response) throws IOException
{
Map<String, Object> ret = new HashMap<String, Object>();
try
{
String jsvalue = request.getParameter("jsvalue");
logger.info("jsvalue: " + jsvalue);
if(FULL_SESSION_POOL.containsKey(jsvalue)) //如果缓存中存在该key,则说明用户已经扫描过了
{
logger.info("return 1....");
ret.put("result", "1");
} else
{
ret.put("result", "0");
}
} catch(Exception e)
{
logger.error("doHeart has error:" , e);
}
writeJSON(response, ret);
}
@RequestMapping(value = "/scan", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> doScan(HttpServletRequest request, @RequestBody Map<String, String> json)
{
Map<String, Object> ret = new HashMap<String, Object>();
try
{
String dianToken = json.get("dian_token");
logger.info("dian_token : " + dianToken);
String openid = OpenIDCache.getCacheMap().get(dianToken).split("#")[0];
logger.info("openID:" + openid);
String jsvalue = json.get("jsvalue");
logger.info("scan jsvalue: " + jsvalue);
FULL_SESSION_POOL.put(jsvalue, openid);
ret.put("data", "success");
} catch(Exception e)
{
logger.error("doHeart has error:" , e);
}
return ret;
}
@RequestMapping(value = "/test", method = RequestMethod.POST, consumes="application/json")
@ResponseBody
public void dotest(HttpServletRequest request, HttpServletResponse response, @RequestBody String param) throws IOException
{
Map<String, Object> ret = new HashMap<String, Object>();
try
{
String token = request.getParameter("dian_token");
logger.info("token : " + token);
String jsvalue = request.getParameter("jsvalue");
logger.info("jsvalue: " + jsvalue);
if(FULL_SESSION_POOL.containsKey(jsvalue)) //如果缓存中存在该key,则说明用户已经扫描过了
{
ret.put("result", "1");
} else
{
ret.put("result", "0");
}
} catch(Exception e)
{
logger.error("doHeart has error:" , e);
}
writeJSON(response, ret);
}
@RequestMapping(value="/upload",method = RequestMethod.POST)
public @ResponseBody void uploadForApp(HttpServletRequest request,HttpServletResponse response,@RequestParam("fileToUpload") MultipartFile file)
throws IllegalStateException, IOException
{
try
{
PrintWriter out = null;
out = response.getWriter();
JSONObject obj = new JSONObject();
logger.info("开始上传文件");
String token = request.getParameter("token");
logger.info("token: " + token);
String openID = FULL_SESSION_POOL.get(token);
logger.info("openID: " + openID);
String originalname = file.getOriginalFilename();
String fileType = originalname.substring(originalname.lastIndexOf("."));
final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String fileName = sdf.format(new Date()) + DianUtils.getRandomString(3) + fileType;
File filePath = new File(getClass().getClassLoader().getResource("/").getPath().replace("/WEB-INF/classes/", "/static/code/"));
if (!filePath.exists()) {
filePath.mkdirs();
}
logger.info("fileName : " + fileName);
// 保存
try {
file.transferTo(new File(filePath.getAbsolutePath() + "/" + fileName));
String rtnNamePath = "/static/code/" + fileName;
//file.transferTo(targetFile);
String currentTime = DateUtils.getDateTime();
//报存上传文件信息到数据库
String insertResourceSql = "insert into market_resource (openid, filepath, filename, originalname, createtime) values ('"+openID+"', '"+rtnNamePath+"', '"+fileName+"', '"+originalname+"', '"+currentTime+"')";
commonService.doInsertUpdateSql(insertResourceSql);
} catch (Exception e)
{
logger.error("upload code has error: ", e);
}
obj.put("msg", "success");
out.print(obj);
//model.addAttribute("fileUrl", request.getContextPath() + "/upload/" + fileName);
} catch(Exception e)
{
logger.error("upload file has error: ", e);
}
// return ret;
}
}
| 29.415385 | 221 | 0.6858 |
ad0473fe6727d0d7d908ec710d6b7cc5122a9761 | 762 | package com.oneoffcoder.java.generic;
public class WildCard {
public static class Data<T extends Number> {
private T[] data;
public Data(T[] data) {
this.data = data;
}
public double getSum() {
double sum = 0.0d;
for (T item : data) {
sum += item.doubleValue();
}
return sum;
}
public T[] getData() {
return data;
}
public boolean isSameLength(Data<?> that) {
return this.data.length == that.data.length;
}
}
public static void main(String[] args) throws Exception {
var data1 = new Data<Integer>(new Integer[] { 1, 2, 3, 4, 9, 10});
var data2 = new Data<Double>(new Double[] { 5d, 6d, 7d, 8d});
System.out.println(data1.isSameLength(data2));
}
}
| 20.594595 | 70 | 0.58399 |
ccdf7c2b06e04a95a65338ebc70dda0a99d3517f | 1,557 | package ru.spb.devclub.liferay.template.portlet.react.portlet;
import ru.spb.devclub.liferay.template.portlet.react.constants.ReactTemplatePortletKeys;
import com.liferay.frontend.js.loader.modules.extender.npm.NPMResolver;
import com.liferay.portal.kernel.portlet.bridges.mvc.MVCPortlet;
import java.io.IOException;
import javax.portlet.Portlet;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
/**
* @author Grig Alex
*/
@Component(
immediate = true,
property = {
"com.liferay.portlet.display-category=" + ReactTemplatePortletKeys.PortletCategory,
"com.liferay.portlet.header-portlet-css=/css/index.css",
"com.liferay.portlet.instanceable=true",
"javax.portlet.init-param.template-path=/",
"javax.portlet.init-param.view-template=/view.jsp",
"javax.portlet.name=" + ReactTemplatePortletKeys.PortletName,
"javax.portlet.resource-bundle=content.Language",
"javax.portlet.security-role-ref=power-user,user"
},
service = Portlet.class
)
public class ReactTemplatePortlet extends MVCPortlet {
@Override
public void doView(
RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {
renderRequest.setAttribute(
"mainRequire",
_npmResolver.resolveModuleName("react-template-portlet") + " as main");
super.doView(renderRequest, renderResponse);
}
@Reference
private NPMResolver _npmResolver;
} | 29.942308 | 88 | 0.791908 |
6dafa9b5b03861c029516d7d70f103f22a84064a | 2,052 | package nl.softcause.jsontemplates.expressions.conversion;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import nl.softcause.jsontemplates.OperatorPrecendence;
import nl.softcause.jsontemplates.expressions.ExpressionParseType;
import nl.softcause.jsontemplates.expressions.IExpression;
import nl.softcause.jsontemplates.expressions.IExpressionWithArguments;
import nl.softcause.jsontemplates.expressions.ReduceOptionalAnnotation;
import nl.softcause.jsontemplates.model.IModel;
import nl.softcause.jsontemplates.model.IModelDefinition;
import nl.softcause.jsontemplates.types.IExpressionType;
import nl.softcause.jsontemplates.types.Types;
@EqualsAndHashCode
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "className")
@ReduceOptionalAnnotation
public class FormatDouble implements IExpressionWithArguments {
@Getter
@JsonInclude
private List<IExpression> arguments;
public FormatDouble() {
this(new ArrayList<>());
}
public FormatDouble(List<IExpression> arguments) {
this.arguments = arguments;
}
@Override
public IExpressionType getReturnType(IModelDefinition model) {
return Types.OPTIONAL_TEXT;
}
@Override
public Object evaluate(IModel model) {
var value = getArguments().get(0).evaluate(model);
if (value != null) {
NumberFormat format = NumberFormat.getInstance(model.getLocale());
return format.format(Types.DECIMAL.convert(value));
}
return null;
}
@Override
public IExpressionType[] getArgumentsTypes() {
return new IExpressionType[] {Types.OPTIONAL_DECIMAL};
}
@Override
public Integer priority() {
return OperatorPrecendence.FUNCTION;
}
@Override
public ExpressionParseType parseType() {
return ExpressionParseType.FUNCTION;
}
}
| 29.314286 | 78 | 0.748538 |
3bcffc204cb3c3704b4761ab4901cb694a28a6c4 | 3,113 | package org.apache.tinkerpop.gremlin.orientdb;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
public class OrientGraphComplexIndexTest extends OrientGraphBaseTest {
@Test
public void compositeIndexSingleSecondFieldTest() {
OrientGraph noTx = factory.getNoTx();
try {
String className = noTx.createVertexClass("Foo");
OClass foo = noTx.getRawDatabase().getMetadata().getSchema().getClass(className);
foo.createProperty("prop1", OType.LONG);
foo.createProperty("prop2", OType.STRING);
foo.createIndex("V_Foo", OClass.INDEX_TYPE.UNIQUE, "prop1", "prop2");
noTx.addVertex(T.label, "Foo", "prop1", 1, "prop2", "4ab25da0-3602-4f4a-bc5e-28bfefa5ca4c");
GraphTraversal<Vertex, Vertex> traversal = noTx.traversal().V().has("Foo", "prop2", "4ab25da0-3602-4f4a-bc5e-28bfefa5ca4c");
Assert.assertEquals(0, usedIndexes(noTx, traversal));
List<Vertex> vertices = traversal.toList();
Assert.assertEquals(1, vertices.size());
} finally {
noTx.close();
}
}
@Test
public void compositeIndexSingleFirstFieldTest() {
OrientGraph noTx = factory.getNoTx();
try {
String className = noTx.createVertexClass("Foo");
OClass foo = noTx.getRawDatabase().getMetadata().getSchema().getClass(className);
foo.createProperty("prop1", OType.LONG);
foo.createProperty("prop2", OType.STRING);
foo.createIndex("V_Foo", OClass.INDEX_TYPE.UNIQUE, "prop1", "prop2");
noTx.addVertex(T.label, "Foo", "prop1", 1, "prop2", "4ab25da0-3602-4f4a-bc5e-28bfefa5ca4c");
GraphTraversal<Vertex, Vertex> traversal = noTx.traversal().V().has("Foo", "prop1", 1);
Assert.assertEquals(1, usedIndexes(noTx, traversal));
List<Vertex> vertices = traversal.toList();
Assert.assertEquals(1, vertices.size());
} finally {
noTx.close();
}
}
@Test
public void compositeIndexTest() {
OrientGraph noTx = factory.getNoTx();
try {
String className = noTx.createVertexClass("Foo");
OClass foo = noTx.getRawDatabase().getMetadata().getSchema().getClass(className);
foo.createProperty("prop1", OType.LONG);
foo.createProperty("prop2", OType.STRING);
foo.createIndex("V_Foo", OClass.INDEX_TYPE.UNIQUE, "prop1", "prop2");
noTx.addVertex(T.label, "Foo", "prop1", 1, "prop2", "4ab25da0-3602-4f4a-bc5e-28bfefa5ca4c");
GraphTraversal<Vertex, Vertex> traversal = noTx.traversal().V().hasLabel("Foo").has("prop1", 1)
.has("prop2", "4ab25da0-3602-4f4a-bc5e-28bfefa5ca4c");
Assert.assertEquals(1, usedIndexes(noTx, traversal));
List<Vertex> vertices = traversal.toList();
Assert.assertEquals(1, vertices.size());
} finally {
noTx.close();
}
}
}
| 29.093458 | 130 | 0.68487 |
010979bff4219b2ad05557cc06f178960866a6aa | 407 | package ru.heroes.modeselector.model;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
@Data
public class Game {
private String id;
private Status status = Status.ACTIVE;
private Mode mode;
private String winner;
private Map<String, Race> positions = new HashMap<>();
public Game(String id, Mode mode) {
this.id = id;
this.mode = mode;
}
}
| 19.380952 | 58 | 0.663391 |
6c36fee0864e81a1909e274a385f7280fa4b6e8e | 9,655 | package com.yash.bestcar.controller;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yash.bestcar.constants.CarConstants;
import com.yash.bestcar.exception.ResourceNotFoundException;
import com.yash.bestcar.model.Car;
import com.yash.bestcar.repository.CarRepository;
/**
* @author Yashwanth
*/
@RestController
@RequestMapping("/api")
public class CarController {
@Autowired
private CarRepository carRepository;
/**
* Get All Cars
*
* @return - All cars
*/
@GetMapping("/getAllCars")
public List<Car> getAllCars() {
return this.carRepository.findAll();
}
/**
* Get Car By Id
*
* @param carId - Car ID
* @return - Car
* @throws ResourceNotFoundException - Not Found
*/
@GetMapping("/getCarById/carId/{id}")
public ResponseEntity<Car> getCarById(@PathVariable(value = "id") final Long carId) throws ResourceNotFoundException {
Car car =
this.carRepository.findById(carId).orElseThrow(() -> new ResourceNotFoundException(CarConstants.ERROR + carId));
return ResponseEntity.ok().body(car);
}
/**
* Get Car By Type
*
* @param carType - Car Type
* @return - Car
*/
@GetMapping("/getCarByType/carType/{type}")
public List<Car> getCarByType(@PathVariable(value = "type") final String carType) {
return this.carRepository.findByCarType(carType);
}
/**
* Get Car By Name - Ignore Case
*
* @param carName - Car Name
* @return - Car
*/
@GetMapping("/getCarNameIgnoreCase/carName/{name}")
public List<Car> getCarNameIgnoreCase(@PathVariable(value = "name") final String carName) {
return this.carRepository.findByCarNameIgnoreCase(carName);
}
/**
* Get Car By Name - Starting With
*
* @param carName - Car Name
* @return - Car
*/
@GetMapping("/getCarNameStartingWith/carName/{name}")
public List<Car> getCarNameStartingWith(@PathVariable(value = "name") final String carName) {
return this.carRepository.findByCarNameStartingWith(carName);
}
/**
* Get Car By Name - Ending With
*
* @param carName - Car Name
* @return - Car
*/
@GetMapping("/getCarNameEndingWith/carName/{name}")
public List<Car> getCarNameEndingWith(@PathVariable(value = "name") final String carName) {
return this.carRepository.findByCarNameEndingWith(carName);
}
/**
* Get Car By Name - Containing (Word)
*
* @param carNameStr - Car Name Inbetween String
* @return - Car
*/
@GetMapping("/getCarNameContaining/carName/{name}")
public List<Car> getCarNameContaining(@PathVariable(value = "name") final String carNameStr) {
return this.carRepository.findByCarNameContaining(carNameStr);
}
/**
* Get All Cars Before Year
*
* @param toYear - To Year
* @return - Car
*/
@GetMapping("/getCarToYearBefore/toYear/{toyear}")
public List<Car> getCarToYearBefore(@PathVariable(value = "toyear") final int toYear) {
return this.carRepository.findByCarToYearBefore(toYear);
}
/**
* Get All Cars After Year
*
* @param fromyear - From Year
* @return - Car
*/
@GetMapping("/getCarFromYearAfter/fromYear/{fromyear}")
public List<Car> getCarFromYearAfter(@PathVariable(value = "fromyear") final int fromyear) {
return this.carRepository.findByCarFromYearAfter(fromyear);
}
/**
* Get All Cars Between Before Year and After Year
*
* @param fromYear - From Year
* @param toYear - To Year
* @return - Car
*/
@GetMapping("/getCarFromYearBetween/fromYear/{fromyear}/toYear/{toyear}")
public List<Car> getCarFromYearBetween(@PathVariable(value = "fromyear") final int fromYear,
@PathVariable(value = "toyear") final int toYear) {
return this.carRepository.findByCarFromYearBetween(fromYear, toYear);
}
/**
* Get All Cars by MPG in collection
*
* @param mpgs - Collection of Mpgs
* @return - Car
*/
@GetMapping("/findByCarMpgIn/mpgs/{mpgs}")
public List<Car> getCarMpgIn(@PathVariable(value = "mpgs") final Collection<Integer> mpgs) {
return this.carRepository.findByCarMpgIn(mpgs);
}
/**
* Get All Cars MPG Greater Than
*
* @param carMpg - Car MPG
* @return - Car
*/
@GetMapping("/getCarMpgGreaterThan/mpg/{mpg}")
public List<Car> getCarMpgGreaterThan(@PathVariable(value = "mpg") final int carMpg) {
return this.carRepository.findByCarMpgGreaterThan(carMpg);
}
/**
* Get All Cars MPG Greater Than And Equal
*
* @param carMpg - Car MPG
* @return - Car
*/
@GetMapping("/getCarMpgGreaterThanEqual/mpg/{mpg}")
public List<Car> getCarMpgGreaterThanEqual(@PathVariable(value = "mpg") final int carMpg) {
return this.carRepository.findByCarMpgGreaterThanEqual(carMpg);
}
/**
* Get All Cars Less Than
*
* @param carMpg - Car MPG
* @return - Car
*/
@GetMapping("/getCarMpgLessThan/mpg/{mpg}")
public List<Car> getCarMpgLessThan(@PathVariable(value = "mpg") final int carMpg) {
return this.carRepository.findByCarMpgLessThan(carMpg);
}
/**
* Get All Cars Less Than And Equal
*
* @param carMpg - Car MPG
* @return - Car
*/
@GetMapping("/getCarMpgLessThanEqual/mpg/{mpg}")
public List<Car> getCarMpgLessThanEqual(@PathVariable(value = "mpg") final int carMpg) {
return this.carRepository.findByCarMpgLessThanEqual(carMpg);
}
/**
* Get All Cars By Type and Color
*
* @param carType - Car Type
* @param carColor - Car Color
* @return - Car
*/
@GetMapping("/getCarTypeAndColor/carType/{type}/carColor/{color}")
public List<Car> getCarTypeAndColor(@PathVariable(value = "type") final String carType,
@PathVariable(value = "color") final String carColor) {
return this.carRepository.findByCarTypeAndCarColor(carType, carColor);
}
/**
* Get All Car by Name based on Car MPG in Ascending
*
* @param carName - Car Name
* @return - Car
*/
@GetMapping("/getCarNameOrderByCarMpgAsc/carName/{name}")
public List<Car> getCarNameOrderByCarNameAsc(@PathVariable(value = "name") final String carName) {
return this.carRepository.findByCarNameOrderByCarMpgAsc(carName);
}
/**
* Get All Car by Name based on Car MPG in Descending
*
* @param carName - Car Name
* @return - Car
*/
@GetMapping("/getCarNameOrderByCarMpgDesc/carName/{name}")
public List<Car> getCarNameOrderByCarNameDesc(@PathVariable(value = "name") final String carName) {
return this.carRepository.findByCarNameOrderByCarMpgDesc(carName);
}
/**
* Get All Top 3 Cars By Review Points
*
* @param carReviewPoints - Car Review Points
* @return - Car
*/
@GetMapping("/getTop3ByCarReviewPoints/reviewPoint/{reviewpoints}")
public List<Car> getTop3ByCarReviewPoints(@PathVariable(value = "reviewpoints") final int carReviewPoints) {
return this.carRepository.findTop3ByCarReviewPoints(carReviewPoints);
}
/**
* Create Cars
*
* @param cars - car
* @return - List of Cars
*/
@PostMapping("/createCars")
public List<Car> createCars(@RequestBody final List<Car> cars) {
return this.carRepository.saveAll(cars);
}
/**
* Create Car
*
* @param car - Car
* @return - car
*/
@PostMapping("/createCar")
public Car createCar(@Valid @RequestBody final Car car) {
return this.carRepository.save(car);
}
/**
* Update Car By Id
*
* @param carId - Car ID
* @param carDetails - Car Details
* @return - Car
* @throws ResourceNotFoundException - Exception
*/
@PutMapping("/updateCarById/carId/{id}")
public ResponseEntity<Car> updateCar(@PathVariable(value = "id") final Long carId,
@Valid @RequestBody final Car carDetails)
throws ResourceNotFoundException {
Car car =
this.carRepository.findById(carId).orElseThrow(() -> new ResourceNotFoundException(CarConstants.ERROR + carId));
car.setCarRank(carDetails.getCarRank());
car.setCarName(carDetails.getCarName());
car.setCarType(carDetails.getCarType());
car.setCarDesc(carDetails.getCarDesc());
car.setFeatures(carDetails.getFeatures());
car.setCarColor(carDetails.getCarColor());
car.setCarMpg(carDetails.getCarMpg());
car.setCarFromYear(carDetails.getCarFromYear());
car.setCarToYear(carDetails.getCarToYear());
final Car updatedCar = this.carRepository.save(car);
return ResponseEntity.ok(updatedCar);
}
/**
* Delete Car By Id
*
* @param carId - Car ID
* @return - Delete Car
* @throws ResourceNotFoundException - Exception
*/
@DeleteMapping("/deleteCarById/carId/{id}")
public Map<String, Boolean> deleteCar(@PathVariable(value = "id") final Long carId) throws ResourceNotFoundException {
Car car =
this.carRepository.findById(carId).orElseThrow(() -> new ResourceNotFoundException(CarConstants.ERROR + carId));
this.carRepository.delete(car);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
}
| 29.891641 | 120 | 0.696634 |
a34a814249b3a59950e5de1d391795bca569b9c4 | 335 | package com.youlai.mall.oms.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.youlai.mall.oms.pojo.domain.OmsOrderDelivery;
/**
* 订单物流记录表
*
* @author huawei
* @email huawei_code@163.com
* @date 2020-12-30 22:31:10
*/
public interface IOrderDeliveryService extends IService<OmsOrderDelivery> {
}
| 19.705882 | 75 | 0.764179 |
3e888ba4a127f54fec033c2f7ac552802e2f0aeb | 1,046 | package io.github.todorkrastev.pathfinder.model.entity;
import javax.persistence.*;
@Entity
@Table(name = "pictures")
public class Picture extends BaseEntity {
private String title;
private String url;
private User author;
private Route route;
public Picture() {
}
@Column(name = "title", nullable = false)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Column(name = "url", nullable = false, columnDefinition = "TEXT")
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@ManyToOne
@JoinColumn(name = "author_id")
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
@ManyToOne
@JoinColumn(name = "route_id")
public Route getRoute() {
return route;
}
public void setRoute(Route route) {
this.route = route;
}
}
| 18.678571 | 70 | 0.602294 |
88cea9983c5c30506d8042c5b5265bed65093354 | 4,009 | /*
* Copyright 2021 Huawei Technologies Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.edgegallery.developer.service.capability.impl;
import java.util.List;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.edgegallery.developer.common.ResponseConsts;
import org.edgegallery.developer.exception.DataBaseException;
import org.edgegallery.developer.mapper.capability.CapabilityGroupMapper;
import org.edgegallery.developer.model.capability.CapabilityGroup;
import org.edgegallery.developer.service.capability.CapabilityGroupService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("v2-capabilityGroupService")
public class CapabilityGroupServiceImpl implements CapabilityGroupService {
private static final Logger LOGGER = LoggerFactory.getLogger(CapabilityGroupServiceImpl.class);
@Autowired
private CapabilityGroupMapper capabilityGroupMapper;
@Override
public List<CapabilityGroup> findByNameOrNameEn(String name, String nameEn) {
return capabilityGroupMapper.selectByNameOrNameEn(name, nameEn);
}
@Override
public CapabilityGroup create(CapabilityGroup capabilityGroup) {
capabilityGroup.setId(UUID.randomUUID().toString());
if (StringUtils.isEmpty(capabilityGroup.getNameEn())) {
capabilityGroup.setName(capabilityGroup.getName());
}
if (StringUtils.isEmpty(capabilityGroup.getDescriptionEn())) {
capabilityGroup.setDescriptionEn(capabilityGroup.getDescription());
}
long currTime = System.currentTimeMillis();
capabilityGroup.setCreateTime(currTime);
capabilityGroup.setUpdateTime(currTime);
int ret = capabilityGroupMapper.insert(capabilityGroup);
if (ret <= 0) {
LOGGER.error("Create capabilityGroup {} failed!", capabilityGroup.getName());
throw new DataBaseException("Create capability group failed.", ResponseConsts.RET_CERATE_DATA_FAIL);
}
return capabilityGroup;
}
@Override
public CapabilityGroup updateById(CapabilityGroup capabilityGroup) {
int ret = capabilityGroupMapper.updateById(capabilityGroup);
if (ret <= 0) {
LOGGER.error("Update capabilityGroup {} failed!", capabilityGroup.getName());
throw new DataBaseException("Update capability group failed.", ResponseConsts.RET_UPDATE_DATA_FAIL);
}
return capabilityGroup;
}
@Override
public boolean deleteById(String groupId) {
int ret = capabilityGroupMapper.deleteById(groupId);
if (ret <= 0) {
LOGGER.error("Delete capabilityGroup {} failed!", groupId);
throw new DataBaseException("Delete capability group failed.", ResponseConsts.RET_DELETE_DATA_FAIL);
}
return true;
}
@Override
public List<CapabilityGroup> findByType(String type) {
return capabilityGroupMapper.selectByType(type);
}
@Override
public List<CapabilityGroup> findAll() {
return capabilityGroupMapper.selectAll();
}
@Override
public CapabilityGroup findById(String id) {
return capabilityGroupMapper.selectById(id);
}
@Override
public CapabilityGroup findByName(String name) {
return capabilityGroupMapper.selectByName(name);
}
}
| 37.46729 | 112 | 0.723123 |
52a3155f87a9e61f2be05b479ff9c478c3dd44b5 | 2,478 | /*
* Copyright 2005-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ws.soap.axiom;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import org.springframework.util.Assert;
import org.springframework.ws.soap.SoapBody;
import org.springframework.ws.soap.axiom.support.AxiomUtils;
import org.springframework.ws.stream.StreamingPayload;
import org.apache.axiom.om.OMDataSource;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.soap.SOAPBody;
import org.apache.axiom.soap.SOAPFactory;
/**
* Axiom-specific version of <code>org.springframework.ws.soap.Soap11Body</code>.
*
* @author Arjen Poutsma
* @since 1.0.0
*/
abstract class AxiomSoapBody extends AxiomSoapElement implements SoapBody {
private final Payload payload;
protected AxiomSoapBody(SOAPBody axiomBody, SOAPFactory axiomFactory, boolean payloadCaching) {
super(axiomBody, axiomFactory);
if (payloadCaching) {
payload = new CachingPayload(axiomBody, axiomFactory);
}
else {
payload = new NonCachingPayload(axiomBody, axiomFactory);
}
}
public Source getPayloadSource() {
return payload.getSource();
}
public Result getPayloadResult() {
return payload.getResult();
}
public boolean hasFault() {
return getAxiomBody().hasFault();
}
protected final SOAPBody getAxiomBody() {
return (SOAPBody) getAxiomElement();
}
public void setStreamingPayload(StreamingPayload payload) {
Assert.notNull(payload, "'payload' must not be null");
OMDataSource dataSource = new StreamingOMDataSource(payload);
OMElement payloadElement = getAxiomFactory().createOMElement(dataSource, payload.getName());
SOAPBody soapBody = getAxiomBody();
AxiomUtils.removeContents(soapBody);
soapBody.addChild(payloadElement);
}
}
| 31.769231 | 100 | 0.719935 |
0cd11566ee3bd4dfac9ad3a94593e4a6adb19c1f | 1,718 | package co.sns.post.service;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import co.sns.common.BoardListDTO;
import co.sns.common.ConnectionManager;
import co.sns.post.dao.TimeLineDAO;
@WebServlet("/timeline.do")
public class TimeLineServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//request객체의 parameter값 가져옴, 접속자의 id만 필요하기 때문에 나중에 세션에서 받아오기
HttpSession session = request.getSession(true);
String myId = (String) session.getAttribute("my_id");
String order = request.getParameter("order");
if(order == null) {
order = "latest"; //latest 최신순 liked 추천순
}
//Dao에서 정보를 가져옴
Connection conn = ConnectionManager.getConnnection();
ArrayList<HashMap<String, Object>> list = TimeLineDAO.getInstance().getTimeLineList(conn, myId, order);
ConnectionManager.close(conn);
//request객체에 담아 forward로 보냄
request.setAttribute("list", list);
RequestDispatcher dispatcher = request.getRequestDispatcher("/views/post/timeLine.tiles");
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| 35.061224 | 120 | 0.763679 |
0ba84371c038abce6581727eda0ecb3cd7fd6fa3 | 1,732 | package org.proteored.miapeapi.xml.gi;
import java.io.File;
import java.io.IOException;
import org.proteored.miapeapi.cv.ControlVocabularyManager;
import org.proteored.miapeapi.exceptions.MiapeDatabaseException;
import org.proteored.miapeapi.exceptions.MiapeSecurityException;
import org.proteored.miapeapi.interfaces.gi.MiapeGIDocument;
import org.proteored.miapeapi.interfaces.persistence.PersistenceManager;
import org.proteored.miapeapi.interfaces.xml.MiapeXmlFile;
import org.proteored.miapeapi.spring.SpringHandler;
public class MIAPEGIXmlFile extends MiapeXmlFile<MiapeGIDocument> {
private String userName;
private String password;
private PersistenceManager dbManager;
private ControlVocabularyManager cvUtil;
public MIAPEGIXmlFile(byte[] bytes) throws IOException {
super(bytes);
}
public MIAPEGIXmlFile(File file) {
super(file);
}
public MIAPEGIXmlFile(String fileName) {
super(fileName);
}
public void initDefault() throws MiapeDatabaseException, MiapeSecurityException {
this.userName = SpringHandler.getInstance().getUserName();
this.password = SpringHandler.getInstance().getPassword();
this.cvUtil = SpringHandler.getInstance().getCVManager();
}
public void setUser(String userName) {
this.userName = userName;
}
public void setPassword(String password) {
this.password = password;
}
public void setDbManager(PersistenceManager dbManager) {
this.dbManager = dbManager;
}
public void setCvUtil(ControlVocabularyManager cvUtil) {
this.cvUtil = cvUtil;
}
@Override
public MiapeGIDocument toDocument() throws MiapeDatabaseException, MiapeSecurityException {
return MiapeGIXmlFactory.getFactory().toDocument(this, cvUtil, dbManager, userName,
password);
}
}
| 27.935484 | 92 | 0.799654 |
af38c272a70c20b19b1e3a60dbb33ce37d8c22c2 | 18,039 | package com.music.player.bhandari.m.activity;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdView;
import com.music.player.bhandari.m.R;
import com.music.player.bhandari.m.model.Constants;
import com.music.player.bhandari.m.model.TrackItem;
import com.music.player.bhandari.m.qlyrics.LyricsAndArtistInfo.ArtistInfo.ArtistInfo;
import com.music.player.bhandari.m.qlyrics.LyricsAndArtistInfo.offlineStorage.OfflineStorageArtistBio;
import com.music.player.bhandari.m.qlyrics.LyricsAndArtistInfo.tasks.DownloadArtInfoThread;
import com.music.player.bhandari.m.interfaces.DoubleClickListener;
import com.music.player.bhandari.m.MyApp;
import com.music.player.bhandari.m.service.PlayerService;
import com.music.player.bhandari.m.utils.UtilityFun;
import com.wang.avi.AVLoadingIndicatorView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
Copyright 2017 Amit Bhandari AB
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.
*/
public class FragmentArtistInfo extends Fragment implements ArtistInfo.Callback {
private View layout;
private BroadcastReceiver mArtistUpdateReceiver;
private ArtistInfo mArtistInfo;
@BindView(R.id.text_view_art_bio_frag) TextView artBioText;
@BindView(R.id.retry_text_view) TextView retryText;
@BindView(R.id.update_track_metadata) TextView updateTagsText;
@BindView(R.id.loading_lyrics_animation) AVLoadingIndicatorView lyricLoadAnimation;
@BindView(R.id.track_artist_artsi_bio_frag) EditText artistEdit;
@BindView(R.id.button_update_metadata) Button buttonUpdateMetadata;
@BindView(R.id.ad_view_wrapper) View adViewWrapper;
@BindView(R.id.adView) AdView mAdView;
@BindView(R.id.ad_close) TextView adCloseText;
private PlayerService playerService;
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
Log.v("frag",isVisibleToUser+"");
if(isVisibleToUser && mAdView!=null){
mAdView.resume();
}else {
if(mAdView!=null){
mAdView.pause();
}
}
super.setUserVisibleHint(isVisibleToUser);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
layout = inflater.inflate(R.layout.fragment_artist_info, container, false);
ButterKnife.bind(this, layout);
playerService = MyApp.getService();
if(MyApp.getService()==null){
UtilityFun.restartApp();
return layout;
}
playerService = MyApp.getService();
buttonUpdateMetadata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TrackItem item =playerService.getCurrentTrack();
if(item==null){
return;
}
String edited_artist = artistEdit.getText().toString().trim();
if(edited_artist.isEmpty()){
Toast.makeText(getContext(),getString(R.string.te_error_empty_field), Toast.LENGTH_SHORT).show();
return;
}
if(!edited_artist.equals(item.getArtist()) ){
//changes made, save those
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
ContentValues values = new ContentValues();
values.put(MediaStore.Audio.Media.ARTIST, edited_artist);
getContext().getContentResolver()
.update(uri, values, MediaStore.Audio.Media.TITLE +"=?", new String[] {item.getTitle()});
Intent intent = new Intent(getContext(), ActivityNowPlaying.class);
intent.putExtra("refresh", true);
intent.putExtra("position",playerService.getCurrentTrackPosition());
intent.putExtra("originalTitle",item.getTitle());
intent.putExtra("title", item.getTitle());
intent.putExtra("artist", edited_artist);
intent.putExtra("album", item.getAlbum());
startActivity(intent);
artistEdit.setVisibility(View.GONE);
updateTagsText.setVisibility(View.GONE);
buttonUpdateMetadata.setVisibility(View.GONE);
buttonUpdateMetadata.setClickable(false);
if(getActivity()!=null) {
View view = getActivity().getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
}
downloadArtInfo();
}else {
Toast.makeText(getContext(),getString(R.string.change_tags_to_update),Toast.LENGTH_SHORT).show();
}
}
});
//retry click listner
layout.findViewById(R.id.ll_art_bio).setOnClickListener(new DoubleClickListener() {
@Override
public void onSingleClick(View v) {
if(retryText.getVisibility()==View.VISIBLE) {
retryText.setVisibility(View.GONE);
artBioText.setVisibility(View.VISIBLE);
artistEdit.setVisibility(View.GONE);
updateTagsText.setVisibility(View.GONE);
buttonUpdateMetadata.setVisibility(View.GONE);
buttonUpdateMetadata.setClickable(false);
lyricLoadAnimation.setVisibility(View.GONE);
downloadArtInfo();
}
}
@Override
public void onDoubleClick(View v) {
//if no connection text, do not hide artist content
if(retryText.getText().toString().equals(getString(R.string.no_connection))){
return;
}
if(artBioText.getVisibility()==View.VISIBLE){
artBioText.setVisibility(View.GONE);
}else {
artBioText.setVisibility(View.VISIBLE);
}
}
});
//downloadArtInfo();
mArtistUpdateReceiver =new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//already displayed, skip
updateArtistInfoIfNeeded();
}
};
return layout;
}
@OnClick(R.id.ad_close)
public void close_ad(){
if(mAdView!=null){
mAdView.destroy();
}
adViewWrapper.setVisibility(View.GONE);
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (mAdView != null) {
mAdView.destroy();
}
}
private void downloadArtInfo(){
TrackItem item =playerService.getCurrentTrack();
if(item==null || item.getArtist()==null){
return;
}
artBioText.setText(getString(R.string.artist_info_loading));
//set loading animation
lyricLoadAnimation.setVisibility(View.VISIBLE);
lyricLoadAnimation.show();
//see in offlinne db first
mArtistInfo = OfflineStorageArtistBio.getArtistBioFromTrackItem(item);
//second check is added to make sure internet call will happen
//when user manually changes artist tag
if(mArtistInfo!=null && item.getArtist().trim().equals(mArtistInfo.getOriginalArtist().trim())){
onArtInfoDownloaded(mArtistInfo);
return;
}
if (UtilityFun.isConnectedToInternet()) {
String artist = item.getArtist();
artist = UtilityFun.filterArtistString(artist);
new DownloadArtInfoThread(this, artist , item).start();
} else {
artBioText.setVisibility(View.GONE);
retryText.setText(getString(R.string.no_connection));
retryText.setVisibility(View.VISIBLE);
lyricLoadAnimation.hide();
lyricLoadAnimation.setVisibility(View.GONE);
}
}
@Override
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(mArtistUpdateReceiver);
}
@Override
public void onResume() {
super.onResume();
if(MyApp.getService()!=null) {
updateArtistInfoIfNeeded();
LocalBroadcastManager.getInstance(getContext()).registerReceiver(mArtistUpdateReceiver
, new IntentFilter(Constants.ACTION.UPDATE_LYRIC_AND_INFO));
}else {
UtilityFun.restartApp();
}
}
private void updateArtistInfoIfNeeded() {
TrackItem item =playerService.getCurrentTrack();
if(item==null){
artBioText.setVisibility(View.GONE);
retryText.setText(getString(R.string.no_music_found));
//retryText.setVisibility(View.GONE);
retryText.setVisibility(View.VISIBLE);
lyricLoadAnimation.hide();
return;
}
if(mArtistInfo!=null && mArtistInfo.getOriginalArtist()
.equals(item.getArtist())){
return;
}
//set loading text and animation
//set loading text and animation
downloadArtInfo();
}
@Override
public void onArtInfoDownloaded(ArtistInfo artistInfo) {
mArtistInfo = artistInfo;
if(artistInfo==null || getActivity()==null || !isAdded()){
return;
}
TrackItem item =playerService.getCurrentTrack();
//if song is already changed , return
if(item!=null && !item.getArtist().trim().equals(artistInfo.getOriginalArtist().trim())){
//artBioText.setText(getString(R.string.artist_info_loading));
return;
}
//hide loading animation
lyricLoadAnimation.hide();
lyricLoadAnimation.setVisibility(View.GONE);
if(artistInfo.getArtistContent()==null){
retryText.setText(getString(R.string.artist_info_no_result));
retryText.setVisibility(View.VISIBLE);
artBioText.setVisibility(View.GONE);
TrackItem tempItem =playerService.getCurrentTrack();
if(tempItem!=null) {
artistEdit.setVisibility(View.VISIBLE);
updateTagsText.setVisibility(View.VISIBLE);
buttonUpdateMetadata.setVisibility(View.VISIBLE);
buttonUpdateMetadata.setClickable(true);
artistEdit.setText(tempItem.getArtist());
}
return;
}
if(layout!=null && getActivity()!=null && artistInfo.getArtistContent()!=null){
Log.d("onArtInfoDownloaded", "onArtInfoDownloaded: " + artistInfo.getCorrectedArtist());
String content = artistInfo.getArtistContent();
int index = content.indexOf("Read more");
SpannableString ss = new SpannableString(content);
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(View textView) {
if(mArtistInfo.getArtistUrl()==null){
Toast.makeText(getContext(),getString(R.string.error_invalid_url),Toast.LENGTH_SHORT).show();
}else {
try {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(mArtistInfo.getArtistUrl()));
startActivity(browserIntent);
}catch (ActivityNotFoundException e){
Toast.makeText(getContext(), "No supporting application found for opening the link.", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(true);
ds.setTypeface(Typeface.create(ds.getTypeface(), Typeface.BOLD));
}
};
if(index!=-1) {
ss.setSpan(clickableSpan, index, index+9, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if(!content.equals("")) {
artBioText.setVisibility(View.VISIBLE);
retryText.setVisibility(View.GONE);
artBioText.setText(ss);
artBioText.setMovementMethod(LinkMovementMethod.getInstance());
artistEdit.setVisibility(View.GONE);
updateTagsText.setVisibility(View.GONE);
buttonUpdateMetadata.setVisibility(View.GONE);
buttonUpdateMetadata.setClickable(false);
artistEdit.setText("");
}else {
artBioText.setVisibility(View.GONE);
retryText.setText(getString(R.string.artist_info_no_result));
retryText.setVisibility(View.VISIBLE);
TrackItem tempItem =playerService.getCurrentTrack();
if(tempItem!=null) {
artistEdit.setVisibility(View.VISIBLE);
updateTagsText.setVisibility(View.VISIBLE);
buttonUpdateMetadata.setVisibility(View.VISIBLE);
buttonUpdateMetadata.setClickable(true);
artistEdit.setText(tempItem.getArtist());
}
}
//check current now playing background setting
///get current setting
// 0 - System default 1 - artist image 2 - custom
int currentNowPlayingBackPref = MyApp.getPref().getInt(getString(R.string.pref_now_playing_back),1);
if(currentNowPlayingBackPref==1) {
if (!((ActivityNowPlaying) getActivity()).isArtistLoadedInBack()) {
new SetBlurryImagetask().execute(artistInfo);
}
}
}
}
@SuppressLint("StaticFieldLeak")
private class SetBlurryImagetask extends AsyncTask<ArtistInfo, String, Bitmap>{
Bitmap b ;
@Override
protected Bitmap doInBackground(ArtistInfo... params) {
//store file in cache with artist id as name
//create folder in cache for artist images
String CACHE_ART_THUMBS = MyApp.getContext().getCacheDir()+"/art_thumbs/";
String actual_file_path = CACHE_ART_THUMBS+params[0].getOriginalArtist();
File f = new File(CACHE_ART_THUMBS);
if(!f.exists()){
f.mkdir();
}
if(!new File(actual_file_path).exists()){
//create file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(actual_file_path));
URL url = new URL(params[0].getImageUrl());
InputStream inputStream = url.openConnection().getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 )
{
fos.write(buffer, 0, bufferLength);
}
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
b= BitmapFactory.decodeFile(actual_file_path);
return b;
}
protected void onPostExecute(Bitmap b) {
//set background image
if(b!=null && getActivity()!=null) {
((ActivityNowPlaying) getActivity()).setBlurryBackground(b);
}
}
}
}
| 38.21822 | 141 | 0.605078 |
658921555fe3f0751bd1f8a0bbae928cacba0014 | 2,405 | /*-
* #%L
* Autolog AspectJ integration module
* %%
* Copyright (C) 2019 - 2020 Maxime WIEWIORA
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.github.maximevw.autolog.aspectj.configuration;
import com.github.maximevw.autolog.core.logger.LoggerManager;
import com.github.maximevw.autolog.core.logger.adapters.SystemOutAdapter;
import org.apiguardian.api.API;
/**
* This class is a singleton providing a {@link LoggerManager} instance used by AspectJ for automation of logging
* based on Autolog annotations.
*
* @see LoggerManager
*/
@API(status = API.Status.STABLE, since = "1.2.0")
public final class AspectJLoggerManager {
private LoggerManager loggerManager;
private AspectJLoggerManager() {
// Private constructor to force usage of singleton instance via the method getInstance().
// By default, at least register standard output in the default logger manager.
this.loggerManager = new LoggerManager();
this.loggerManager.register(SystemOutAdapter.getInstance());
}
/**
* Gets an instance of AspectJLoggerManager.
*
* @return A singleton instance of AspectJLoggerManager.
*/
public static AspectJLoggerManager getInstance() {
return AspectJLoggerManager.AspectJLoggerManagerInstanceHolder.INSTANCE;
}
/**
* Defines the instance of {@link LoggerManager} provided by the AspectJLoggerManager singleton.
*
* @param loggerManager The logger manager.
*/
public void init(final LoggerManager loggerManager) {
this.loggerManager = loggerManager;
}
/**
* Gets the {@link LoggerManager} instance to use for logging.
*
* @return The {@link LoggerManager} instance to use for logging.
*/
public LoggerManager getLoggerManager() {
return this.loggerManager;
}
private static class AspectJLoggerManagerInstanceHolder {
private static final AspectJLoggerManager INSTANCE = new AspectJLoggerManager();
}
}
| 31.644737 | 113 | 0.753015 |
c24a0e9a8932480ba91d719818b553e6d3fd0c7b | 7,355 | /*
* MIT License
*
* Copyright (c) 2022 Miguel Sousa
*
* 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 krazune.krps.servlet;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import krazune.krps.dao.DaoException;
import krazune.krps.dao.DaoFactory;
import krazune.krps.game.GameChoice;
import krazune.krps.game.GameOutcome;
import krazune.krps.game.dao.GameDao;
import krazune.krps.user.Authentication;
import krazune.krps.user.User;
public class StatisticsPageServlet extends HttpServlet
{
private static final String TOTAL_GAME_COUNT = "gameCount";
private static final String TOTAL_GAME_WINS = "gameWins";
private static final String TOTAL_GAME_LOSSES = "gameLosses";
private static final String TOTAL_GAME_DRAWS = "gameDraws";
private static final String TOTAL_ROCKS = "totalRocks";
private static final String TOTAL_PAPERS = "totalPapers";
private static final String TOTAL_SCISSORS = "totalScissors";
private static final String USER_GAME_COUNT = "userGameCount";
private static final String USER_GAME_WINS = "userWins";
private static final String USER_GAME_LOSSES = "userLosses";
private static final String USER_GAME_DRAWS = "userDraws";
private static final String USER_ROCKS = "userRocks";
private static final String USER_PAPERS = "userPapers";
private static final String USER_SCISSORS = "userScissors";
private static final String LAST_GAMES = "lastGames";
private static final Duration DURATION_BETWEEN_UPDATES = Duration.ofSeconds(120);
private static final int LAST_GAMES_COUNT = 10;
private Map<String, Integer> statistics;
private Instant statisticsUpdateInstant;
private DaoFactory daoFactory;
@Override
public void init() throws ServletException
{
daoFactory = (DaoFactory) getServletContext().getAttribute("mainDaoFactory");
try
{
statistics = getGlobalStatistics();
statisticsUpdateInstant = Instant.now();
}
catch (DaoException e)
{
throw new ServletException(e);
}
}
private Map<String, Integer> getGlobalStatistics() throws DaoException
{
Map<String, Integer> newStatistics = new HashMap<>();
GameDao gameDao = daoFactory.createGameDao();
newStatistics.put(TOTAL_GAME_COUNT, gameDao.getGameCount());
newStatistics.put(TOTAL_GAME_WINS, gameDao.getOutcomeCount(GameOutcome.WIN));
newStatistics.put(TOTAL_GAME_LOSSES, gameDao.getOutcomeCount(GameOutcome.LOSS));
newStatistics.put(TOTAL_GAME_DRAWS, gameDao.getOutcomeCount(GameOutcome.DRAW));
newStatistics.put(TOTAL_ROCKS, gameDao.getUserChoiceCount(GameChoice.ROCK));
newStatistics.put(TOTAL_PAPERS, gameDao.getUserChoiceCount(GameChoice.PAPER));
newStatistics.put(TOTAL_SCISSORS, gameDao.getUserChoiceCount(GameChoice.SCISSORS));
return newStatistics;
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
setupNavigationLinks(request);
if (Instant.now().isAfter(statisticsUpdateInstant.plus(DURATION_BETWEEN_UPDATES)))
{
try
{
statistics = getGlobalStatistics();
statisticsUpdateInstant = Instant.now();
}
catch (DaoException e)
{
throw new ServletException(e);
}
}
setupGlobalStatisticsAttributes(request);
User sessionUser = Authentication.getSessionUser(request.getSession(false));
if (sessionUser != null)
{
try
{
request.setAttribute("showUserStatistics", true);
setupUserStatisticsAttributes(request, sessionUser);
request.setAttribute("showLastGames", true);
setupLastGamesAttribute(request, sessionUser);
}
catch (DaoException e)
{
throw new ServletException(e);
}
}
request.getRequestDispatcher("/WEB-INF/jsp/statistics.jsp").forward(request, response);
}
private void setupLastGamesAttribute(HttpServletRequest request, User sessionUser) throws DaoException
{
GameDao gameDao = daoFactory.createGameDao();
request.setAttribute(LAST_GAMES, gameDao.getLastGames(sessionUser, LAST_GAMES_COUNT));
}
private void setupNavigationLinks(HttpServletRequest request)
{
boolean authenticated = Authentication.getSessionUser(request.getSession()) != null;
request.setAttribute("showHomeLink", true);
request.setAttribute("showLoginLink", !authenticated);
request.setAttribute("showRegistrationLink", !authenticated);
request.setAttribute("showStatisticsLink", false);
request.setAttribute("showInformationLink", true);
request.setAttribute("showSettingsLink", authenticated);
request.setAttribute("showLogoutLink", authenticated);
}
private void setupGlobalStatisticsAttributes(HttpServletRequest request)
{
request.setAttribute(TOTAL_GAME_COUNT, statistics.get(TOTAL_GAME_COUNT));
request.setAttribute(TOTAL_GAME_WINS, statistics.get(TOTAL_GAME_WINS));
request.setAttribute(TOTAL_GAME_LOSSES, statistics.get(TOTAL_GAME_LOSSES));
request.setAttribute(TOTAL_GAME_DRAWS, statistics.get(TOTAL_GAME_DRAWS));
request.setAttribute(TOTAL_ROCKS, statistics.get(TOTAL_ROCKS));
request.setAttribute(TOTAL_PAPERS, statistics.get(TOTAL_PAPERS));
request.setAttribute(TOTAL_SCISSORS, statistics.get(TOTAL_SCISSORS));
}
private void setupUserStatisticsAttributes(HttpServletRequest request, User user) throws DaoException
{
GameDao gameDao = daoFactory.createGameDao();
request.setAttribute(USER_GAME_COUNT, gameDao.getUserGameCount(user));
request.setAttribute(USER_GAME_WINS, gameDao.getOutcomeCount(GameOutcome.WIN, user));
request.setAttribute(USER_GAME_LOSSES, gameDao.getOutcomeCount(GameOutcome.LOSS, user));
request.setAttribute(USER_GAME_DRAWS, gameDao.getOutcomeCount(GameOutcome.DRAW, user));
request.setAttribute(USER_ROCKS, gameDao.getUserChoiceCount(GameChoice.ROCK, user));
request.setAttribute(USER_PAPERS, gameDao.getUserChoiceCount(GameChoice.PAPER, user));
request.setAttribute(USER_SCISSORS, gameDao.getUserChoiceCount(GameChoice.SCISSORS, user));
}
}
| 37.146465 | 117 | 0.767777 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.