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
|
---|---|---|---|---|---|
fed8e25db2f7b032827db28ef4da8196edbd51d2
| 2,006 |
package mage.cards.g;
import java.util.UUID;
import mage.abilities.Mode;
import mage.abilities.effects.common.ReturnFromGraveyardToBattlefieldTargetEffect;
import mage.abilities.effects.common.ReturnFromGraveyardToBattlefieldWithCounterTargetEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.ComparisonType;
import mage.counters.CounterType;
import mage.filter.StaticFilters;
import mage.filter.common.FilterCreatureCard;
import mage.filter.predicate.mageobject.PowerPredicate;
import mage.target.common.TargetCardInYourGraveyard;
/**
*
* @author weirddan455
*/
public final class GracefulRestoration extends CardImpl {
private static final FilterCreatureCard filter = new FilterCreatureCard("creature cards with power 2 or less from your graveyard");
static {
filter.add(new PowerPredicate(ComparisonType.FEWER_THAN, 3));
}
public GracefulRestoration(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{3}{W}{B}");
// Choose one —
// • Return target creature card from your graveyard to the battlefield with an additional +1/+1 counter on it.
this.getSpellAbility().addEffect(new ReturnFromGraveyardToBattlefieldWithCounterTargetEffect(CounterType.P1P1.createInstance(), true));
this.getSpellAbility().addTarget(new TargetCardInYourGraveyard(StaticFilters.FILTER_CARD_CREATURE_YOUR_GRAVEYARD));
// • Return up to two target creature cards with power 2 or less from your graveyard to the battlefield.
Mode mode = new Mode(new ReturnFromGraveyardToBattlefieldTargetEffect());
mode.addTarget(new TargetCardInYourGraveyard(0, 2, filter));
this.getSpellAbility().addMode(mode);
}
private GracefulRestoration(final GracefulRestoration card) {
super(card);
}
@Override
public GracefulRestoration copy() {
return new GracefulRestoration(this);
}
}
| 37.849057 | 143 | 0.76321 |
6b5c080ea850a2202ff89d1de6f3ab2f25fcb58e
| 293 |
package com.loginsignup.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.loginsignup.models.UserModel;
@Repository
public interface UserRepository extends MongoRepository<UserModel, String> {
}
| 26.636364 | 76 | 0.83959 |
9be1f40448f9ec7a7a238225c65f3602a39e7315
| 1,493 |
package org.qw3rtrun.aub.engine;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.qw3rtrun.aub.engine.vectmath.Near;
import static java.lang.Float.max;
import static java.lang.Math.abs;
public class Matchers {
public static final float EPSILON = .00001f;
@Factory
public static <T extends Near<T>> Matcher<T> nearTo(T actual, double epsilon) {
return new BaseMatcher<T>() {
@Override
public boolean matches(Object o) {
return actual.isNearTo((T) o, epsilon);
}
@Override
public void describeTo(Description description) {
description.appendValue(actual);
}
};
}
public static <T extends Near<T>> Matcher<T> nearTo(T t) {
return nearTo(t, EPSILON * max(t.bound(), EPSILON));
}
public static Matcher<Number> nearTo(Number f, double epsilon) {
return new BaseMatcher<Number>() {
@Override
public boolean matches(Object o) {
return abs(f.doubleValue() - ((Number) o).doubleValue()) < abs(epsilon);
}
@Override
public void describeTo(Description description) {
description.appendValue(f);
}
};
}
public static Matcher<Number> nearTo(Number f) {
return nearTo(f, EPSILON * max(f.floatValue(), EPSILON));
}
}
| 28.169811 | 88 | 0.600804 |
bebbb026d4a29fa6d1ea8bc9111622a9071bbcd2
| 3,744 |
import com.badlogic.gdx.graphics.Color;
class Java2 {
public static final Color CLEAR = <weak_warning descr="#00000000">new Color(0.0F, 0.0F, 0.0F, 0.0F)</weak_warning>;
public static final Color BLACK = <weak_warning descr="#000000ff">new Color(0.0F, 0.0F, 0.0F, 1.0F)</weak_warning>;
public static final Color WHITE = <weak_warning descr="#ffffffff">new Color(-1)</weak_warning>;
public static final Color LIGHT_GRAY = <weak_warning descr="#bfbfbfff">new Color(-1077952513)</weak_warning>;
public static final Color GRAY = <weak_warning descr="#7f7f7fff">new Color(2139062271)</weak_warning>;
public static final Color DARK_GRAY = <weak_warning descr="#3f3f3fff">new Color(1061109759)</weak_warning>;
public static final Color BLUE = <weak_warning descr="#0000ffff">new Color(0.0F, 0.0F, 1.0F, 1.0F)</weak_warning>;
public static final Color NAVY = <weak_warning descr="#000080ff">new Color(0.0F, 0.0F, 0.5F, 1.0F)</weak_warning>;
public static final Color ROYAL = <weak_warning descr="#4169e1ff">new Color(1097458175)</weak_warning>;
public static final Color SLATE = <weak_warning descr="#708090ff">new Color(1887473919)</weak_warning>;
public static final Color SKY = <weak_warning descr="#87ceebff">new Color(-2016482305)</weak_warning>;
public static final Color CYAN = <weak_warning descr="#00ffffff">new Color(0.0F, 1.0F, 1.0F, 1.0F)</weak_warning>;
public static final Color TEAL = <weak_warning descr="#008080ff">new Color(0.0F, 0.5F, 0.5F, 1.0F)</weak_warning>;
public static final Color GREEN = <weak_warning descr="#00ff00ff">new Color(16711935)</weak_warning>;
public static final Color CHARTREUSE = <weak_warning descr="#7fff00ff">new Color(2147418367)</weak_warning>;
public static final Color LIME = <weak_warning descr="#32cd32ff">new Color(852308735)</weak_warning>;
public static final Color FOREST = <weak_warning descr="#228b22ff">new Color(579543807)</weak_warning>;
public static final Color OLIVE = <weak_warning descr="#6b8e23ff">new Color(1804477439)</weak_warning>;
public static final Color YELLOW = <weak_warning descr="#ffff00ff">new Color(-65281)</weak_warning>;
public static final Color GOLD = <weak_warning descr="#ffd700ff">new Color(-2686721)</weak_warning>;
public static final Color GOLDENROD = <weak_warning descr="#daa520ff">new Color(-626712321)</weak_warning>;
public static final Color ORANGE = <weak_warning descr="#ffa500ff">new Color(-5963521)</weak_warning>;
public static final Color BROWN = <weak_warning descr="#8b4513ff">new Color(-1958407169)</weak_warning>;
public static final Color TAN = <weak_warning descr="#d2b48cff">new Color(-759919361)</weak_warning>;
public static final Color FIREBRICK = <weak_warning descr="#b22222ff">new Color(-1306385665)</weak_warning>;
public static final Color RED = <weak_warning descr="#ff0000ff">new Color(-16776961)</weak_warning>;
public static final Color SCARLET = <weak_warning descr="#ff341cff">new Color(-13361921)</weak_warning>;
public static final Color CORAL = <weak_warning descr="#ff7f50ff">new Color(-8433409)</weak_warning>;
public static final Color SALMON = <weak_warning descr="#fa8072ff">new Color(-92245249)</weak_warning>;
public static final Color PINK = <weak_warning descr="#ff69b4ff">new Color(-9849601)</weak_warning>;
public static final Color MAGENTA = <weak_warning descr="#ff00ffff">new Color(1.0F, 0.0F, 1.0F, 1.0F)</weak_warning>;
public static final Color PURPLE = <weak_warning descr="#a020f0ff">new Color(-1608453889)</weak_warning>;
public static final Color VIOLET = <weak_warning descr="#ee82eeff">new Color(-293409025)</weak_warning>;
public static final Color MAROON = <weak_warning descr="#b03060ff">new Color(-1339006721)</weak_warning>;
}
| 93.6 | 119 | 0.754541 |
2e96672bb08cb4bebe372d89d09c4cdf028a37b2
| 1,155 |
package eu.fbk.iv4xr.mbt.efsm;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.lang3.SerializationUtils;
import eu.fbk.iv4xr.mbt.efsm.exp.Var;
import eu.fbk.iv4xr.mbt.efsm.exp.VarSet;
public class EFSMParameter implements Cloneable, Serializable {
/**
*
*/
private static final long serialVersionUID = -6839254675772433933L;
private VarSet parameter;
public EFSMParameter(Var... vars) {
if (parameter == null) {
parameter = new VarSet();
}
for(Var v : vars ) {
parameter.put(v);
}
}
@Override
public EFSMParameter clone() {
return SerializationUtils.clone(this);
}
public VarSet getParameter() {
return this.parameter;
}
public String toDebugString() {
return this.parameter.toDebugString();
}
@Override
public String toString() {
return this.toDebugString();
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof EFSMParameter) {
EFSMParameter v = (EFSMParameter)o;
if (v.getParameter().equals(this.parameter)) {
return true;
}else {
return false;
}
}else {
return false;
}
}
}
| 18.046875 | 68 | 0.679654 |
bc33d149747d866c56b4451f09d524067f019072
| 1,860 |
package com.harpz.androidvalidator.testValidator;
import android.support.design.widget.TextInputLayout;
import android.widget.EditText;
/**
* Created by Neha Thakur on 9/4/2017.
*/
public class PasswordTest {
public boolean checkValid(final EditText ePassword, final String message, final TextInputLayout til){
if(ePassword != null) {
final String check = ePassword.getText().toString().trim();
if(til != null) {
til.setErrorEnabled(false);
if(check.isEmpty()){
til.setErrorEnabled(true);
til.setError("Please enter Password.");
}else if(!chkpwd(check)){
til.setErrorEnabled(true);
til.setError("Please enter Password minimum 8 Character");
} else {
til.setErrorEnabled(false);
til.setError(null);
}
}else {
if(check.isEmpty()) {
ePassword.setError("Please enter Password");
}else if(!chkpwd(ePassword.getText().toString())){
ePassword.setError("Please enter Password minimum 8 Character");
}else {
ePassword.setError(null);
}
}
return chkpwd(ePassword.getText().toString());
}else{
throw new NullPointerException("Validator : Field is null");
}
}
public boolean chkpwd(String sPassword) {
if(sPassword.length() > 7){
return true;
}
return false;
}
}
| 24.155844 | 105 | 0.466667 |
92103197b7552672edd7b663061fb99306002553
| 3,747 |
package com.labdogstudio.tutorial.tut3;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.labdogstudio.tutorial.BaseScreen;
import com.labdogstudio.tutorial.MenuScreen;
public class LoadSceneTest2 extends BaseScreen {
public PerspectiveCamera cam;
public CameraInputController camController;
public ModelBatch modelBatch;
public AssetManager assets;
public Array<ModelInstance> instances = new Array<ModelInstance>();
public Environment environment;
public boolean loading;
public Array<ModelInstance> blocks = new Array<ModelInstance>();
public Array<ModelInstance> invaders = new Array<ModelInstance>();
public ModelInstance ship;
public ModelInstance space;
public LoadSceneTest2(Game game) {
super(game);
}
@Override
public void show() {
super.show();
modelBatch = new ModelBatch();
environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f));
environment.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(0f, 7f, 10f);
cam.lookAt(0, 0, 0);
cam.near = 1f;
cam.far = 300f;
cam.update();
assets = new AssetManager();
assets.load("loadscene/data/all-models.g3db", Model.class);
loading = true;
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(new InputMultiplexer(camController, new InputAdapter() {
@Override
public boolean keyUp(int keycode) {
if (keycode == Keys.BACK || keycode == Keys.ESCAPE) {
game.setScreen(new MenuScreen(game));
}
return super.keyUp(keycode);
}
}));
}
private void doneLoading() {
Model model = assets.get("loadscene/data/all-models.g3db", Model.class);
ship = new ModelInstance(model, "ship");
ship.transform.setToRotation(Vector3.Y, 180).trn(0, 0, 6f);
instances.add(ship);
for (float x = -5f; x <= 5f; x += 2f) {
ModelInstance block = new ModelInstance(model, "block");
block.transform.setToTranslation(x, 0, 3f);
instances.add(block);
blocks.add(block);
}
for (float x = -5f; x <= 5f; x += 2f) {
for (float z = -8f; z <= 0f; z += 2f) {
ModelInstance invader = new ModelInstance(model, "invader");
invader.transform.setToTranslation(x, 0, z);
instances.add(invader);
invaders.add(invader);
}
}
space = new ModelInstance(model, "space");
loading = false;
}
@Override
public void render(float delta) {
super.render(delta);
if (loading && assets.update())
doneLoading();
camController.update();
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
modelBatch.begin(cam);
modelBatch.render(instances, environment);
if (space != null)
modelBatch.render(space);
modelBatch.end();
}
@Override
public void hide() {
super.hide();
modelBatch.dispose();
instances.clear();
assets.dispose();
}
}
| 29.046512 | 89 | 0.728316 |
e45d343654a8ba3ab6ed7d885dba8aa149e7e415
| 328 |
package kr.geun.o.app.bbs.repository;
import kr.geun.o.app.bbs.model.BbsCategoryEntity;
/**
* 카테고리 Repo
*
* @author akageun
*/
public interface BbsCategoryRepoDsl {
/**
* 추가
*
* @param param
*/
void add(BbsCategoryEntity param);
/**
* 수정
*
* @param param
*/
void update(BbsCategoryEntity param);
}
| 12.615385 | 49 | 0.640244 |
8f00702d76c6a933072849e0f3456133da32b224
| 586 |
package com.ervin.IO;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class OutputStreamTest {
public static void main(String[] args) throws IOException {
// 输出流文件
ByteArrayOutputStream output = new ByteArrayOutputStream();
output.write("Hello ".getBytes(StandardCharsets.UTF_8)); // 阻塞
System.out.println(output.toString("UTF-8"));
// 输出普通文件
OutputStream output2 = new FileOutputStream("out/readme.txt");
output2.write("Hello".getBytes(StandardCharsets.UTF_8)); // Hello
output2.close();
}
}
| 34.470588 | 73 | 0.674061 |
42a09ff5b5c898dfaf6ae91d30c296eeb083859e
| 12,336 |
package net.osmand.plus.osmedit;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import net.osmand.AndroidNetworkUtils;
import net.osmand.AndroidUtils;
import net.osmand.CallbackWithObject;
import net.osmand.PlatformUtil;
import net.osmand.plus.ColorUtilities;
import net.osmand.plus.OsmAndFormatter;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R;
import net.osmand.plus.UiUtilities;
import net.osmand.plus.base.BaseOsmAndFragment;
import net.osmand.plus.chooseplan.BasePurchaseDialogFragment.ButtonBackground;
import net.osmand.plus.settings.backend.OsmandSettings;
import net.osmand.util.Algorithms;
import org.apache.commons.logging.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
public class MappersFragment extends BaseOsmAndFragment {
public static final String TAG = MappersFragment.class.getSimpleName();
private static final Log log = PlatformUtil.getLog(MappersFragment.class);
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM", Locale.US);
private static final SimpleDateFormat MONTH_FORMAT = new SimpleDateFormat("MMMM", Locale.US);
private static final SimpleDateFormat CONTRIBUTION_FORMAT = new SimpleDateFormat("MMMM yyyy", Locale.US);
private static final String CONTRIBUTIONS_URL = "https://www.openstreetmap.org/user/";
private static final String USER_CHANGES_URL = "https://osmand.net/changesets/user-changes";
private static final int VISIBLE_MONTHS_COUNT = 6;
private static final int CHANGES_FOR_MAPPER_PROMO = 15;
private static final int DAYS_FOR_MAPPER_PROMO_CHECK = 60;
private OsmandApplication app;
private OsmandSettings settings;
private Map<String, Contribution> changesInfo = new LinkedHashMap<>();
private View mainView;
private boolean nightMode;
public static void showInstance(@NonNull FragmentActivity activity) {
FragmentManager fm = activity.getSupportFragmentManager();
if (!fm.isStateSaved() && fm.findFragmentByTag(TAG) == null) {
MappersFragment fragment = new MappersFragment();
fragment.setRetainInstance(true);
fm.beginTransaction()
.replace(R.id.fragmentContainer, fragment, TAG)
.addToBackStack(TAG)
.commitAllowingStateLoss();
}
}
@Override
public int getStatusBarColorId() {
return nightMode ? R.color.status_bar_color_dark : R.color.status_bar_color_light;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = requireMyApplication();
settings = app.getSettings();
nightMode = !app.getSettings().isLightContent();
requireActivity().getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
dismiss();
}
});
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
LayoutInflater themedInflater = UiUtilities.getInflater(app, nightMode);
mainView = themedInflater.inflate(R.layout.fragment_mappers_osm, container, false);
AndroidUtils.addStatusBarPadding21v(app, mainView);
setupToolbar();
setupRefreshButton();
setupContributionsBtn();
fullUpdate();
return mainView;
}
@Override
public void onResume() {
super.onResume();
if (Algorithms.isEmpty(changesInfo)) {
refreshContributions();
}
}
private void setupToolbar() {
Toolbar toolbar = mainView.findViewById(R.id.toolbar);
int iconId = AndroidUtils.getNavigationIconResId(app);
int color = ColorUtilities.getActiveButtonsAndLinksTextColor(app, nightMode);
toolbar.setNavigationIcon(getPaintedContentIcon(iconId, color));
toolbar.setNavigationContentDescription(R.string.shared_string_close);
toolbar.setNavigationOnClickListener(v -> dismiss());
}
private void setupRefreshButton() {
View button = mainView.findViewById(R.id.button_refresh);
int normal = ColorUtilities.getActiveColor(app, nightMode);
int pressed = ContextCompat.getColor(app, nightMode ? R.color.active_buttons_and_links_bg_pressed_dark : R.color.active_buttons_and_links_bg_pressed_light);
setupButtonBackground(button, normal, pressed);
button.setOnClickListener(v -> refreshContributions());
}
private void setupContributionsBtn() {
View button = mainView.findViewById(R.id.contributions_button);
button.setOnClickListener(v -> {
FragmentActivity activity = getActivity();
if (activity != null) {
String userName = settings.OSM_USER_DISPLAY_NAME.get();
String url = CONTRIBUTIONS_URL + userName + "/history";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
AndroidUtils.startActivityIfSafe(activity, intent);
}
});
}
private void fullUpdate() {
updateHeader();
updateLastInterval();
updateContributionsList();
}
private void updateHeader() {
int titleColor;
String title;
String description;
long expireTime = settings.MAPPER_LIVE_UPDATES_EXPIRE_TIME.get();
boolean isAvailable = expireTime > System.currentTimeMillis();
if (isAvailable) {
titleColor = ColorUtilities.getActiveColor(app, nightMode);
String date = OsmAndFormatter.getFormattedDate(app, expireTime);
title = getString(R.string.available_until, date);
description = getString(R.string.enough_contributions_descr);
} else {
int size = getChangesSize(changesInfo);
titleColor = ColorUtilities.getPrimaryTextColor(app, nightMode);
title = getString(R.string.map_updates_are_unavailable_yet);
description = getString(R.string.not_enough_contributions_descr,
String.valueOf(CHANGES_FOR_MAPPER_PROMO - size),
String.valueOf(DAYS_FOR_MAPPER_PROMO_CHECK));
}
TextView tvTitle = mainView.findViewById(R.id.header_title);
tvTitle.setText(title);
tvTitle.setTextColor(titleColor);
TextView tvDescr = mainView.findViewById(R.id.header_descr);
tvDescr.setText(description);
}
private void updateLastInterval() {
View container = mainView.findViewById(R.id.contributions_header);
TextView tvInterval = container.findViewById(R.id.interval);
TextView tvCount = container.findViewById(R.id.total_contributions);
Calendar calendar = Calendar.getInstance();
String currentMonth = MONTH_FORMAT.format(calendar.getTimeInMillis());
calendar.add(Calendar.MONTH, -1);
String prevMonth = MONTH_FORMAT.format(calendar.getTimeInMillis());
tvInterval.setText(getString(R.string.ltr_or_rtl_combine_via_dash, prevMonth, currentMonth));
tvCount.setText(String.valueOf(getChangesSize(changesInfo)));
}
private void updateContributionsList() {
LayoutInflater inflater = UiUtilities.getInflater(app, nightMode);
LinearLayout list = mainView.findViewById(R.id.contributions_list);
list.removeAllViews();
Calendar calendar = Calendar.getInstance();
for (int i = 0; i < VISIBLE_MONTHS_COUNT; i++) {
long time = calendar.getTimeInMillis();
calendar.add(Calendar.MONTH, -1);
Contribution contribution = changesInfo.get(DATE_FORMAT.format(time));
int changesSize = contribution != null ? contribution.count : 0;
View view = inflater.inflate(R.layout.osm_contribution_item, list, false);
TextView tvTitle = view.findViewById(R.id.title);
TextView tvCount = view.findViewById(R.id.count);
tvTitle.setText(CONTRIBUTION_FORMAT.format(time));
tvCount.setText(String.valueOf(changesSize));
list.addView(view);
}
}
protected void dismiss() {
FragmentManager manager = getFragmentManager();
if (manager != null && !manager.isStateSaved()) {
manager.popBackStack(TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
private void setupButtonBackground(@NonNull View button, @ColorInt int normalColor, @ColorInt int pressedColor) {
Drawable normal = createRoundedDrawable(normalColor, ButtonBackground.ROUNDED_SMALL);
Drawable pressed = createRoundedDrawable(pressedColor, ButtonBackground.ROUNDED_SMALL);
setupRoundedBackground(button, normal, pressed);
}
protected Drawable createRoundedDrawable(@ColorInt int color, ButtonBackground background) {
return UiUtilities.createTintedDrawable(app, background.drawableId, color);
}
protected void setupRoundedBackground(@NonNull View view, @NonNull Drawable normal, @NonNull Drawable selected) {
Drawable background;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
background = UiUtilities.getLayeredIcon(normal, getRippleDrawable());
} else {
background = AndroidUtils.createPressedStateListDrawable(normal, selected);
}
AndroidUtils.setBackground(view, background);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
protected Drawable getRippleDrawable() {
return AppCompatResources.getDrawable(app, nightMode ? R.drawable.purchase_button_ripple_dark : R.drawable.purchase_button_ripple_light);
}
public void refreshContributions() {
downloadChangesInfo(result -> {
changesInfo = result;
checkLastChanges(result);
if (isAdded()) {
fullUpdate();
}
return true;
});
}
private void checkLastChanges(@NonNull Map<String, Contribution> map) {
int size = getChangesSize(map);
if (size >= CHANGES_FOR_MAPPER_PROMO) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 16);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
settings.MAPPER_LIVE_UPDATES_EXPIRE_TIME.set(calendar.getTimeInMillis());
} else {
settings.MAPPER_LIVE_UPDATES_EXPIRE_TIME.resetToDefault();
}
}
private int getChangesSize(@NonNull Map<String, Contribution> map) {
int changesSize = 0;
Calendar calendar = Calendar.getInstance();
String date = DATE_FORMAT.format(calendar.getTimeInMillis());
Contribution contribution = map.get(date);
changesSize += contribution != null ? contribution.count : 0;
calendar.add(Calendar.MONTH, -1);
date = DATE_FORMAT.format(calendar.getTimeInMillis());
contribution = map.get(date);
changesSize += contribution != null ? contribution.count : 0;
return changesSize;
}
public void downloadChangesInfo(@NonNull CallbackWithObject<Map<String, Contribution>> callback) {
String userName = settings.OSM_USER_DISPLAY_NAME.get();
Map<String, String> params = new HashMap<>();
params.put("name", userName);
AndroidNetworkUtils.sendRequestAsync(app, USER_CHANGES_URL, params, "Download object changes list", false, false,
(resultJson, error, resultCode) -> {
Map<String, Contribution> map = new LinkedHashMap<>();
if (!Algorithms.isEmpty(error)) {
log.error(error);
app.showShortToastMessage(error);
} else if (!Algorithms.isEmpty(resultJson)) {
try {
JSONObject res = new JSONObject(resultJson);
JSONObject objectChanges = res.getJSONObject("objectChanges");
for (Iterator<String> it = objectChanges.keys(); it.hasNext(); ) {
String dateStr = it.next();
Date date = DATE_FORMAT.parse(dateStr);
int changesCount = objectChanges.optInt(dateStr);
map.put(dateStr, new Contribution(date, changesCount));
}
} catch (JSONException | ParseException e) {
log.error(e);
}
}
callback.processResult(map);
});
}
private static class Contribution {
private final Date date;
private final int count;
public Contribution(Date date, int count) {
this.date = date;
this.count = count;
}
}
}
| 35.653179 | 158 | 0.766537 |
7ff7288264becab816eb517fed60228711016324
| 1,335 |
package org.talend.components.processing.limit;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.talend.sdk.component.runtime.manager.chain.Job.components;
import javax.json.JsonBuilderFactory;
import javax.json.JsonObject;
import org.junit.jupiter.api.Test;
import org.talend.sdk.component.api.service.Service;
import org.talend.sdk.component.junit.ComponentsHandler;
import org.talend.sdk.component.junit5.Injected;
import org.talend.sdk.component.junit5.WithComponents;
@WithComponents("org.talend.components.processing")
class LimitTest {
@Injected
private ComponentsHandler handler;
@Service
private JsonBuilderFactory factory;
@Test
void limit() {
handler.setInputData(asList(factory.createObjectBuilder().add("index", 1).build(),
factory.createObjectBuilder().add("index", 2).build(), factory.createObjectBuilder().add("index", 3).build()));
components().component("input", "test://emitter").component("limit", "Processing://Limit?configuration.limit=2")
.component("output", "test://collector").connections().from("input").to("limit").from("limit").to("output")
.build().run();
assertEquals(2, handler.getCollectedData(JsonObject.class).size());
}
}
| 37.083333 | 127 | 0.725094 |
5adc0130a025b157af8fd7bdbf61ca80a3bc4517
| 1,388 |
/*
* Copyright 2003-2013 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 jetbrains.mps.idea.java.index;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.indexing.FileBasedIndex.InputFilter;
import jetbrains.mps.fileTypes.MPSFileTypeFactory;
/**
* User: fyodor
* Date: 3/28/13
*/
/*package*/ class MPSFilesInputFilter implements InputFilter {
static MPSFilesInputFilter INSTANCE = new MPSFilesInputFilter();
@Override
public boolean acceptInput(VirtualFile file) {
FileType fileType = file.getFileType();
return MPSFileTypeFactory.MPS_FILE_TYPE.equals(fileType)
|| MPSFileTypeFactory.MPS_BINARY_FILE_TYPE.equals(fileType)
|| MPSFileTypeFactory.MPS_HEADER_FILE_TYPE.equals(fileType)
|| MPSFileTypeFactory.MPS_ROOT_FILE_TYPE.equals(fileType);
}
}
| 33.853659 | 75 | 0.766571 |
84dc7b5c2d01b8b5d7e30325cbb298a4708394f9
| 2,990 |
/**
*
* Copyright 2020 paolo mococci
*
* 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 following 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 local.example.data.reactive.rest.controller;
import java.net.URISyntaxException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.rest.webmvc.RepositoryRestController;
import org.springframework.hateoas.CollectionModel;
import org.springframework.hateoas.EntityModel;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import local.example.data.assembler.EmployeeRepresentationModelAssembler;
import local.example.data.entity.Employee;
import local.example.data.exception.EmployeeNotFoundException;
import local.example.data.repository.EmployeeRestRepository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RepositoryRestController
@RequestMapping(path = "/api/reactive/employees")
public class EmployeeReactiveRestController {
@Autowired
EmployeeRestRepository employeeRestRepository;
@Autowired
EmployeeRepresentationModelAssembler employeeRepresentationModelAssembler;
@GetMapping(path = "/{id}")
public ResponseEntity<Mono<EntityModel<Employee>>> read(@PathVariable Long id)
throws URISyntaxException {
Employee employee = employeeRestRepository.findById(id)
.orElseThrow(() -> new EmployeeNotFoundException(id));
Mono<EntityModel<Employee>> monoOfEmployee;
monoOfEmployee = employeeRepresentationModelAssembler.toMono(employee);
return new ResponseEntity<Mono<EntityModel<Employee>>>(monoOfEmployee, HttpStatus.OK);
}
@GetMapping(path = "/nicknames/{nickname}")
public ResponseEntity<?> readByNickname(@PathVariable String nickname)
throws URISyntaxException {
var employees = employeeRestRepository.findByNickname(nickname);
var fluxOfEmployees = employeeRepresentationModelAssembler.toFlux(employees);
return new ResponseEntity<>(fluxOfEmployees, HttpStatus.OK);
}
@GetMapping
public ResponseEntity<?> readAll()
throws URISyntaxException {
Iterable<Employee> employees = employeeRestRepository.findAll();
Flux<CollectionModel<EntityModel<Employee>>> fluxOfEmployees;
fluxOfEmployees = employeeRepresentationModelAssembler.toFlux(employees);
return new ResponseEntity<>(fluxOfEmployees, HttpStatus.OK);
}
}
| 38.831169 | 88 | 0.80903 |
d020b6e92242082dd573ff733a95ee98fc440896
| 639 |
package edu.howest.breakout.client.render;
import edu.howest.breakout.game.entity.Entity;
import java.awt.*;
import java.awt.geom.Rectangle2D;
/**
* Created by thomas on 05/11/2014.
*/
public class RenderBlock implements Render {
private Rectangle2D block;
public RenderBlock() {
this.block = new Rectangle2D.Double();
}
@Override
public void render(Graphics2D g, Entity entity) {
block.setFrame(entity.getX(), entity.getY(), entity.getWidth(), entity.getHeight());
g.setColor(entity.getColor());
g.fill(block);
g.setColor(Color.black);
g.draw(block);
}
}
| 20.612903 | 92 | 0.655712 |
041c3fa1faf268176ba3022ad4abe2e9c042461f
| 1,978 |
package hope;
import java.util.ArrayList;
final class ActorCollector {
private ArrayList<String> actorLevels = new ArrayList<String>();
private ArrayList<ArrayList<Actor>> actorLists = new ArrayList<ArrayList<Actor>>();
private boolean isFrozen = false;
void freeze() {
isFrozen = true;
}
ActorCollector() {
}
void registerActorLevel(String actorLevel) {
assert !isFrozen;
assert !isActorLevelRegistered(actorLevel);
// Register.
this.actorLevels.add(actorLevel);
this.actorLists.add(new ArrayList<Actor>());
assert this.actorLevels.size() == this.actorLists.size();
}
private boolean isActorLevelRegistered(String actorLevel) {
for (String al : actorLevels) {
if (al.equals(actorLevel)) {
return true;
}
}
return false;
}
private int getActorLevelIndex(String actorLevel) {
return actorLevels.indexOf(actorLevel);
}
void registerActor(Actor actor) {
assert isFrozen;
String actorLevel = actor.getActorLevel();
assert isActorLevelRegistered(actorLevel);
// Get existing list.
int actorLevelIndex = getActorLevelIndex(actorLevel);
ArrayList<Actor> actors = actorLists.get(actorLevelIndex);
assert actors != null;
// Register.
actors.add(actor);
}
void unregisterActor(Actor actor) {
assert isFrozen;
String actorLevel = actor.getActorLevel();
assert isActorLevelRegistered(actorLevel);
// Get existing list.
int actorLevelIndex = getActorLevelIndex(actorLevel);
ArrayList<Actor> actors = actorLists.get(actorLevelIndex);
assert actors != null;
// Unregister.
actors.remove(actor);
}
void update(float timeStep) {
assert isFrozen;
// Actor update.
for (ArrayList<Actor> actorList : this.actorLists) {
for (int i = 0; i < actorList.size(); /*i++*/) {
Actor actor = actorList.get(i);
// Cleanup.
if (actor.IsKilled()) {
actorList.remove(i);
continue;
}
actor.update(timeStep);
i++;
}
}
}
}
| 21.268817 | 84 | 0.688069 |
acc110ac201d2567b43b1b0bda974f9ecef14835
| 150 |
package me.bc56.tuna.events;
import me.bc56.tuna.events.type.Event;
public interface EventReceiver {
<E extends Event> void enqueue(E event);
}
| 18.75 | 44 | 0.746667 |
00a6ef812ec1d081dbc11a28673b26f96fa46203
| 368 |
package com.psygate.minecraft.spigot.gauntlet.connection.packets.wrappers.v1_8_R3;
//Gauntlet generated interface class.
public interface IPacketPlayOutTransactionWrapper extends com.psygate.minecraft.spigot.gauntlet.connection.packets.IPacketWrapper {
int getA();
void setA(int param);
short getB();
void setB(short param);
boolean getC();
void setC(boolean param);
}
| 36.8 | 131 | 0.820652 |
fda3a325d32c1676d0c94a8172d0c020db075b6e
| 172 |
package com.growingwiththeweb.sorting;
public class QuicksortTest extends BaseSortTest {
protected void sort(Integer[] array) {
Quicksort.sort(array);
}
}
| 21.5 | 49 | 0.72093 |
306b35e2b41168ea99379207682c173a3b962f12
| 536 |
package cz.cvut.fel.ida.logic.constructs.template.transforming;
import cz.cvut.fel.ida.logic.constructs.example.QueryAtom;
import cz.cvut.fel.ida.logic.constructs.template.Template;
import cz.cvut.fel.ida.setup.Settings;
/**
* Created by gusta on 14.3.17.
*/
public interface TemplateReducing {
<T extends Template> T reduce(T itemplate);
<T extends Template> T reduce(T itemplate, QueryAtom queryAtom);
static TemplateReducing getReducer(Settings settings) {
return new TemplateChainReducer(settings);
}
}
| 29.777778 | 68 | 0.753731 |
43bea848bf36fa7fd823158cd2d6f3e30f745bb0
| 6,249 |
package ru.shutoff.cgstarter;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import java.util.Date;
public class GpsActivity extends ActionBarActivity {
private LocationManager locationManager;
private LocationListener netListener;
private LocationListener gpsListener;
Location currentBestLocation;
boolean need_fine;
void locationChanged() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
@Override
protected void onResume() {
super.onResume();
netListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
locationChanged(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
try {
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 10, netListener);
} else {
netListener = null;
}
} catch (Exception ex) {
netListener = null;
}
if ((netListener == null) || need_fine) {
gpsListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
locationChanged(location);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, gpsListener);
} catch (Exception ex) {
gpsListener = null;
}
}
locationChanged(getLastBestLocation());
}
@Override
protected void onPause() {
super.onPause();
if (netListener != null)
locationManager.removeUpdates(netListener);
if (gpsListener != null)
locationManager.removeUpdates(gpsListener);
}
static final int TWO_MINUTES = 1000 * 60 * 2;
Location getLastBestLocation() {
Location locationGPS = null;
try {
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
locationGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
// ignore
}
Location locationNet = null;
try {
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
locationNet = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
// ignore
}
long GPSLocationTime = 0;
if (locationGPS != null)
GPSLocationTime = locationGPS.getTime();
long NetLocationTime = 0;
if (locationNet != null)
NetLocationTime = locationNet.getTime();
if (GPSLocationTime > NetLocationTime)
return locationGPS;
return locationNet;
}
public void locationChanged(Location location) {
if ((location != null) && isBetterLocation(location, currentBestLocation))
currentBestLocation = location;
if (currentBestLocation != null) {
long t1 = currentBestLocation.getTime() + TWO_MINUTES;
long t2 = new Date().getTime();
if (t1 < t2)
currentBestLocation = null;
}
locationChanged();
}
protected boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null)
return true;
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true;
// If the new location is more than two minutes older, it must be worse
} else if (isSignificantlyOlder) {
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true;
}
return false;
}
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null)
return provider2 == null;
return provider1.equals(provider2);
}
}
| 32.21134 | 112 | 0.609858 |
05c7bf2ef9cedbc4856eb4559decd7fb44cf15eb
| 7,052 |
/* Copyright © 2015 Matthew Champion
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of mattunderscore.com nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL MATTHEW CHAMPION BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
package com.mattunderscore.trees.walkers;
import static com.mattunderscore.trees.walkers.MatcherUtilities.linkedTreeElementMatcher;
import static com.mattunderscore.trees.walkers.MatcherUtilities.linkedTreeTypeMatcher;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import com.mattunderscore.trees.linked.tree.Constructor;
import com.mattunderscore.trees.linked.tree.EmptyConstructor;
import com.mattunderscore.trees.linked.tree.LinkedTree;
import com.mattunderscore.trees.mutable.MutableSettableStructuredNode;
import com.mattunderscore.trees.traversal.Walker;
/**
* Unit tests for {@link BreadthFirstTraversalDriver}.
*/
public final class BreadthFirstTraversalDriverTest {
private static TraversalDriver walker;
private static LinkedTree<String> tree;
private static LinkedTree<String> emptyTree;
@Mock
private Walker<MutableSettableStructuredNode<String>> nodeWalker;
@Mock
private Walker<String> elementWalker;
private InOrder elementOrder;
private InOrder nodeOrder;
@BeforeClass
public static void setUpClass() {
final Constructor<String> constructor = new Constructor<>();
tree = constructor.build(
"f",
constructor.build(
"b",
constructor.build(
"a"),
constructor.build(
"d",
constructor.build(
"c"),
constructor.build(
"e")
)
),
constructor.build(
"i",
constructor.build(
"h",
constructor.build(
"g"))));
emptyTree = new EmptyConstructor<String>().build();
walker = new BreadthFirstTraversalDriver();
}
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
nodeOrder = inOrder(nodeWalker);
elementOrder = inOrder(elementWalker);
}
@Test
public void empty() {
walker.traverseTree(emptyTree, nodeWalker);
nodeOrder.verify(nodeWalker).onEmpty();
nodeOrder.verify(nodeWalker).onCompleted();
nodeOrder.verifyNoMoreInteractions();
verifyNoMoreInteractions(nodeWalker);
}
@Test
public void emptyElements() {
walker.traverseTree(emptyTree, new NodeToElementWalker<>(elementWalker));
elementOrder.verify(elementWalker).onEmpty();
elementOrder.verify(elementWalker).onCompleted();
elementOrder.verifyNoMoreInteractions();
verifyNoMoreInteractions(elementWalker);
}
@Test
public void elements() {
when(elementWalker.onNext(isA(String.class))).thenReturn(true);
walker.traverseTree(tree, new NodeToElementWalker<>(elementWalker));
elementOrder.verify(elementWalker).onNext("f");
elementOrder.verify(elementWalker).onNext("b");
elementOrder.verify(elementWalker).onNext("i");
elementOrder.verify(elementWalker).onNext("a");
elementOrder.verify(elementWalker).onNext("d");
elementOrder.verify(elementWalker).onNext("h");
elementOrder.verify(elementWalker).onNext("c");
elementOrder.verify(elementWalker).onNext("e");
elementOrder.verify(elementWalker).onNext("g");
elementOrder.verify(elementWalker).onCompleted();
elementOrder.verifyNoMoreInteractions();
verifyNoMoreInteractions(elementWalker);
}
@Test
public void firstElement() {
when(elementWalker.onNext(isA(String.class))).thenReturn(false);
walker.traverseTree(tree, new NodeToElementWalker<>(elementWalker));
verify(elementWalker).onNext("f");
verifyNoMoreInteractions(elementWalker);
}
@Test
public void firstTwoElements() {
when(elementWalker.onNext(isA(String.class))).thenReturn(true, false);
walker.traverseTree(tree, new NodeToElementWalker<>(elementWalker));
elementOrder.verify(elementWalker).onNext("f");
elementOrder.verify(elementWalker).onNext("b");
elementOrder.verifyNoMoreInteractions();
verifyNoMoreInteractions(elementWalker);
}
@Test
public void nodes() {
when(nodeWalker.onNext(linkedTreeTypeMatcher())).thenReturn(true);
walker.traverseTree(tree, nodeWalker);
nodeOrder.verify(nodeWalker).onNext(linkedTreeElementMatcher("f"));
nodeOrder.verify(nodeWalker).onNext(linkedTreeElementMatcher("b"));
nodeOrder.verify(nodeWalker).onNext(linkedTreeElementMatcher("i"));
nodeOrder.verify(nodeWalker).onNext(linkedTreeElementMatcher("a"));
nodeOrder.verify(nodeWalker).onNext(linkedTreeElementMatcher("d"));
nodeOrder.verify(nodeWalker).onNext(linkedTreeElementMatcher("h"));
nodeOrder.verify(nodeWalker).onNext(linkedTreeElementMatcher("c"));
nodeOrder.verify(nodeWalker).onNext(linkedTreeElementMatcher("e"));
nodeOrder.verify(nodeWalker).onNext(linkedTreeElementMatcher("g"));
nodeOrder.verify(nodeWalker).onCompleted();
nodeOrder.verifyNoMoreInteractions();
verifyNoMoreInteractions(nodeWalker);
}
}
| 41 | 89 | 0.704481 |
72afbd00300feb05aac47f82887992893976c10e
| 1,251 |
package com.huuu.web.system.response;
import com.huuu.base.response.BaseResponse;
import com.huuu.system.enums.UserState;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* @author chenzhenhu
*/
@Getter
@Setter
public class UserListResponse extends BaseResponse {
private static final long serialVersionUID = 2660004492439639073L;
/** 用户ID*/
private Long id;
/** 创建时间*/
private LocalDateTime createTime;
/** 姓名*/
private String name;
/** 员工编号*/
private String code;
/** 头像*/
private String avatar;
/** 性别:0-未知 1-男 2-女*/
private Integer gender;
/** 手机号*/
private String mobile;
/** 邮箱*/
private String email;
/** 生日*/
private LocalDate birthday;
/** 人事状态*/
private Integer state;
/** 合同到期*/
private LocalDate contractExpireDate;
private String stateFormat;
public String getMobile() {
if (StringUtils.isNotBlank(mobile)) {
mobile = mobile.replaceAll("(\\w{3})\\w*(\\w{4})", "$1****$2");
}
return mobile;
}
public String getStateFormat() {
return UserState.find(state).getDesc();
}
}
| 22.339286 | 75 | 0.638689 |
d28d88230b0d5549cacd1f6459be911138a839de
| 1,458 |
package com.google.smartmessage.bean;
import android.database.Cursor;
/**
* ============================================================
* Copyright:Google有限公司版权所有 (c) 2017
* Author: 陈冠杰
* Email: 815712739@qq.com
* GitHub: https://github.com/JackChen1999
* 博客: http://blog.csdn.net/axi295309066
* 微博: AndroidDeveloper
* <p>
* Project_Name:SmartMessage
* Package_Name:PACKAGE_NAME
* Version:1.0
* time:2016/2/16 12:35
* des :${TODO}
* gitVersion:$Rev$
* updateAuthor:$Author$
* updateDate:$Date$
* updateDes:${TODO}
* ============================================================
**/
public class Sms {
private String body;
private long date;
private int type;
private int _id;
public static Sms createFromCursor(Cursor cursor){
Sms sms = new Sms();
sms.setBody(cursor.getString(cursor.getColumnIndex("body")));
sms.setDate(cursor.getLong(cursor.getColumnIndex("date")));
sms.setType(cursor.getInt(cursor.getColumnIndex("type")));
sms.set_id(cursor.getInt(cursor.getColumnIndex("_id")));
return sms;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
}
| 22.090909 | 63 | 0.620713 |
735cc8f74874e2039194e385ae13062bb35bbdfa
| 553 |
package com.ezlinker.app.common.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* ezlinker
*
* @author wangwenhai
* @description Token引起的异常
* @create 2019-11-20 22:46
**/
@ResponseStatus(value = HttpStatus.UNAUTHORIZED, reason = "Token异常,禁止访问")
public class TokenException extends XException {
public TokenException(String message, String i18nMessage) {
this.setCode(401);
this.setMessage(message);
this.setI18nMessage(i18nMessage);
}
}
| 24.043478 | 73 | 0.734177 |
92facb4c9fa27ef11aa538ce483091c1abf75294
| 676 |
package edu.usc.ict.nl.nlu.nlp4j.parserservice;
import javax.ws.rs.client.ClientBuilder;
import org.json.JSONException;
import org.json.JSONObject;
public class Client {
public static JSONObject parse(String target,String sentence) throws JSONException {
String responseEntity = ClientBuilder.newClient()
.target(target).path("clearnlp/parse").queryParam("sentence", sentence).queryParam("timeout", "20")
.request().get(String.class);
return new JSONObject(responseEntity);
}
public static void main(String[] args) throws JSONException {
System.out.println(parse("http://localhost:8080","i eat an apple because i am angry."));
}
}
| 32.190476 | 104 | 0.730769 |
1bba5bca25a190b3e67a88ed967974899c982f9e
| 95 |
package pojogen;
public class MainClass {
public static void main(String[] argv) {
}
}
| 10.555556 | 41 | 0.673684 |
2b56cca578143ec706c260d6d2939a5864163447
| 729 |
package jopenvr;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import java.util.Arrays;
import java.util.List;
public class VREvent_Ipd_t extends Structure
{
public float ipdMeters;
public VREvent_Ipd_t()
{
}
protected List<String> getFieldOrder()
{
return Arrays.asList("ipdMeters");
}
public VREvent_Ipd_t(float ipdMeters)
{
this.ipdMeters = ipdMeters;
}
public VREvent_Ipd_t(Pointer peer)
{
super(peer);
}
public static class ByReference extends VREvent_Ipd_t implements com.sun.jna.Structure.ByReference
{
}
public static class ByValue extends VREvent_Ipd_t implements com.sun.jna.Structure.ByValue
{
}
}
| 18.692308 | 102 | 0.680384 |
3fb0b84449ce43de620b54e28dece99bcd21bf36
| 3,958 |
/*
* This file is part of Flicklib.
*
* Copyright (C) Zsombor Gegesy
*
* 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.flicklib.service.movie.xpress;
import java.io.IOException;
import java.util.List;
import junit.framework.Assert;
import org.junit.Test;
import com.flicklib.api.AbstractMovieInfoFetcher;
import com.flicklib.domain.MoviePage;
import com.flicklib.domain.MovieSearchResult;
import com.flicklib.service.movie.AlternateLiveTester;
public class XpressHuLiveFetcherTest extends AlternateLiveTester {
private final AbstractMovieInfoFetcher fetcher;
public XpressHuLiveFetcherTest (boolean internalHttpClient, boolean internalRedirects) {
super(internalHttpClient, internalRedirects);
fetcher = new XpressHuFetcher(loader);
}
@Test
public void testBreakfastSearch() throws IOException {
List<? extends MovieSearchResult> searchResult = fetcher.search("Breakfast");
Assert.assertNotNull("search result", searchResult);
Assert.assertEquals("5 result", 5, searchResult.size());
Assert.assertEquals("title 1", "Álom luxuskivitelben", searchResult.get(0).getTitle());
Assert.assertEquals("title 2", "Nulladik óra", searchResult.get(1).getTitle());
Assert.assertEquals("orig title 2", "The Breakfast Club", searchResult.get(1).getOriginalTitle());
Assert.assertEquals("orig year 2", Integer.valueOf(1985), searchResult.get(1).getYear());
Assert.assertEquals("title 3", "Bajnokok reggelije", searchResult.get(2).getTitle());
Assert.assertEquals("orig title 3", "Breakfast of Champions", searchResult.get(2).getOriginalTitle());
Assert.assertEquals("orig year 3", Integer.valueOf(1999), searchResult.get(2).getYear());
Assert.assertEquals("title 4", "Reggeli a Plútón", searchResult.get(3).getTitle());
Assert.assertEquals("orig title 4", "Breakfast on Pluto", searchResult.get(3).getOriginalTitle());
Assert.assertEquals("orig year 4", Integer.valueOf(2005), searchResult.get(3).getYear());
Assert.assertEquals("title 5", "Álom luxuskivitelben (!!! CSAK ANGOLUL !!!)", searchResult.get(4).getTitle());
Assert.assertEquals("orig title 5", "Breakfast at Tiffany's", searchResult.get(4).getOriginalTitle());
Assert.assertEquals("orig year 5", Integer.valueOf(1961), searchResult.get(4).getYear());
}
@Test
public void testMovieInfoFetching() throws IOException {
MoviePage movieInfo = fetcher.getMovieInfo("7467");
Assert.assertNotNull("movie info", movieInfo);
Assert.assertEquals("id", "7467", movieInfo.getIdForSite());
Assert.assertEquals("url", "http://www.xpress.hu/dvd/film.asp?FILMAZ=7467", movieInfo.getUrl());
Assert.assertEquals("image url", "http://www.xpress.hu/dvd/cover/kicsi/7467.jpg", movieInfo.getImgUrl());
Assert.assertEquals("title", "Bajnokok reggelije", movieInfo.getTitle());
Assert.assertEquals("genre", "[vígjáték]", movieInfo.getGenres().toString());
Assert.assertTrue("director", movieInfo.getDirectors().contains("Alan Rudolph"));
Assert.assertEquals("orig title", "Breakfast of Champions", movieInfo.getOriginalTitle());
Assert.assertEquals("orig year", Integer.valueOf(1999), movieInfo.getYear());
Assert.assertEquals("score", Integer.valueOf(70), movieInfo.getScore());
}
}
| 45.494253 | 118 | 0.707933 |
3c58edf82372f8e8ce27c6f52b7d1e022f3b52e1
| 27,774 |
/*
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
*
* 1. Definitions.
*
* "License" shall mean the terms and conditions for use, reproduction,
* and distribution as defined by Sections 1 through 9 of this document.
*
* "Licensor" shall mean the copyright owner or entity authorized by
* the copyright owner that is granting the License.
*
* "Legal Entity" shall mean the union of the acting entity and all
* other entities that control, are controlled by, or are under common
* control with that entity. For the purposes of this definition,
* "control" means (i) the power, direct or indirect, to cause the
* direction or management of such entity, whether by contract or
* otherwise, or (ii) ownership of fifty percent (50%) or more of the
* outstanding shares, or (iii) beneficial ownership of such entity.
*
* "You" (or "Your") shall mean an individual or Legal Entity
* exercising permissions granted by this License.
*
* "Source" form shall mean the preferred form for making modifications,
* including but not limited to software source code, documentation
* source, and configuration files.
*
* "Object" form shall mean any form resulting from mechanical
* transformation or translation of a Source form, including but
* not limited to compiled object code, generated documentation,
* and conversions to other media types.
*
* "Work" shall mean the work of authorship, whether in Source or
* Object form, made available under the License, as indicated by a
* copyright notice that is included in or attached to the work
* (an example is provided in the Appendix below).
*
* "Derivative Works" shall mean any work, whether in Source or Object
* form, that is based on (or derived from) the Work and for which the
* editorial revisions, annotations, elaborations, or other modifications
* represent, as a whole, an original work of authorship. For the purposes
* of this License, Derivative Works shall not include works that remain
* separable from, or merely link (or bind by name) to the interfaces of,
* the Work and Derivative Works thereof.
*
* "Contribution" shall mean any work of authorship, including
* the original version of the Work and any modifications or additions
* to that Work or Derivative Works thereof, that is intentionally
* submitted to Licensor for inclusion in the Work by the copyright owner
* or by an individual or Legal Entity authorized to submit on behalf of
* the copyright owner. For the purposes of this definition, "submitted"
* means any form of electronic, verbal, or written communication sent
* to the Licensor or its representatives, including but not limited to
* communication on electronic mailing lists, source code control systems,
* and issue tracking systems that are managed by, or on behalf of, the
* Licensor for the purpose of discussing and improving the Work, but
* excluding communication that is conspicuously marked or otherwise
* designated in writing by the copyright owner as "Not a Contribution."
*
* "Contributor" shall mean Licensor and any individual or Legal Entity
* on behalf of whom a Contribution has been received by Licensor and
* subsequently incorporated within the Work.
*
* 2. Grant of Copyright License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* copyright license to reproduce, prepare Derivative Works of,
* publicly display, publicly perform, sublicense, and distribute the
* Work and such Derivative Works in Source or Object form.
*
* 3. Grant of Patent License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* (except as stated in this section) patent license to make, have made,
* use, offer to sell, sell, import, and otherwise transfer the Work,
* where such license applies only to those patent claims licensable
* by such Contributor that are necessarily infringed by their
* Contribution(s) alone or by combination of their Contribution(s)
* with the Work to which such Contribution(s) was submitted. If You
* institute patent litigation against any entity (including a
* cross-claim or counterclaim in a lawsuit) alleging that the Work
* or a Contribution incorporated within the Work constitutes direct
* or contributory patent infringement, then any patent licenses
* granted to You under this License for that Work shall terminate
* as of the date such litigation is filed.
*
* 4. Redistribution. You may reproduce and distribute copies of the
* Work or Derivative Works thereof in any medium, with or without
* modifications, and in Source or Object form, provided that You
* meet the following conditions:
*
* (a) You must give any other recipients of the Work or
* Derivative Works a copy of this License; and
*
* (b) You must cause any modified files to carry prominent notices
* stating that You changed the files; and
*
* (c) You must retain, in the Source form of any Derivative Works
* that You distribute, all copyright, patent, trademark, and
* attribution notices from the Source form of the Work,
* excluding those notices that do not pertain to any part of
* the Derivative Works; and
*
* (d) If the Work includes a "NOTICE" text file as part of its
* distribution, then any Derivative Works that You distribute must
* include a readable copy of the attribution notices contained
* within such NOTICE file, excluding those notices that do not
* pertain to any part of the Derivative Works, in at least one
* of the following places: within a NOTICE text file distributed
* as part of the Derivative Works; within the Source form or
* documentation, if provided along with the Derivative Works; or,
* within a display generated by the Derivative Works, if and
* wherever such third-party notices normally appear. The contents
* of the NOTICE file are for informational purposes only and
* do not modify the License. You may add Your own attribution
* notices within Derivative Works that You distribute, alongside
* or as an addendum to the NOTICE text from the Work, provided
* that such additional attribution notices cannot be construed
* as modifying the License.
*
* You may add Your own copyright statement to Your modifications and
* may provide additional or different license terms and conditions
* for use, reproduction, or distribution of Your modifications, or
* for any such Derivative Works as a whole, provided Your use,
* reproduction, and distribution of the Work otherwise complies with
* the conditions stated in this License.
*
* 5. Submission of Contributions. Unless You explicitly state otherwise,
* any Contribution intentionally submitted for inclusion in the Work
* by You to the Licensor shall be under the terms and conditions of
* this License, without any additional terms or conditions.
* Notwithstanding the above, nothing herein shall supersede or modify
* the terms of any separate license agreement you may have executed
* with Licensor regarding such Contributions.
*
* 6. Trademarks. This License does not grant permission to use the trade
* names, trademarks, service marks, or product names of the Licensor,
* except as required for reasonable and customary use in describing the
* origin of the Work and reproducing the content of the NOTICE file.
*
* 7. Disclaimer of Warranty. Unless required by applicable law or
* agreed to in writing, Licensor provides the Work (and each
* Contributor provides its Contributions) on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied, including, without limitation, any warranties or conditions
* of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
* PARTICULAR PURPOSE. You are solely responsible for determining the
* appropriateness of using or redistributing the Work and assume any
* risks associated with Your exercise of permissions under this License.
*
* 8. Limitation of Liability. In no event and under no legal theory,
* whether in tort (including negligence), contract, or otherwise,
* unless required by applicable law (such as deliberate and grossly
* negligent acts) or agreed to in writing, shall any Contributor be
* liable to You for damages, including any direct, indirect, special,
* incidental, or consequential damages of any character arising as a
* result of this License or out of the use or inability to use the
* Work (including but not limited to damages for loss of goodwill,
* work stoppage, computer failure or malfunction, or any and all
* other commercial damages or losses), even if such Contributor
* has been advised of the possibility of such damages.
*
* 9. Accepting Warranty or Additional Liability. While redistributing
* the Work or Derivative Works thereof, You may choose to offer,
* and charge a fee for, acceptance of support, warranty, indemnity,
* or other liability obligations and/or rights consistent with this
* License. However, in accepting such obligations, You may act only
* on Your own behalf and on Your sole responsibility, not on behalf
* of any other Contributor, and only if You agree to indemnify,
* defend, and hold each Contributor harmless for any liability
* incurred by, or claims asserted against, such Contributor by reason
* of your accepting any such warranty or additional liability.
*
* END OF TERMS AND CONDITIONS
*
* APPENDIX: How to apply the Apache License to your work.
*
* To apply the Apache License to your work, attach the following
* boilerplate notice, with the fields enclosed by brackets "[]"
* replaced with your own identifying information. (Don't include
* the brackets!) The text should be enclosed in the appropriate
* comment syntax for the file format. We also recommend that a
* file or class name and description of purpose be included on the
* same "printed page" as the copyright notice for easier
* identification within third-party archives.
*
* Copyright 2020 Shea Smith
*
* 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 sheasmith.me.betterkamar.widgets;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import com.google.gson.Gson;
import com.securepreferences.SecurePreferences;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import sheasmith.me.betterkamar.R;
import sheasmith.me.betterkamar.dataModels.CalendarObject;
import sheasmith.me.betterkamar.dataModels.EventsObject;
import sheasmith.me.betterkamar.dataModels.GlobalObject;
import sheasmith.me.betterkamar.dataModels.LoginObject;
import sheasmith.me.betterkamar.dataModels.TimetableObject;
import sheasmith.me.betterkamar.internalModels.ApiResponse;
import sheasmith.me.betterkamar.internalModels.Exceptions;
import sheasmith.me.betterkamar.internalModels.PortalObject;
import sheasmith.me.betterkamar.util.ApiManager;
import sheasmith.me.betterkamar.util.WidgetApiManager;
import static android.content.Context.MODE_PRIVATE;
/**
* Created by TheDiamondPicks on 18/01/2019.
*/
public class TimetableWidgetRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
private Context mContext;
private Intent mIntent;
public List<EventsObject.Event> mEvents = new ArrayList<>();
public List<EventsObject.Event> dayEvents = new ArrayList<>();
public List<PortalObject> servers;
public List<TimetableObject.Week> timetable;
List<TimetableObject.Class> periods = new ArrayList<>();
public List<CalendarObject.Day> days = new ArrayList<>();
public List<GlobalObject.PeriodDefinition> mPeriodDefinitions;
PortalObject portal = null;
public String error = null;
private ArrayList<GlobalObject.Day> mPeriodDays;
private ArrayList<GlobalObject.PeriodTime> mPeriodTimes;
public TimetableWidgetRemoteViewsFactory(Context applicationContext, Intent intent) {
mContext = applicationContext;
mIntent = intent;
String key = "NOTHING_RANDOM_DATA_SHOULD_RETURN_NO_PORTAL";
try {
key = TimetableWidgetConfigureActivity.loadTitlePref(mContext, Integer.valueOf(intent.getData().getSchemeSpecificPart()));
} catch (NullPointerException e) {
// DO NOTHING
}
SharedPreferences preferences = applicationContext.getSharedPreferences("sheasmith.me.betterkamar", MODE_PRIVATE);
Set<String> jsonString;
if (!preferences.contains("salt")) {
// There are two possible salts, Build.SERIAL and Unknown. If it is neither we will nuke the data.
SharedPreferences serialPrefs = new SecurePreferences(applicationContext, Build.SERIAL);
jsonString = serialPrefs.getStringSet("sheasmith.me.betterkamar.portals", null);
String salt = null;
if (jsonString == null || jsonString.isEmpty() || jsonString.toArray()[0] == null) {
jsonString = null;
} else {
salt = Build.SERIAL;
}
if (jsonString == null) {
SharedPreferences unknownPrefs = new SecurePreferences(applicationContext, "UNKNOWN");
jsonString = unknownPrefs.getStringSet("sheasmith.me.betterkamar.portals", null);
if (jsonString == null || jsonString.isEmpty() || jsonString.toArray()[0] == null) {
jsonString = null;
} else {
salt = "UNKNOWN";
}
}
if (jsonString == null) {
SharedPreferences unknownPrefs = new SecurePreferences(applicationContext, Settings.Secure.getString(applicationContext.getContentResolver(), Settings.Secure.ANDROID_ID));
jsonString = unknownPrefs.getStringSet("sheasmith.me.betterkamar.portals", null);
if (jsonString == null || jsonString.isEmpty() || jsonString.toArray()[0] == null) {
jsonString = null;
} else {
salt = Settings.Secure.getString(applicationContext.getContentResolver(), Settings.Secure.ANDROID_ID);
}
}
if (jsonString == null) {
preferences.edit().putString("serial", Settings.Secure.getString(applicationContext.getContentResolver(), Settings.Secure.ANDROID_ID)).apply();
new SecurePreferences(applicationContext).edit().remove("sheasmith.me.betterkamar.portals").apply();
jsonString = new HashSet<>();
} else {
preferences.edit().putString("serial", salt).apply();
}
} else {
jsonString = new SecurePreferences(applicationContext, preferences.getString("salt", Settings.Secure.getString(applicationContext.getContentResolver(), Settings.Secure.ANDROID_ID))).getStringSet("sheasmith.me.betterkamar.portals", null);
}
servers = new ArrayList<>();
if (jsonString != null) {
for (String s : jsonString) {
Gson gson = new Gson();
PortalObject s1 = gson.fromJson(s, PortalObject.class);
servers.add(s1);
}
}
for (PortalObject p : servers) {
if ((p.username + "%" + p.schoolName).equals(key)) {
portal = p;
break;
}
}
}
@Override
public void onCreate() {
}
private void doRequest(final PortalObject portal) {
try {
WidgetApiManager.setVariables(portal, mContext);
WidgetApiManager.login(portal.username, portal.password);
WidgetApiManager.setVariables(portal, mContext);
mPeriodDefinitions = WidgetApiManager.getGlobals(false).GlobalsResults.PeriodDefinitions;
mPeriodDays = WidgetApiManager.getGlobals(false).GlobalsResults.StartTimes;
timetable = WidgetApiManager.getTimetable(false).StudentTimetableResults.Student.Timetable;
days = WidgetApiManager.getCalendar(false).CalendarResults.Days;
mEvents = WidgetApiManager.getEvents(Calendar.getInstance().get(Calendar.YEAR), false).EventsResults.Events;
} catch (Exception e) {
handleError(portal, e);
}
}
private void handleError(final PortalObject portal, Exception e) {
if (e instanceof Exceptions.ExpiredToken) {
ApiManager.login(portal.username, portal.password, new ApiResponse<LoginObject>() {
@Override
public void success(LoginObject value) {
doRequest(portal);
}
@Override
public void error(Exception e) {
e.printStackTrace();
}
});
} else if (e instanceof IOException) {
error = "You do not appear to be connected to the internet. Please check your connection and try again.";
} else if (e instanceof Exceptions.AccessDenied) {
error = "Your school has disabled access to the timetable. You may still be able to view it via the web portal.";
} else {
error = "An unknown error occurred";
e.printStackTrace();
}
}
@Override
public void onDataSetChanged() {
if (portal != null) {
error = null;
doRequest(portal);
final Date date = new Date();
Calendar current = Calendar.getInstance();
current.setTime(date);
periods = new ArrayList<>();
Calendar monday = Calendar.getInstance();
monday.setTime(date);
monday.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
int weekNumber = 0;
final Calendar temp = Calendar.getInstance();
for (CalendarObject.Day day : days) {
try {
Date start = format.parse(day.Date);
temp.setTime(start);
if (current.get(Calendar.DAY_OF_YEAR) == temp.get(Calendar.DAY_OF_YEAR) && !day.WeekYear.equals("") && !day.Status.equals("Holidays")) {
weekNumber = Integer.parseInt(day.WeekYear);
break;
}
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
if (weekNumber == 0) {
error = "No timetable entries for today.";
} else {
weekLoop:
for (TimetableObject.Week week : timetable) {
if (week.WeekNumber == weekNumber) {
for (Integer day : week.Classes.keySet()) {
Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.SUNDAY);
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
cal.add(Calendar.DAY_OF_WEEK, day);
if (cal.get(Calendar.DAY_OF_YEAR) == current.get(Calendar.DAY_OF_YEAR)) {
for (GlobalObject.Day periodDay : mPeriodDays) {
if (Integer.parseInt(periodDay.index) == day) {
mPeriodTimes = periodDay.PeriodTimes;
break;
}
}
periods = week.Classes.get(day);
break weekLoop;
}
}
}
}
dayEvents = new ArrayList<>();
for (EventsObject.Event event : mEvents) {
try {
Date start = format.parse(event.Start);
Date end = format.parse(event.Finish);
Calendar c = Calendar.getInstance();
c.setTime(start);
int startDay = c.get(Calendar.DAY_OF_YEAR);
c.setTime(end);
int endDay = c.get(Calendar.DAY_OF_YEAR);
c.setTime(date);
int currentDay = c.get(Calendar.DAY_OF_YEAR);
if (startDay >= currentDay && endDay <= currentDay) {
dayEvents.add(event);
}
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
if (periods == null) {
throw new RuntimeException();
}
if (dayEvents.size() == 0 && periods.size() == 0) {
error = "No timetable entries for today.";
}
}
} else {
error = "Portal has been deleted!";
}
}
@Override
public void onDestroy() {
}
@Override
public int getCount() {
if (dayEvents != null && mPeriodDefinitions != null && days != null && periods != null && mPeriodDays != null) {
if (dayEvents.size() + periods.size() == 0)
return 1;
return dayEvents.size() + periods.size();
} else if (error == null) {
return 1;
} else {
return 1;
}
}
@Override
public RemoteViews getViewAt(int position) {
if (error != null) {
RemoteViews errorView = new RemoteViews(mContext.getPackageName(), R.layout.timetable_widget_error);
errorView.setTextViewText(R.id.error, error);
return errorView;
} else {
RemoteViews rv = new RemoteViews(mContext.getPackageName(), R.layout.adapter_timetable);
rv.setViewVisibility(R.id.attendance, View.GONE);
if (position < dayEvents.size()) {
final EventsObject.Event event = dayEvents.get(position);
SimpleDateFormat hourFormat = new SimpleDateFormat("HH:mm:ss");
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
rv.setTextViewText(R.id.title, event.Title);
String time = "All day";
if (!event.DateTimeStart.equals("") && !event.DateTimeFinish.equals("")) {
try {
String start = timeFormat.format(hourFormat.parse(event.DateTimeStart));
String end = timeFormat.format(hourFormat.parse(event.DateTimeFinish));
time = start + " - " + end;
} catch (ParseException e) {
throw new RuntimeException(e);
}
} else if (!event.DateTimeStart.equals("")) {
try {
time = timeFormat.format(hourFormat.parse(event.DateTimeStart));
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
rv.setTextViewText(R.id.details, time);
rv.setInt(R.id.item, "setBackgroundColor", Color.parseColor("#5677fc"));
if (position == 0)
rv.setTextViewText(R.id.time, "Events");
else
rv.setTextViewText(R.id.time, "Visible");
} else {
final int pos = position - dayEvents.size();
Log.d("Widget", position + " " + dayEvents.size());
final TimetableObject.Class period = periods.get(pos);
final GlobalObject.PeriodDefinition periodDefinition = mPeriodDefinitions.get(pos);
final GlobalObject.PeriodTime periodTime = mPeriodTimes.get(pos);
rv.setTextViewText(R.id.time, periodDefinition.PeriodName);
if (!period.SubjectCode.equals("")) {
rv.setTextViewText(R.id.title, period.SubjectCode);
rv.setTextViewText(R.id.details, String.format("%s • %s • %s", periodTime.time, period.Teacher, period.Room));
final TypedArray colors = mContext.getResources().obtainTypedArray(R.array.mdcolor_500);
final int number = Math.abs(period.SubjectCode.hashCode()) % colors.length();
rv.setInt(R.id.item, "setBackgroundColor", colors.getColor(number, Color.BLACK));
rv.setViewVisibility(R.id.item, View.VISIBLE);
} else {
rv.setViewVisibility(R.id.item, View.GONE);
}
}
return rv;
}
}
@Override
public RemoteViews getLoadingView() {
return new RemoteViews(mContext.getPackageName(), R.layout.timetable_widget_loading);
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public boolean hasStableIds() {
return false;
}
}
| 44.941748 | 249 | 0.622273 |
7a8b8469a3ea2ca57cb83db90f5ae0e14a858521
| 10,516 |
package com.bulletphysics.dynamics;
import com.bulletphysics.BulletGlobals;
import com.bulletphysics.MotionState;
import com.bulletphysics.Transform;
import com.bulletphysics.collision.broadphase.BroadPhaseProxy;
import com.bulletphysics.collision.dispatch.CollisionFlags;
import com.bulletphysics.collision.dispatch.CollisionObject;
import com.bulletphysics.collision.dispatch.CollisionObjectType;
import javax.vecmath.Matrix3;
import javax.vecmath.Vector3;
public class RigidBody extends CollisionObject {
private static final float MAX_ANGVEL = BulletGlobals.HALF_PI;
private final Matrix3 invInertiaTensorWorld = new Matrix3();
private final Vector3 linearVelocity = new Vector3();
private final Vector3 angularVelocity = new Vector3();
private float inverseMass;
private float angularFactor;
private final Vector3 gravity = new Vector3();
private final Vector3 invInertiaLocal = new Vector3();
private final Vector3 totalForce = new Vector3();
private final Vector3 totalTorque = new Vector3();
private float linearDamping;
private float angularDamping;
private boolean additionalDamping;
private float additionalDampingFactor;
private float additionalLinearDampingThresholdSqr;
private float additionalAngularDampingThresholdSqr;
private float linearSleepingThreshold;
private float angularSleepingThreshold;
private MotionState optionalMotionState;
public int contactSolverType;
public int frictionSolverType;
private static int uniqueId = 0;
public int debugBodyId;
public RigidBody(RigidBodyConstructionInfo constructionInfo) {
setupRigidBody(constructionInfo);
}
private void setupRigidBody(RigidBodyConstructionInfo constructionInfo) {
internalType = CollisionObjectType.RIGID_BODY;
linearVelocity.set(0f, 0f, 0f);
angularVelocity.set(0f, 0f, 0f);
angularFactor = 1f;
gravity.set(0f, 0f, 0f);
totalForce.set(0f, 0f, 0f);
totalTorque.set(0f, 0f, 0f);
linearDamping = 0f;
angularDamping = 0.5f;
linearSleepingThreshold = constructionInfo.linearSleepingThreshold;
angularSleepingThreshold = constructionInfo.angularSleepingThreshold;
optionalMotionState = constructionInfo.motionState;
contactSolverType = 0;
frictionSolverType = 0;
additionalDamping = constructionInfo.additionalDamping;
additionalDampingFactor = constructionInfo.additionalDampingFactor;
additionalLinearDampingThresholdSqr = constructionInfo.additionalLinearDampingThresholdSqr;
additionalAngularDampingThresholdSqr = constructionInfo.additionalAngularDampingThresholdSqr;
if (optionalMotionState != null) {
optionalMotionState.getWorldTransform(worldTransform);
} else {
worldTransform.set(constructionInfo.startWorldTransform);
}
interpolationWorldTransform.set(worldTransform);
interpolationLinearVelocity.set(0f, 0f, 0f);
interpolationAngularVelocity.set(0f, 0f, 0f);
friction = constructionInfo.friction;
restitution = constructionInfo.restitution;
setCollisionShape(constructionInfo.collisionShape);
debugBodyId = uniqueId++;
setMassProps(constructionInfo.mass, constructionInfo.localInertia);
setDamping(constructionInfo.linearDamping, constructionInfo.angularDamping);
updateInertiaTensor();
}
public void proceedToTransform(Transform newTrans) {
setCenterOfMassTransform(newTrans);
}
public static RigidBody upcast(CollisionObject colObj) {
if (colObj.getInternalType() == CollisionObjectType.RIGID_BODY) {
return (RigidBody) colObj;
}
return null;
}
public void predictIntegratedTransform(float timeStep, Transform predictedTransform) {
Transform.integrateTransform(worldTransform, linearVelocity, angularVelocity, timeStep, predictedTransform);
}
public void saveKinematicState(float timeStep) {
if (timeStep != 0f) {
if (getMotionState() != null) {
getMotionState().getWorldTransform(worldTransform);
}
Transform.calculateVelocity(interpolationWorldTransform, worldTransform, timeStep, linearVelocity, angularVelocity);
interpolationLinearVelocity.set(linearVelocity);
interpolationAngularVelocity.set(angularVelocity);
interpolationWorldTransform.set(worldTransform);
}
}
public void applyGravity() {
if (isStaticOrKinematicObject()) {
return;
}
applyCentralForce(gravity);
}
public void setGravity(Vector3 acceleration) {
if (inverseMass != 0f) {
gravity.set(acceleration).mul(1f / inverseMass);
}
}
public void setDamping(float lin_damping, float ang_damping) {
linearDamping = lin_damping < 0f ? 0f : Math.min(1f, lin_damping);
angularDamping = ang_damping < 0f ? 0f : Math.min(1f, ang_damping);
}
public void applyDamping(float timeStep) {
linearVelocity.mul((float) Math.pow(1f - linearDamping, timeStep));
angularVelocity.mul((float) Math.pow(1f - angularDamping, timeStep));
if (additionalDamping) {
if (angularVelocity.lengthSquared() < additionalAngularDampingThresholdSqr && linearVelocity.lengthSquared() < additionalLinearDampingThresholdSqr) {
angularVelocity.mul(additionalDampingFactor);
linearVelocity.mul(additionalDampingFactor);
}
var speed = linearVelocity.length();
if (speed < linearDamping) {
var dampVel = 0.005f;
if (speed > dampVel) {
var dir = new Vector3(linearVelocity);
dir.normalize();
dir.mul(dampVel);
linearVelocity.sub(dir);
} else {
linearVelocity.set(0f, 0f, 0f);
}
}
var angSpeed = angularVelocity.length();
if (angSpeed < angularDamping) {
var angDampVel = 0.005f;
if (angSpeed > angDampVel) {
var dir = new Vector3(angularVelocity);
dir.normalize();
dir.mul(angDampVel);
angularVelocity.sub(dir);
} else {
angularVelocity.set(0f, 0f, 0f);
}
}
}
}
public void setMassProps(float mass, Vector3 inertia) {
if (mass == 0f) {
collisionFlags |= CollisionFlags.STATIC_OBJECT;
inverseMass = 0f;
} else {
collisionFlags &= ~CollisionFlags.STATIC_OBJECT;
inverseMass = 1f / mass;
}
invInertiaLocal.set(inertia.x != 0f ? 1f / inertia.x : 0f, inertia.y != 0f ? 1f / inertia.y : 0f, inertia.z != 0f ? 1f / inertia.z : 0f);
}
public float getInvMass() {
return inverseMass;
}
public Matrix3 getInvInertiaTensorWorld(Matrix3 out) {
out.set(invInertiaTensorWorld);
return out;
}
public void integrateVelocities(float step) {
if (isStaticOrKinematicObject()) {
return;
}
linearVelocity.scaleAdd(inverseMass * step, totalForce, linearVelocity);
var tmp = new Vector3(totalTorque);
tmp.transform(invInertiaTensorWorld);
angularVelocity.scaleAdd(step, tmp, angularVelocity);
var angvel = angularVelocity.length();
if (angvel * step > MAX_ANGVEL) {
angularVelocity.mul(MAX_ANGVEL / step / angvel);
}
}
public void setCenterOfMassTransform(Transform xform) {
if (isStaticOrKinematicObject()) {
interpolationWorldTransform.set(worldTransform);
} else {
interpolationWorldTransform.set(xform);
}
getLinearVelocity(interpolationLinearVelocity);
getAngularVelocity(interpolationAngularVelocity);
worldTransform.set(xform);
updateInertiaTensor();
}
public void applyCentralForce(Vector3 force) {
totalForce.add(force);
}
public void clearForces() {
totalForce.set(0f, 0f, 0f);
totalTorque.set(0f, 0f, 0f);
}
public void updateInertiaTensor() {
var mat1 = new Matrix3();
mat1.scale(worldTransform.basis, invInertiaLocal);
var mat2 = new Matrix3(worldTransform.basis);
mat2.transpose();
invInertiaTensorWorld.mul(mat1, mat2);
}
public Vector3 getLinearVelocity(Vector3 out) {
out.set(linearVelocity);
return out;
}
public Vector3 getAngularVelocity(Vector3 out) {
out.set(angularVelocity);
return out;
}
public void setLinearVelocity(Vector3 lin_vel) {
linearVelocity.set(lin_vel);
}
public void setAngularVelocity(Vector3 ang_vel) {
angularVelocity.set(ang_vel);
}
public Vector3 getVelocityInLocalPoint(Vector3 rel_pos, Vector3 out) {
out.cross(angularVelocity, rel_pos);
out.add(linearVelocity);
return out;
}
public void updateDeactivation(float timeStep) {
if (getActivationState() == ISLAND_SLEEPING || getActivationState() == DISABLE_DEACTIVATION) {
return;
}
if (getLinearVelocity(new Vector3()).lengthSquared() < linearSleepingThreshold * linearSleepingThreshold && getAngularVelocity(new Vector3()).lengthSquared() < angularSleepingThreshold * angularSleepingThreshold) {
deactivationTime += timeStep;
} else {
deactivationTime = 0f;
setActivationState(0);
}
}
public boolean wantsSleeping() {
if (getActivationState() == DISABLE_DEACTIVATION) {
return false;
}
if (BulletGlobals.DISABLE_DEACTIVATION || BulletGlobals.DEACTIVATION_TIME == 0f) {
return false;
}
if (getActivationState() == ISLAND_SLEEPING || getActivationState() == WANTS_DEACTIVATION) {
return true;
}
return deactivationTime > BulletGlobals.DEACTIVATION_TIME;
}
public BroadPhaseProxy getBroadphaseProxy() {
return broadphaseHandle;
}
public MotionState getMotionState() {
return optionalMotionState;
}
public float getAngularFactor() {
return angularFactor;
}
}
| 36.898246 | 222 | 0.657474 |
e2e03688edfab6b6abe542a960c8aeda6c644258
| 493 |
package net.openhft.chronicle.queue.impl.single.stress;
import org.junit.Test;
public class RollCycleMultiThreadStressPretouchTest extends RollCycleMultiThreadStressTest {
public RollCycleMultiThreadStressPretouchTest() {
super(StressTestType.PRETOUCH);
}
@Test
public void stress() throws Exception {
super.stress();
}
public static void main(String[] args) throws Exception {
new RollCycleMultiThreadStressPretouchTest().stress();
}
}
| 25.947368 | 92 | 0.730223 |
ef525a04a7d3ae1cb90cf018fc4f6fe825801f69
| 532 |
package com.zel.common.enums;
/**
* 展会状态
*
* @author andy
*/
public enum ExhibitionStatus
{
SAVE(1, "保存"),
PROSPECT(2, "勘展"),
ARRANGE(3, "布展"),
REVOKE(4, "撤展"),
END(5,"结束");
private final int code;
private final String info;
ExhibitionStatus(int code, String info)
{
this.code = code;
this.info = info;
}
public int getCode()
{
return code;
}
public String getInfo()
{
return info;
}
}
| 14 | 44 | 0.488722 |
b3ffa90720d04cac0d098a14a5e3ecf7ed12e7b5
| 477 |
package javaFundamentalsCorePlatform.basicConcepts.collections.comparison;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;
import javaFundamentalsCorePlatform.basicConcepts.collections.copy.utils.Duplicator;
public class Main {
public static void main(String[] args) {
}
}
| 23.85 | 85 | 0.78826 |
f091294bd7cf71c0a44388b7895ab00421d87c06
| 2,110 |
package gash.clock;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class VectorClock {
/** behavior of touch() if the node is not already part of the vector clock */
private boolean failOnUknown = false;
private List<ClockEntry> vector = Collections.synchronizedList(new ArrayList<ClockEntry>());
public VectorClock() {
}
/**
* creates a deep copy of the supplied clock
*
* @param vc
*/
public VectorClock(VectorClock vc) {
List<ClockEntry> vector = Collections.synchronizedList(new ArrayList<ClockEntry>());
for (ClockEntry e : vc.vector) {
ClockEntry e2 = new ClockEntry();
e2.node = e.node;
e2.timestamp = e.timestamp;
e2.version = e.version;
vector.add(e2);
}
this.vector = vector;
}
public VectorClock clone() {
return new VectorClock(this);
}
public void clear() {
vector = Collections.synchronizedList(new ArrayList<ClockEntry>());
}
public void add(String node) {
for (ClockEntry e : vector) {
if (e.getNode().equals(node))
return;
}
ClockEntry e = new ClockEntry();
e.setNode(node);
e.touch();
}
public void touch(String node) {
for (ClockEntry e : vector) {
if (e.getNode().equals(node)) {
e.touch();
return;
}
}
if (failOnUknown)
throw new RuntimeException("Unknown node: " + node);
else {
//System.out.println("---> clock: adding node " + node);
ClockEntry e = new ClockEntry();
e.setNode(node);
e.touch();
vector.add(e);
}
}
public String toString() {
StringBuffer sb = new StringBuffer();
Collections.sort(vector, new Comparator<ClockEntry>() {
@Override
public int compare(ClockEntry arg0, ClockEntry arg1) {
return arg0.node.toLowerCase().compareTo(arg1.node.toLowerCase());
}
});
//System.out.println("--> " + vector);
for (ClockEntry e : vector)
sb.append(e.toString() + " ");
return sb.toString().trim();
}
public boolean isFailOnUknown() {
return failOnUknown;
}
public void setFailOnUknown(boolean failOnUknown) {
this.failOnUknown = failOnUknown;
}
}
| 21.530612 | 93 | 0.669668 |
606000ec99d2edbe62b4346592e8d3949e16f15b
| 1,192 |
package com.syntifi.near.api.rpc.model.contract;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.syntifi.near.api.common.model.common.EncodedHash;
import com.syntifi.near.api.rpc.json.serializer.ByteArraySerializer;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Collection;
/**
* ContractFunctionCallResult
*
* @author Alexandre Carvalho
* @author Andre Bertolace
* @since 0.0.1
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class ContractFunctionCallResult {
@JsonProperty("result")
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonSerialize(using = ByteArraySerializer.class)
private byte[] result;
@JsonProperty("logs")
private Collection<String> logs;
@JsonProperty("block_height")
private long blockHeight;
@JsonProperty("block_hash")
private EncodedHash blockHash;
@JsonProperty("error")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String error;
}
| 25.361702 | 68 | 0.779362 |
4a093474d99406acde3d4169a8537511e09dc0dd
| 1,668 |
package modelo;
public class Vendedor {
private Integer idVendedor;
private String cui;
private String nombre;
private String telefono;
private String estado;
private String usuario;
private String password;
public Vendedor() {
}
public Vendedor(Integer idVendedor, String cui, String nombre, String telefono, String estado, String usuario, String password) {
this.idVendedor = idVendedor;
this.cui = cui;
this.nombre = nombre;
this.telefono = telefono;
this.estado = estado;
this.usuario = usuario;
this.password = password;
}
public Integer getIdVendedor() {
return idVendedor;
}
public void setIdVendedor(Integer idVendedor) {
this.idVendedor = idVendedor;
}
public String getCui() {
return cui;
}
public void setCui(String cui) {
this.cui = cui;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public String getUsuario() {
return usuario;
}
public void setUsuario(String usuario) {
this.usuario = usuario;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| 19.857143 | 133 | 0.607314 |
1a59064b275bab3aa35ff7ed35153b9675ab40d3
| 1,121 |
package bruteForce;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class BAEKJOON_7568 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int N = Integer.parseInt(br.readLine());
int[][] arr = new int[N][2];
for(int i = 0; i < N; i++){
st = new StringTokenizer(br.readLine()," ");
arr[i][0] = Integer.parseInt(st.nextToken());
arr[i][1] = Integer.parseInt(st.nextToken());
}
for (int i = 0; i < N; i++){
int rank = 1;
for (int j = 0; j < N; j++){
if(i == j){ //같은 사람은 비교하지 않는다.
continue;
}
// i번째 사람이 j번째 사람보다 덩치가 작을 때 rank값을 증가시킨다.
if(arr[i][0] < arr[j][0] && arr[i][1] < arr[j][1]) {
rank++;
}
}
System.out.print(rank + " ");
}
}
}
| 28.74359 | 81 | 0.487957 |
4da4b3a90d26e6f77615ce4c03c01f2b3d800c9e
| 4,653 |
package io.airlift.command.model;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import io.airlift.command.Accessor;
import io.airlift.command.Group;
import java.util.List;
public class CommandMetadata
{
private final String name;
private final String description;
private final boolean hidden;
private final List<OptionMetadata> globalOptions;
private final List<OptionMetadata> groupOptions;
private final List<OptionMetadata> commandOptions;
private final ArgumentsMetadata arguments;
private final List<Accessor> metadataInjections;
private final Class<?> type;
private final List<String> groupNames;
private final List<Group> groups;
private final List<String> examples;
private final String discussion;
public CommandMetadata(String name,
String description,
final String discussion,
final List<String> examples,
boolean hidden, Iterable<OptionMetadata> globalOptions,
Iterable<OptionMetadata> groupOptions,
Iterable<OptionMetadata> commandOptions,
ArgumentsMetadata arguments,
Iterable<Accessor> metadataInjections,
Class<?> type,
List<String> groupNames,
List<Group> groups)
{
this.name = name;
this.description = description;
this.hidden = hidden;
this.globalOptions = ImmutableList.copyOf(globalOptions);
this.groupOptions = ImmutableList.copyOf(groupOptions);
this.commandOptions = ImmutableList.copyOf(commandOptions);
this.arguments = arguments;
this.metadataInjections = ImmutableList.copyOf(metadataInjections);
this.type = type;
this.discussion = discussion;
this.examples = examples;
this.groupNames = groupNames;
this.groups = groups;
}
public String getName()
{
return name;
}
public String getDescription()
{
return description;
}
public boolean isHidden()
{
return hidden;
}
public List<OptionMetadata> getAllOptions()
{
return ImmutableList.<OptionMetadata>builder().addAll(globalOptions).addAll(groupOptions).addAll(commandOptions).build();
}
public List<String> getExamples() {
return examples;
}
public String getDiscussion() {
return discussion;
}
public List<OptionMetadata> getGlobalOptions()
{
return globalOptions;
}
public List<OptionMetadata> getGroupOptions()
{
return groupOptions;
}
public List<OptionMetadata> getCommandOptions()
{
return commandOptions;
}
public ArgumentsMetadata getArguments()
{
return arguments;
}
public List<Accessor> getMetadataInjections()
{
return metadataInjections;
}
public Class<?> getType()
{
return type;
}
public List<String> getGroupNames()
{
return groupNames;
}
public List<Group> getGroups()
{
return groups;
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("CommandMetadata");
sb.append("{name='").append(name).append('\'');
sb.append(", description='").append(description).append('\'');
sb.append(", discussion='").append(discussion).append('\'');
sb.append(", examples='").append(examples).append('\'');
sb.append(", globalOptions=").append(globalOptions);
sb.append(", groupOptions=").append(groupOptions);
sb.append(", commandOptions=").append(commandOptions);
sb.append(", arguments=").append(arguments);
sb.append(", metadataInjections=").append(metadataInjections);
sb.append(", type=").append(type);
sb.append('}');
return sb.toString();
}
public static Function<CommandMetadata, String> nameGetter()
{
return new Function<CommandMetadata, String>()
{
public String apply(CommandMetadata input)
{
return input.getName();
}
};
}
public static Function<CommandMetadata, Class> typeGetter()
{
return new Function<CommandMetadata, Class>()
{
public Class<?> apply(CommandMetadata input)
{
return input.getType();
}
};
}
}
| 27.862275 | 129 | 0.603697 |
0afaa1b5ed03836fe55c382a6a10cf81e0d8d18f
| 356 |
package com.snowman.touristspot.exception;
public class BadRequestException extends RuntimeException {
private static final long serialVersionUID = 5904867277110967104L;
public BadRequestException(String message) {
super(message);
}
public BadRequestException(String message, Throwable cause) {
super(message, cause);
}
}
| 23.733333 | 67 | 0.75 |
612ce98e022b95bae2dc1a740ee191edc5ae7da3
| 252 |
package cn.haohaoli.book.headfirst.factory.version6.ingredent.impl;
import cn.haohaoli.book.headfirst.factory.version6.ingredent.Dough;
/**
* 厚皮比萨面团
* @author LiWenHao
* @date 2019-04-28 21:12
*/
public class ThickCrustDough implements Dough {
}
| 21 | 67 | 0.765873 |
59f1fd5539840296db0e3ad41a770b59b69cc266
| 2,433 |
/**
* 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.waveprotocol.wave.client.wavepanel.impl.contact;
import org.waveprotocol.wave.client.account.ContactListener;
import org.waveprotocol.wave.client.account.ContactManager;
import org.waveprotocol.wave.client.account.Profile;
import org.waveprotocol.wave.client.account.ProfileListener;
import org.waveprotocol.wave.client.account.ProfileManager;
import org.waveprotocol.wave.model.wave.ParticipantId;
import java.util.ArrayList;
/**
* A contacts view list.
*
* @author akaplanov@gmail.com (Andrew Kaplanov)
*/
public class ContactModelList extends ArrayList<ContactModel> implements ContactListener, ProfileListener {
interface Listener {
void onContactsUpdated();
void onContactUpdated(ContactModel contact);
}
private final ContactManager contactManager;
private final ProfileManager profileManager;
private Listener listener;
public ContactModelList(ContactManager contactManager, ProfileManager profileManager) {
this.contactManager = contactManager;
this.profileManager = profileManager;
contactManager.addListener(this);
profileManager.addListener(this);
update();
}
public void setListener(Listener listener) {
this.listener = listener;
}
@Override
public void onContactsUpdated() {
update();
if (listener != null) {
listener.onContactsUpdated();
}
}
@Override
public void onProfileUpdated(Profile profile) {
if (listener != null) {
for (ContactModel contact : this) {
if (contact.getParticipantId().equals(profile.getParticipantId())) {
listener.onContactUpdated(contact);
break;
}
}
}
}
private void update() {
clear();
for (ParticipantId participantId : contactManager.getContacts()) {
add(new ContactModelImpl(participantId, profileManager.getProfile(participantId)));
}
}
}
| 30.797468 | 107 | 0.736128 |
131b26714072ef41488c57e6ced1c3c6ea982bde
| 1,353 |
package com.proposta.propostaservice.proposta;
import java.math.BigDecimal;
public class PropostaResponse {
private Long id;
private String nome;
private BigDecimal salario;
private StatusProposta status;
private String email;
private String endereco;
private String cartao;
public Long getId() {
return id;
}
public String getNome() {
return nome;
}
public BigDecimal getSalario() {
return salario;
}
public String getEmail() {
return email;
}
public String getEndereco() {
return endereco;
}
public String getCartao(){
return cartao;
}
public StatusProposta getStatus() {
return status;
}
/**
*
* @param proposta Proposta que você quer retornar como um dto
*/
public PropostaResponse(Proposta proposta) {
this.id = proposta.getId();
this.nome = proposta.getNome();
this.email = proposta.getEmail();
this.salario = proposta.getSalario();
this.endereco = proposta.getEndereco();
this.status = proposta.getStatusProposta();
if(proposta.getCartao() != null)
this.cartao = proposta.getCartao().getId();
}
/**
* Default constructor only for test mockmvc
*/
public PropostaResponse() {
}
}
| 21.47619 | 66 | 0.610495 |
18bb7f1b377c664a5646a5dbfcc4c15bb8ae415f
| 2,060 |
package net.gangelov.transporter.network.protocol;
import net.gangelov.ProgressTracker;
import net.gangelov.StreamPipe;
import net.gangelov.Streams;
import net.gangelov.transporter.network.protocol.packets.FileRequestPacket;
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.nio.channels.Channels;
public class ClientDataConnection implements Runnable {
private final Socket socket;
private final File file;
private final FileRequestPacket request;
private final ProgressTracker progressTracker;
public ClientDataConnection(Socket socket, FileRequestPacket request,
File file, ProgressTracker progressTracker) throws IOException {
this.socket = socket;
this.request = request;
this.file = file;
this.progressTracker = progressTracker;
// Send the request packet
request.serialize(new DataOutputStream(socket.getOutputStream()));
}
@Override
public void run() {
try {
transfer();
} catch (SocketException e) {
// The socket is being disconnected
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("File transferred");
}
public void disconnect() {
try {
socket.close();
} catch (IOException e) {
// Ignore close errors
}
}
public void transfer() throws IOException {
// TODO: Maybe lock the file while writing to it
RandomAccessFile fileAccess = new RandomAccessFile(file, "rw");
BufferedOutputStream out = new BufferedOutputStream(
Channels.newOutputStream(
fileAccess.getChannel().position(request.offset)
)
);
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
StreamPipe pipe = new StreamPipe(in, out, request.size, 4096, progressTracker);
pipe.pipe();
// Streams.pipe(in, out, 4096, false, request.size);
}
}
| 30.746269 | 96 | 0.650485 |
f3461d2dbc52889c45c9753d5d099186a3abbf5c
| 1,687 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package st.jigasoft.dbutil.view;
import java.awt.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JList;
import javax.swing.ListModel;
/**
*
* @author xdata
*/
public final class VerticalListView extends JList<ItemDataSet> implements Createble{
private List<Component> recicledViewList;
private ListViewManager listViewManager;
public VerticalListView(ListModel<ItemDataSet> dataModel) {
super(dataModel);
this.onCreate();
}
public VerticalListView(ItemDataSet[] listData) {
super(listData);
this.onCreate();
}
public VerticalListView(Vector<? extends ItemDataSet> listData) {
super(listData);
this.onCreate();
}
public VerticalListView() {
onCreate();
}
@Override
public void onCreate() {
this.recicledViewList = new ArrayList<>();
this.listViewManager = new ListViewManager();
super.setModel(listViewManager);
super.setCellRenderer(this.listViewManager);
}
public ListViewManager getListViewManager() {
return listViewManager;
}
@Override
public void setModel(ListModel<ItemDataSet> model) {
super.setModel(model);
}
public void addItem(ItemViewList itemViewList, ItemDataSet dataSet) {
listViewManager.add(itemViewList, dataSet);
}
public void clearItem()
{
this.listViewManager.clear();
}
}
| 24.1 | 85 | 0.671606 |
369e9f275135624a29aa5c1ff5ce3e38dae11d81
| 6,309 |
/** Notice of modification as required by the LGPL
* This file was modified by Gemstone Systems Inc. on
* $Date$
**/
package com.gemstone.org.jgroups.persistence;
/**
* @author Mandar Shinde
* This class is the factory to get access to any DB based or file based
* implementation. None of the implementations should expose directly
* to user for migration purposes
*/
import com.gemstone.org.jgroups.util.GemFireTracer;
import com.gemstone.org.jgroups.util.ExternalStrings;
import com.gemstone.org.jgroups.util.Util;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.Properties;
@SuppressFBWarnings(value="ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD",justification="GemFire doesn't use this class")
public class PersistenceFactory
{
protected final static GemFireTracer log=GemFireTracer.getLog(PersistenceFactory.class);
/**
* Default private constructor// does nothing
*/
private PersistenceFactory()
{
}
/**
* Singular public method to get access to any of the Persistence
* Manager implementations. It is important to known at this point
* that properties determine the implementation of the Persistence
* Manager, there is no direct interface which gives access to
* either DB implemented ot FILE implemented storage API.
* @return PersistenceFactory;
*/
public static PersistenceFactory getInstance() {
log.error(ExternalStrings.PersistenceFactory_GETTING_FACTORY_INSTANCE);
if (_factory == null)
_factory = new PersistenceFactory();
return _factory;
}
/**
* Register a custom persistence manager as opposed to the
* {@link FilePersistenceManager} or {@link DBPersistenceManager}.
*/
public synchronized void registerManager(PersistenceManager manager)
{
_manager = manager;
}
/**
* Reads the default properties and creates a persistencemanager
* The default properties are picked up from the $USER_HOME or
* from the classpath. Default properties are represented by
* "persist.properties"
* @return PersistenceManager
* @exception Exception;
*/
public synchronized PersistenceManager createManager() throws Exception {
// will return null if not initialized
// uses default properties
if (_manager == null)
{
if (checkDB())
_manager = createManagerDB(propPath);
else
_manager = createManagerFile(propPath);
}
return _manager;
}
/**
* Duplicated signature to create PersistenceManager to allow user to
* provide property path.
* @param filePath complete pathname to get the properties
* @return PersistenceManager;
* @exception Exception;
*/
public synchronized PersistenceManager createManager (String filePath) throws Exception
{
if (_manager == null)
{
if (checkDB(filePath))
_manager = createManagerDB(filePath);
else
_manager = createManagerFile(filePath);
}
return _manager;
}
/**
* Internal creator of DB persistence manager, the outside user accesses only
* the PersistenceManager interface API
*/
private PersistenceManager createManagerDB(String filePath) throws Exception
{
if(log.isInfoEnabled()) log.info(ExternalStrings.PersistenceFactory_CALLING_DB_PERSIST_FROM_FACTORY__0, filePath);
if (_manager == null)
_manager = new DBPersistenceManager(filePath);
return _manager;
}// end of DB persistence
/**
* creates instance of file based persistency manager
* @return PersistenceManager
*/
private PersistenceManager createManagerFile(String filePath)
{
if(log.isInfoEnabled()) log.info(ExternalStrings.PersistenceFactory_CREATING_FILE_MANAGER__0, filePath);
Properties props;
try
{
if (_manager == null)
{
props=readProps(filePath);
String classname=props.getProperty(filePersistMgr);
if(classname != null)
{
Class cl=Util.loadClass(classname, this.getClass());
Constructor ctor=cl.getConstructor(new Class[]{String.class});
_manager=(PersistenceManager)ctor.newInstance(new Object[]{filePath});
}
else
{
_manager = new FilePersistenceManager(filePath);
}
}
return _manager;
}
catch (Exception t)
{
t.printStackTrace();
return null;
}
}// end of file persistence
/**
* checks the default properties for DB/File flag
* @return boolean;
* @exception Exception;
*/
private boolean checkDB() throws Exception
{
Properties props=readProps(propPath);
String persist = props.getProperty(persistProp);
if ("DB".equals(persist))
return true;
return false;
}
/**
* checks the provided properties for DB/File flag
* @return boolean;
*/
private boolean checkDB(String filePath) throws Exception
{
Properties props=readProps(filePath);
String persist = props.getProperty(persistProp);
if ("DB".equals(persist))
return true;
return false;
}
Properties readProps(String fileName) throws IOException
{
Properties props;
FileInputStream _stream = new FileInputStream(fileName);
props=new Properties();
props.load(_stream);
return props;
}
private static PersistenceManager _manager = null;
private static PersistenceFactory _factory = null;
/* Please set this according to configuration */
final static String propPath = "persist.properties";
final static String persistProp = "persist";
/** The class that implements a file-based PersistenceManager */
final static String filePersistMgr="filePersistMgr";
}
| 30.331731 | 126 | 0.644952 |
858c8c8ed0919b2ce6845f974fe187f0559fb1a0
| 3,573 |
/*
* Copyright (c) 2014, Klaus Hauschild All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* 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 de.hauschild.gmltracer.gml.token.evaluate.render;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import com.google.common.collect.Lists;
import de.hauschild.gmltracer.gml.token.Token;
import de.hauschild.gmltracer.gml.token.base.ArrayToken;
import de.hauschild.gmltracer.gml.token.base.NumberToken;
import de.hauschild.gmltracer.gml.token.base.StringToken;
import de.hauschild.gmltracer.gml.token.evaluate.Evaluate;
import de.hauschild.gmltracer.gml.token.geometry.PointToken;
import de.hauschild.gmltracer.gml.token.geometry.ShapeToken;
import de.hauschild.gmltracer.gml.token.light.LightToken;
import de.hauschild.gmltracer.tracer.impl.GmlRaytracer;
import de.hauschild.gmltracer.tracer.light.Light;
/**
* @since 1.0
* @author Klaus Hauschild
*/
public class RenderEvaluate implements Evaluate {
@Override
public void evaluate(final Stack<Token> tokenStack, final Map<String, Token> environment) {
final StringToken fileName = (StringToken) tokenStack.pop();
final NumberToken height = (NumberToken) tokenStack.pop();
final NumberToken width = (NumberToken) tokenStack.pop();
final NumberToken fieldOfView = (NumberToken) tokenStack.pop();
final NumberToken depth = (NumberToken) tokenStack.pop();
final ShapeToken scene = (ShapeToken) tokenStack.pop();
final ArrayToken lightArray = (ArrayToken) tokenStack.pop();
final List<Light> lights = Lists.newArrayList();
for (final Token light : lightArray.getValue()) {
if (!(light instanceof LightToken)) {
throw new ClassCastException(String.format("[%s] is [%s] expected was [%s]", light,
light.getClass(), LightToken.class));
}
lights.add(((LightToken) light).getValue());
}
final PointToken ambientLightIntensity = (PointToken) tokenStack.pop();
new GmlRaytracer().render(ambientLightIntensity.getValue(), lights, scene.getValue(),
depth.getValue().intValue(), fieldOfView.getValue(),
width.getValue().intValue(), height.getValue().intValue(),
fileName.getValue());
}
}
| 50.323944 | 120 | 0.725441 |
b33ae87c3e3e02506c26d228ae0213e4f1ab5aa0
| 1,305 |
package me.yarinlevi.qskywars.games;
import me.yarinlevi.minigameframework.MinigameFramework;
import me.yarinlevi.minigameframework.arena.Arena;
import me.yarinlevi.minigameframework.exceptions.ArenaNotExistException;
import me.yarinlevi.minigameframework.exceptions.NoArenaAvailable;
import me.yarinlevi.minigameframework.game.Game;
import me.yarinlevi.minigameframework.game.GameManager;
/**
* @author YarinQuapi
**/
public class SkywarsGameManager extends GameManager {
@Override
public Game createGame(Arena arena) throws NoArenaAvailable {
if (arena.isAssigned()) {
throw new NoArenaAvailable();
} else {
SkywarsGame game = new SkywarsGame(arena);
arena.setAssigned(true);
this.getAvailableGames().add(game);
return game;
}
}
@Override
public Game createGame(String arenaGame) throws ArenaNotExistException, NoArenaAvailable {
Arena arena = MinigameFramework.getFramework().getArenaManager().getArena(arenaGame);
if (!arena.isAssigned()) {
Game game = new SkywarsGame(arena);
arena.setAssigned(true);
this.getAvailableGames().add(game);
return game;
} else {
throw new NoArenaAvailable();
}
}
}
| 33.461538 | 94 | 0.682759 |
6c2bf6e13a1f535191004fcd6cd9f04f647262ad
| 1,023 |
package com.jsong.oom.heap;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
/**
* Function:方法区内存溢出
* 1.8之后修改为元数据区
*
* CGLIB基于ASM实现。提供比反射更为强大的动态特性。使用CGLIB可以非常方便的实现的动态代理。
*
* @href https://www.cnblogs.com/shijiaqi1066/p/3429691.html CGLIB学习笔记
* @author jsong
* Date: 29/12/2017 21:34
* @since JDK 1.8
*/
public class MetaSpaceOOM {
public static void main(String[] args) {
while (true){
Enhancer enhancer = new Enhancer() ;
enhancer.setSuperclass(HeapOOM.class);
enhancer.setUseCache(false) ;
enhancer.setCallback(new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
return methodProxy.invoke(o,objects) ;
}
});
enhancer.create() ;
}
}
}
| 26.921053 | 126 | 0.626588 |
3905afa89b55093c7439c18845ba09a13a8eb80f
| 686 |
package online.minipixel.smp.WarpSystem;
import online.minipixel.smp.Main;
import org.bukkit.Location;
public class WarpManager {
public static Location getWarp(String name) {
return Main.getWarps().getConfiguration().getLocation(name);
}
public static void createWarp(String name, Location location) {
Main.getWarps().set(name, location);
Main.getWarps().save();
}
public static void deleteWarp(String name) {
Main.getWarps().isClear(true);
Main.getWarps().save();
}
public static void reloadConfig() {
Main.getWarps().reload();
}
}
| 24.5 | 71 | 0.597668 |
44dcf3a98a199972c307a8f4550e93cce30350d8
| 2,664 |
/*
* MIT License
*
* Copyright (c) 2021 Demeng Chen
*
* 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.demeng.rankgrantplus.menus;
import dev.demeng.pluginbase.chat.Placeholders;
import dev.demeng.pluginbase.menu.model.MenuButton;
import dev.demeng.rankgrantplus.RankGrantPlus;
import dev.demeng.rankgrantplus.util.ConfigMenu;
import dev.demeng.rankgrantplus.util.Utils;
import java.util.Objects;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
/**
* The menu for selecting the rank to grant.
*/
public class RankSelectMenu extends ConfigMenu {
public RankSelectMenu(RankGrantPlus i, Player issuer, OfflinePlayer target) {
super(i, "rank-select", Placeholders.of("%target%",
Objects.requireNonNull(target.getName(), "Target name is null")));
for (String rank : Objects.requireNonNull(
i.getRanks().getConfigurationSection("ranks"), "Ranks section is null")
.getKeys(false)) {
final String permission = i.getRanks().getString("ranks." + rank + ".permission");
// Do not display the rank if the issuer does not have the required permission.
if (permission != null
&& !permission.equalsIgnoreCase("none")
&& !issuer.hasPermission(permission)) {
continue;
}
addButton(MenuButton.fromConfig(
Objects.requireNonNull(i.getRanks().getConfigurationSection("ranks." + rank)),
Placeholders
.of("%target%", target.getName())
.add("%rank%", Utils.getRankName(rank)),
event -> new DurationSelectMenu(i, issuer, target, rank).open(issuer)));
}
}
}
| 39.761194 | 88 | 0.716592 |
0ffbf8dcaef0527d4584a769879fac3ea707a118
| 1,514 |
// "Fix all 'Loop can be collapsed with Stream API' problems in file" "true"
import java.util.*;
import java.util.stream.Collectors;
class Test {
List<String> test(String[] list) {
return Arrays.stream(list).filter(s -> !s.isEmpty()).collect(Collectors.toUnmodifiableList());
}
Collection<String> test2(String[] list) {
return Arrays.stream(list).filter(s -> !s.isEmpty()).collect(Collectors.toUnmodifiableSet());
}
List<String> test3(String[] array) {
return Arrays.stream(array).filter(s -> !s.isEmpty()).distinct().collect(Collectors.toUnmodifiableList());
}
Set<String> test4(String[] array) {
Set<String> result = Arrays.stream(array).filter(s -> !s.isEmpty()).collect(Collectors.toCollection(TreeSet::new));
// toUnmodifiableSet will not preserve order; not suggested here
return Collections.unmodifiableSet(result);
}
Map<String, Integer> map(List<String> input) {
return input.stream().filter(s -> !s.isEmpty()).collect(Collectors.toUnmodifiableMap(s -> s, s -> s.length(), (a, b) -> b));
}
Map<String, Integer> map1(List<String> input) {
Map<String, Integer> result = input.stream().filter(s -> !s.isEmpty()).collect(Collectors.toMap(s -> s, String::length, (a, b) -> b, TreeMap::new));
return Collections.unmodifiableMap(result);
}
Map<String, Integer> map2(int[] input) {
return Arrays.stream(input).filter(s -> s > 0).boxed().collect(Collectors.toUnmodifiableMap(s -> String.valueOf(s), s -> s, (a, b) -> b));
}
}
| 42.055556 | 152 | 0.671731 |
f7c7ba072b676dbaa8cf1d65ecfbf7a575b803c0
| 849 |
package slack.android.api.webapi.params;
import java.util.HashMap;
import java.util.Map;
/**
* Set a list of optional params to use in a slack web api methods.
*/
public abstract class Params {
private Map<String, String> params;
public Params(){
params = new HashMap<>();
}
public Map<String, String> build(){
return params;
}
void put(String key, String value){
params.put(key, value);
}
void put(String key, boolean value){
params.put(key, value ? "1" : "0");
}
void put(String key, int value){
params.put(key, String.valueOf(value));
}
void put(String key, int value, int min, int max){
if(value < min){
value = min;
}
else if(value > max){
value = max;
}
put(key, value);
}
}
| 19.295455 | 67 | 0.557126 |
0b59a311e79ca39dcf777f59d2797b375506b0f4
| 1,545 |
package interviewquestions;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
// Please change the extension of the file to .java
// I added .txt because udemy currently does not allow to add .java files
public class WorkingWithElementsList {
private WebDriver driver;
private String baseUrl;
@Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver","C:\\Users\\me\\Downloads\\Day01Selenium (1)\\Day01\\chromedriver.exe");
driver = new ChromeDriver();
baseUrl="https://courses.letskodeit.com/practice";
// Maximize the browser's window
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(baseUrl);
}
@Test
public void testListOfElements() throws Exception {
boolean isChecked = false;
List<WebElement> radioButtons = driver.findElements(
By.xpath("//input[contains(@type,'radio') and contains(@name,'cars')]"));
int size = radioButtons.size();
System.out.println("Size of the list: " + size);
for (int i=0; i<size; i++) {
isChecked = radioButtons.get(i).isSelected();
if (!isChecked) {
radioButtons.get(i).click();
Thread.sleep(2000);
}
}
}
@After
public void tearDown() throws Exception {
Thread.sleep(2000);
driver.quit();
}
}
| 26.186441 | 120 | 0.720388 |
4efd565e6d1f222ab946d670469c7adab0619a0c
| 420 |
package backend.food.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import backend.food.domain.Tag;
@Repository
@Transactional
public interface TagRepository extends JpaRepository<Tag, Integer> {
public Optional<Tag> findByName(String name);
}
| 23.333333 | 68 | 0.833333 |
5414ef0741a963849447a97caf00d1cdc0b9ee6b
| 4,602 |
package com.zeligsoft.domain.omg.ccm.api.CCM_Implementation.impl;
import com.zeligsoft.base.zdl.staticapi.util.ZDLFactoryRegistry;
import com.zeligsoft.domain.omg.ccm.api.CCM_Implementation.MonolithicImplementation;
import com.zeligsoft.domain.zml.api.ZML_Component.impl.StructuralRealizationImplementation;
import com.zeligsoft.domain.zml.api.ZML_Component.WorkerFunction;
import com.zeligsoft.domain.omg.ccm.api.CCM_Implementation.ComponentCategory;
import com.zeligsoft.base.zdl.util.ZDLUtil;
public class MonolithicImplementationImplementation extends
StructuralRealizationImplementation implements MonolithicImplementation {
protected ComponentCategory _category;
protected java.util.List<WorkerFunction> _worker;
public MonolithicImplementationImplementation(
org.eclipse.emf.ecore.EObject element) {
super(element);
}
@Override
public String getName() {
final Object rawValue = com.zeligsoft.base.zdl.util.ZDLUtil.getValue(
eObject(), "CCM::CCM_Implementation::MonolithicImplementation",
"name");
return (String) rawValue;
}
@Override
public void setName(String val) {
ZDLUtil.setValue(element,
"CCM::CCM_Implementation::MonolithicImplementation", "name",
val);
}
@Override
public ComponentCategory getCategory() {
final Object rawValue = com.zeligsoft.base.zdl.util.ZDLUtil.getValue(
eObject(), "CCM::CCM_Implementation::MonolithicImplementation",
"category");
if (_category == null) {
if (rawValue instanceof org.eclipse.emf.ecore.EObject) {
_category = ComponentCategory
.create((org.eclipse.emf.ecore.EObject) rawValue);
}
}
return _category;
}
@Override
public void setCategory(ComponentCategory val) {
ZDLUtil.setValue(element,
"CCM::CCM_Implementation::MonolithicImplementation",
"category", val.eObject(element));
}
@Override
public java.util.List<WorkerFunction> getWorker() {
if (_worker == null) {
final Object rawValue = com.zeligsoft.base.zdl.util.ZDLUtil
.getValue(eObject(),
"ZMLMM::ZML_Component::Implementation", "worker");
_worker = new java.util.ArrayList<WorkerFunction>();
@SuppressWarnings("unchecked")
final java.util.List<Object> rawList = (java.util.List<Object>) rawValue;
for (Object next : rawList) {
if (next instanceof org.eclipse.emf.ecore.EObject) {
WorkerFunction nextWrapper = ZDLFactoryRegistry.INSTANCE
.create((org.eclipse.emf.ecore.EObject) next,
WorkerFunction.class);
_worker.add(nextWrapper);
}
}
}
return _worker;
}
@Override
public void addWorker(WorkerFunction val) {
// make sure the worker list is created
getWorker();
final Object rawValue = ZDLUtil.getValue(element,
"ZMLMM::ZML_Component::Implementation", "worker");
@SuppressWarnings("unchecked")
final java.util.List<Object> rawList = (java.util.List<Object>) rawValue;
rawList.add(val.eObject());
if (_worker != null) {
_worker.add(val);
}
}
@Override
public <T extends WorkerFunction> T addWorker(Class<T> typeToCreate,
String concept) {
// make sure the worker list is created
getWorker();
org.eclipse.emf.ecore.EObject newConcept = ZDLUtil.createZDLConcept(
element, "ZMLMM::ZML_Component::Implementation", "worker",
concept);
T element = ZDLFactoryRegistry.INSTANCE.create(
newConcept, typeToCreate);
if (_worker != null) {
_worker.add(element);
}
return element;
}
@Override
public WorkerFunction addWorker() {
// make sure the worker list is created
getWorker();
org.eclipse.emf.ecore.EObject newConcept = ZDLUtil.createZDLConcept(
element, "ZMLMM::ZML_Component::Implementation", "worker",
"ZMLMM::ZML_Component::WorkerFunction");
WorkerFunction element = ZDLFactoryRegistry.INSTANCE.create(
newConcept,
WorkerFunction.class);
if (_worker != null) {
_worker.add(element);
}
return element;
}
@Override
public String getUuid() {
final Object rawValue = com.zeligsoft.base.zdl.util.ZDLUtil.getValue(
eObject(), "ZMLMM::ZML_Component::WorkerFunctionIdentifiable",
"uuid");
return (String) rawValue;
}
@Override
public void setUuid(String val) {
ZDLUtil.setValue(element,
"ZMLMM::ZML_Component::WorkerFunctionIdentifiable", "uuid", val);
}
@Override
public String getQualifiedName() {
final Object rawValue = com.zeligsoft.base.zdl.util.ZDLUtil.getValue(
eObject(), "ZMLMM::ZML_Core::NamedElement", "qualifiedName");
return (String) rawValue;
}
@Override
public org.eclipse.uml2.uml.NamedElement asNamedElement() {
return (org.eclipse.uml2.uml.NamedElement) eObject();
}
}
| 29.883117 | 91 | 0.737288 |
4d4eed98132a8262ec17acc71bd6af2c8905646b
| 5,745 |
package customSynTool;
import java.util.concurrent.FutureTask;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* @ClassName AnaylzeAQSTool
* @Author bin
* @Date 2020/6/11 上午10:38
* @Decr TODO
* 简单分析concurrent中的阻塞类,基于AQS的实现
* @Link TODO
**/
public class AnaylzeAQSTool {
ReentrantLock reentrantLock = new ReentrantLock();
/**
* Base of synchronization control for this lock. Subclassed
* into fair and nonfair versions below. Uses AQS state to
* represent the number of holds on the lock.
*/
abstract static class ReenTrantSync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = -5179523762034025860L;
/**
* Performs {@link Lock#lock}. The main reason for subclassing
* is to allow fast path for nonfair version.
*/
abstract void lock();
/**
* Performs non-fair tryLock. tryAcquire is implemented in
* subclasses, but both need nonfair try for trylock method.
* 非公平的tryAcquire.
*/
final boolean nonfairTryAcquire(int acquires) {
//获取当前线程
final Thread current = Thread.currentThread();
//线程状态
int c = getState();
//c=0 ,锁未被持有
if (c == 0) {
//原子地更新状态,表示锁已经被占用
if (compareAndSetState(0, acquires)) {
//设置 锁的拥有者
setExclusiveOwnerThread(current);
return true;
}
}
//如果当前线程 与 锁的拥有者相同,可重入
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
//否则失败
return false;
}
protected final boolean tryRelease(int releases) {
//获取当前状态
int c = getState() - releases;
//当前线程 != 锁持有的线程,则抛出异常
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
//若当前状态 =0,则表示锁是打开的
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
protected final boolean isHeldExclusively() {
// While we must in general read state before owner,
// we don't need to do so to check if current thread is owner
return getExclusiveOwnerThread() == Thread.currentThread();
}
final ConditionObject newCondition() {
return new ConditionObject();
}
// Methods relayed from outer class
final Thread getOwner() {
return getState() == 0 ? null : getExclusiveOwnerThread();
}
final int getHoldCount() {
return isHeldExclusively() ? getState() : 0;
}
final boolean isLocked() {
return getState() != 0;
}
/**
* Reconstitutes the instance from a stream (that is, deserializes it).
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
setState(0); // reset to unlocked state
}
}
Semaphore semaphore = new Semaphore(2);
/**
* Synchronization implementation for semaphore. Uses AQS state
* to represent permits. Subclassed into fair and nonfair
* versions.
*/
abstract static class SemaphoreSync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 1192457210091910933L;
//设置许可的数量
SemaphoreSync(int permits) {
setState(permits);
}
final int getPermits() {
return getState();
}
final int nonfairTryAcquireShared(int acquires) {
for (;;) {
//计算可用的许可
int available = getState();
//剩余的许可
int remaining = available - acquires;
//若没有许可,则循环将终止
//如果还有剩余的许可,原子方式降低许可的计数
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
}
}
protected final boolean tryReleaseShared(int releases) {
for (;;) {
int current = getState();
int next = current + releases;
if (next < current) // overflow
throw new Error("Maximum permit count exceeded");
if (compareAndSetState(current, next))
return true;
}
}
final void reducePermits(int reductions) {
for (;;) {
int current = getState();
int next = current - reductions;
if (next > current) // underflow
throw new Error("Permit count underflow");
if (compareAndSetState(current, next))
return;
}
}
final int drainPermits() {
for (;;) {
int current = getState();
if (current == 0 || compareAndSetState(current, 0))
return current;
}
}
}
}
| 30.558511 | 79 | 0.536641 |
0a97c9feb0dcfadb2413428590f57232580bce9b
| 1,177 |
package com.mingchao.snsspider.qq.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import com.google.common.hash.Funnel;
import com.google.common.hash.PrimitiveSink;
import com.mingchao.snsspider.model.IdAble;
/**
* 用于调度用户
* @author yangchaojun
*
*/
@Entity(name="t_schedule_user_key")
public class ScheduleUserKey implements IdAble{
private Long id;
private Long qq;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getQq() {
return qq;
}
public void setQq(Long qq) {
this.qq = qq;
}
@Override
public String toString() {
return "ScheduleUserKey [id=" + id + ", qq=" + qq + "]";
}
public static Funnel<ScheduleUserKey> getFunnel(){
return ScheduleUserKeyFunnel.INSTANCE;
}
}
enum ScheduleUserKeyFunnel implements Funnel<ScheduleUserKey> {
INSTANCE;
public void funnel(ScheduleUserKey from, PrimitiveSink into) {
into.putLong(from.getQq());
}
@Override
public String toString() {
return "Funnels.ScheduleUserKeyFunnel()";
}
}
| 19.949153 | 63 | 0.735769 |
acb03fae58fba7b2a8c11092158daf64b8496c3f
| 2,888 |
package com.nitorcreations.willow.metrics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHitField;
import com.nitorcreations.willow.messages.metrics.MetricConfig;
import com.nitorcreations.willow.messages.metrics.TimePoint;
public abstract class SimpleMetric<L extends Comparable, T> extends AbstractMetric<T> {
protected SortedMap<Long, L> rawData = new TreeMap<Long, L>();
private Map<String, SearchHitField> fields;
@Override
public abstract String getType();
public abstract String[] requiresFields();
protected void readResponse(SearchResponse response) {
for (SearchHit next : response.getHits().getHits()) {
fields = next.getFields();
Long timestamp = fields.get("timestamp").value();
List<T> nextData = new ArrayList<>();
for (String nextField : requiresFields()) {
if (fields.get(nextField) == null) {
break;
}
nextData.add((T) fields.get(nextField).value());
}
if (nextData.size() == requiresFields().length) {
rawData.put(timestamp, getValue(nextData));
}
}
}
@SuppressWarnings("unchecked")
protected L getValue(List<T> arr) {
return (L) arr.get(0);
}
@Override
public List<TimePoint<L>> calculateMetric(MetricConfig conf) {
List<String> reqFields = new ArrayList<String>();
reqFields.add("timestamp");
reqFields.addAll(Arrays.asList(requiresFields()));
SearchResponse response = executeQuery(client, conf, getType(), reqFields);
readResponse(response);
int len = (int) ((conf.getStop() - conf.getStart()) / conf.getStep()) + 1;
List<TimePoint<L>> ret = new ArrayList<TimePoint<L>>();
if (rawData.isEmpty()) {
return ret;
}
List<Long> retTimes = new ArrayList<Long>();
long curr = conf.getStart();
for (int i = 0; i < len; i++) {
retTimes.add(Long.valueOf(curr));
curr += conf.getStep();
}
for (Long nextTime : retTimes) {
long afterNextTime = nextTime + 1;
Collection<L> preceeding = rawData.headMap(afterNextTime).values();
rawData = rawData.tailMap(afterNextTime);
List<L> tmplist = new ArrayList<L>(preceeding);
if (tmplist.isEmpty()) {
ret.add(new TimePoint(nextTime.longValue(), fillMissingValue()));
continue;
}
ret.add(new TimePoint(nextTime.longValue(), estimateValue(tmplist, nextTime, conf.getStep(), conf)));
}
return ret;
}
protected L estimateValue(List<L> preceeding, long stepTime, long stepLen, MetricConfig conf) {
return preceeding.get(preceeding.size() - 1);
}
protected abstract L fillMissingValue();
}
| 33.581395 | 107 | 0.681094 |
1025cf3f2274bc01755fe4488c417d0addd98052
| 844 |
package com.heyi.UniversityNews.Utils;
import android.content.Context;
import android.view.View;
import android.view.animation.AlphaAnimation;
/**
* Created by heyi on 2017/1/7.
*/
public class AnimationUtils {
private AnimationUtils(){}
public static void showAndHidden( View target, long time){
AlphaAnimation aa=new AlphaAnimation(0.0f,1.0f);
aa.setDuration(time);
aa.setFillAfter(true);
target.startAnimation(aa);
AlphaAnimation aa1=new AlphaAnimation(1.0f,0.0f);
aa1.setDuration(time);
aa1.setFillAfter(true);
target.startAnimation(aa1);
}
public static void hidden(View target,long time){
AlphaAnimation aa=new AlphaAnimation(1.0f,0.0f);
aa.setDuration(time);
aa.setFillAfter(true);
target.startAnimation(aa);
}
}
| 25.575758 | 62 | 0.671801 |
0d377e5cf5655714b97435d4715966e3dd248184
| 4,968 |
/*
* MIT License
*
* Copyright (c) 2018 Kirill
*
* 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 wtf.g4s8.hamcrest.json;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonValue;
import wtf.g4s8.oot.SimpleTest;
import wtf.g4s8.oot.TestCase;
import wtf.g4s8.oot.TestGroup;
/**
* Test case for JSON matchers.
*
* @since 0.1
* @checkstyle JavadocMethodCheck (500 lines)
* @checkstyle JavadocParameterOrderCheck (500 lines)
*/
public final class JsonHasCase extends TestGroup.Wrap {
/**
* Ctor.
*/
public JsonHasCase() {
super(
new TestGroup.Of(
"json-has",
new JsonHasCase.JsonFields(),
new JsonHasCase.MatchesString(),
new JsonHasCase.MatchesBool(),
new JsonHasCase.MatchesNull()
)
);
}
/**
* Test case against JSON object fields.
* @since 1.0
*/
private static final class JsonFields extends TestCase.Wrap {
/**
* Default ctor.
*/
JsonFields() {
this("foo", "bar", 1);
}
/**
* Primary ctor.
*/
private JsonFields(final String foo, final String bar, final int num) {
super(
new SimpleTest<JsonObject>(
"matches json items",
() -> Json.createObjectBuilder()
.add(
foo,
Json.createObjectBuilder()
.add(bar, num)
.build()
).build(),
new JsonHas(
foo,
new JsonHas(
bar,
new JsonValueIs(num)
)
)
)
);
}
}
/**
* Test case against JSON bool items.
* @since 1.0
*/
private static final class MatchesBool extends TestCase.Wrap {
/**
* Default ctor.
*/
MatchesBool() {
this("key");
}
/**
* Primary ctor.
*/
private MatchesBool(final String key) {
super(
new SimpleTest<JsonObject>(
"matches bool value",
() -> Json.createObjectBuilder().add(key, JsonValue.TRUE).build(),
new JsonHas(key, new JsonValueIs(Boolean.TRUE))
)
);
}
}
/**
* Test case against JSON string item.
* @since 1.0
*/
private static final class MatchesString extends TestCase.Wrap {
/**
* Default ctor.
*/
MatchesString() {
this("key123", "asdfasdberg34bf");
}
/**
* Primary ctor.
*/
private MatchesString(final String key, final String val) {
super(
new SimpleTest<JsonObject>(
"matches string",
() -> Json.createObjectBuilder().add(key, val).build(),
new JsonHas(key, new JsonValueIs(val))
)
);
}
}
/**
* Test case against JSON null items.
* @since 1.0
*/
private static final class MatchesNull extends TestCase.Wrap {
/**
* Default ctor.
*/
MatchesNull() {
this("key-null");
}
/**
* Primary ctor.
*/
private MatchesNull(final String key) {
super(
new SimpleTest<JsonObject>(
"matches null",
() -> Json.createObjectBuilder().add(key, JsonValue.NULL).build(),
new JsonHas(key, JsonValueIs.NULL)
)
);
}
}
}
| 27.910112 | 86 | 0.513486 |
eedd28845ef1d8ab7c26a5177ba532a6c81dfc4d
| 342 |
package io.cscanner.core.rule.firewall;
import io.cscanner.core.test.engine.CloudProvider;
import javax.annotation.ParametersAreNonnullByDefault;
@ParametersAreNonnullByDefault
public interface FirewallCloudProvider<CONFIGURATIONTYPE, CONNECTIONTYPE extends FirewallConnection> extends CloudProvider<CONFIGURATIONTYPE, CONNECTIONTYPE> {
}
| 34.2 | 159 | 0.871345 |
69c3aa2ae16236553f6a2c587db6926abef4b315
| 3,202 |
package net.avcompris.tools.diagrammer;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.apache.commons.lang3.StringUtils.substringBeforeLast;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import net.avcompris.tools.diagrammer.sample.MyFirstDiagram;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class AllSamplesTest {
@Parameters(name = "{0}")
public static Collection<Object[]> parameters() throws Exception {
final List<Object[]> parameters = new ArrayList<Object[]>();
final String packageName = MyFirstDiagram.class.getPackage().getName();
for (final File file : new File("src/test/java/"
+ packageName.replace('.', File.separatorChar)).listFiles()) {
if (!file.isFile()) {
continue;
}
final String filename = file.getName();
if (!filename.endsWith(".java")) {
continue;
}
final String sampleDiagrammerSimpleClassName = substringBeforeLast(
filename, ".java");
final String sampleDiagrammerClassName = packageName + "."
+ sampleDiagrammerSimpleClassName;
@SuppressWarnings("unchecked")
final Class<? extends AvcDiagrammer> sampleDiagrammerClass = //
(Class<? extends AvcDiagrammer>) Class
.forName(sampleDiagrammerClassName);
if (Modifier.isAbstract(sampleDiagrammerClass.getModifiers())) {
continue;
}
parameters.add(new Object[] { sampleDiagrammerSimpleClassName,
sampleDiagrammerClass });
}
return parameters;
}
public AllSamplesTest(final String classSimpleName,
final Class<? extends AvcDiagrammer> sampleDiagrammerClass) {
this.sampleDiagrammerClass = checkNotNull(sampleDiagrammerClass,
"sampleDiagrammerClass");
assertEquals(classSimpleName, sampleDiagrammerClass.getSimpleName());
outFile = new File("target", classSimpleName + ".svg");
}
private final Class<? extends AvcDiagrammer> sampleDiagrammerClass;
private final File outFile;
@Test
public void testMain() throws Exception {
generateSVG();
}
private void generateSVG() throws Exception {
sampleDiagrammerClass.getMethod("main", String[].class).invoke(null,
new Object[] { new String[0] });
}
@Test
public void testOutFilename() throws Exception {
outFile.delete();
generateSVG();
assertTrue(
"outFile should be created by sample class: "
+ outFile.getPath(), outFile.exists());
}
@Test
public void svgIsWellFormed() throws Exception {
if (!outFile.exists()) {
generateSVG();
}
final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
documentBuilderFactory.setValidating(false);
documentBuilderFactory.setNamespaceAware(true);
final DocumentBuilder documentBuilder = documentBuilderFactory
.newDocumentBuilder();
documentBuilder.parse(outFile);
}
}
| 25.212598 | 78 | 0.749844 |
c8eddfbd18691e2e6ce495192940a5e8df1585b3
| 2,738 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.braisdom.objsql.sql.function;
import com.github.braisdom.objsql.sql.Expression;
import com.github.braisdom.objsql.sql.SqlFunctionCall;
import com.github.braisdom.objsql.sql.expression.PlainExpression;
import static com.github.braisdom.objsql.sql.Expressions.literal;
public class Oracle {
public static final Expression cosh(Integer literal) {
return new SqlFunctionCall("COSH", literal(literal));
}
public static final Expression cosh(Expression expression) {
return new SqlFunctionCall("COSH", expression);
}
public static final Expression addMonth(Expression expression, Integer delta) {
return new SqlFunctionCall("ADD_MONTHS", expression, literal(delta));
}
public static final Expression toDate(Expression expression, String format) {
return new SqlFunctionCall("to_char", expression, literal(format));
}
public static final Expression toDateYYYY_MM_DD(Expression expression, String format) {
return toDate(expression, "yyyy-MM-dd");
}
public static final Expression toDateYYYY_MM_DD_hh_mi_ss(Expression expression, String format) {
return toDate(expression, "yyyy-mm-dd hh24:mi:ss");
}
public static final Expression toTimestamp(Expression expression, String format) {
return new SqlFunctionCall("to_timestamp", expression, literal(format));
}
public static final Expression toTimestampYYYY_MM_DD(Expression expression, String format) {
return toDate(expression, "yyyy-MM-dd");
}
public static final Expression toTimestampYYYY_MM_DD_hh_mi_ss(Expression expression, String format) {
return toDate(expression, "yyyy-mm-dd hh24:mi:ss");
}
public static final Expression timestamp(String string) {
return new PlainExpression(new StringBuilder().append("TIMESTAMP ")
.append("'").append(string).append("'").toString());
}
}
| 39.681159 | 105 | 0.735208 |
cea4bedfb089546c19cb6f267c4b6cd1a36e58ba
| 13,191 |
/**
* Copyright 2017 Goldman Sachs.
* 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.gs.obevo.impl.reader;
import com.gs.obevo.api.appdata.ChangeInput;
import com.gs.obevo.api.platform.ChangeType;
import com.gs.obevo.impl.DeployMetricsCollectorImpl;
import com.gs.obevo.util.hash.DbChangeHashStrategy;
import com.gs.obevo.util.vfs.FileObject;
import org.apache.commons.vfs2.FileName;
import org.eclipse.collections.api.block.function.Function;
import org.eclipse.collections.api.list.ImmutableList;
import org.eclipse.collections.impl.block.factory.Predicates;
import org.eclipse.collections.impl.set.mutable.UnifiedSet;
import org.junit.Rule;
import org.junit.Test;
import org.junit.internal.matchers.ThrowableMessageMatcher;
import org.junit.rules.ExpectedException;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TableChangeParserTest {
@Rule
public final ExpectedException thrown = ExpectedException.none();
private final String objectName = "MyObj";
private final ChangeType tableChangeType = mock(ChangeType.class);
private final GetChangeType getChangeType = TableChangeParser.DEFAULT_IMPL;
private static class EmptyContentHashStrategy implements DbChangeHashStrategy {
@Override
public String hashContent(String content) {
return content.length() > 6 ? content.substring(0, 6).toLowerCase() : content.toLowerCase();
}
}
@Test
public void testTemplate() throws Exception {
TableChangeParser parser = new TableChangeParser(new EmptyContentHashStrategy(), getChangeType);
String fileContent = "//// METADATA templateParams=\"suffix=1;suffix=2\"\n" +
"//// CHANGE name=chng1\ncreate1\n" +
"//// CHANGE name=chng2\ncreate2\n" +
"";
ImmutableList<ChangeInput> changes = parser.value(tableChangeType, null, fileContent, "MyTemplate${suffix}", "schema", null);
assertEquals(4, changes.size());
assertEquals(2, changes.count(Predicates.attributeEqual(new Function<ChangeInput, Object>() {
@Override
public Object valueOf(ChangeInput it) {
return it.getObjectName();
}
}, "MyTemplate1")));
assertEquals(2, changes.count(Predicates.attributeEqual(new Function<ChangeInput, Object>() {
@Override
public Object valueOf(ChangeInput it) {
return it.getObjectName();
}
}, "MyTemplate2")));
}
@Test
public void invalidNoContentAllowedInMetadata() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expect(new ThrowableMessageMatcher<Throwable>(containsString("First content of the file must be the")));
TableChangeParser parser = new TableChangeParser(new EmptyContentHashStrategy(), getChangeType);
String fileContent = "contentNotAllowedHere\n" +
"//// METADATA\n" +
"invalid content\n" +
"//// CHANGE name=chng1\n" +
"CREATE TABLE;\n" +
"";
parser.value(tableChangeType, null, fileContent, objectName, "schema", null);
}
@Test
public void invalidNoContentAllowedInPrologue1() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expect(new ThrowableMessageMatcher<Throwable>(containsString("First content of the file must be the")));
TableChangeParser parser = new TableChangeParser(new EmptyContentHashStrategy(), getChangeType);
String fileContent = "contentNotAllowedHere\n" +
"//// METADATA\n" +
"//// CHANGE name=chng1\n" +
"CREATE TABLE;\n" +
"";
parser.value(tableChangeType, null, fileContent, objectName, "schema", null);
}
@Test
public void invalidNoContentAllowedInPrologue2() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expect(new ThrowableMessageMatcher<Throwable>(containsString("First content of the file must be the")));
TableChangeParser parser = new TableChangeParser(new EmptyContentHashStrategy(), getChangeType);
String fileContent = "contentNotAllowedHere\n" +
"//// CHANGE name=chng1\n" +
"CREATE TABLE;\n" +
"";
parser.value(tableChangeType, null, fileContent, objectName, "schema", null);
}
@Test
public void invalidNoContentAllowedInPrologue3() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expect(new ThrowableMessageMatcher<Throwable>(containsString("No //// CHANGE sections found")));
TableChangeParser parser = new TableChangeParser(new EmptyContentHashStrategy(), getChangeType);
String fileContent = "contentNotAllowedHere\n" +
"CREATE TABLE;\n" +
"";
parser.value(tableChangeType, null, fileContent, objectName, "schema", null);
}
@Test
public void noMetadataContentAllowedAfterFirstLine1() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expect(new ThrowableMessageMatcher<Throwable>(containsString("Instead, found this section in between")));
TableChangeParser parser = new TableChangeParser(new EmptyContentHashStrategy(), getChangeType);
String fileContent = "\n" +
"//// METADATA\n" +
"//// CHANGE name=chng1\n" +
"CREATE TABLE;\n" +
"//// METADATA\n" +
"//// CHANGE name=chng1\n" +
"CREATE TABLE;\n" +
"";
parser.value(tableChangeType, null, fileContent, objectName, "schema", null);
}
@Test
public void noMetadataContentAllowedAfterFirstLine1_FineInBackwardsCompatibleMode() throws Exception {
TableChangeParser parser = new TableChangeParser(new EmptyContentHashStrategy(), true, new DeployMetricsCollectorImpl(), new TextMarkupDocumentReader(false), getChangeType);
String fileContent = "\n" +
"//// METADATA\n" +
"//// CHANGE name=chng1\n" +
"CREATE TABLE;\n" +
"//// METADATA\n" +
"//// CHANGE name=chng1\n" +
"CREATE TABLE;\n" +
"";
parser.value(tableChangeType, null, fileContent, objectName, "schema", null);
}
@Test
public void noMetadataContentAllowedAfterFirstLine2() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expect(new ThrowableMessageMatcher<Throwable>(containsString("Instead, found this section in between")));
TableChangeParser parser = new TableChangeParser(new EmptyContentHashStrategy(), getChangeType);
String fileContent = "\n" +
"//// CHANGE name=chng1\n" +
"CREATE TABLE;\n" +
"//// METADATA\n" +
"";
parser.value(tableChangeType, null, fileContent, objectName, "schema", null);
}
@Test
public void noMetadataContentAllowedAfterFirstLine2_FineInBackwardsCompatibleMode() throws Exception {
TableChangeParser parser = new TableChangeParser(new EmptyContentHashStrategy(), true, new DeployMetricsCollectorImpl(), new TextMarkupDocumentReader(false), getChangeType);
String fileContent = "\n" +
"//// CHANGE name=chng1\n" +
"CREATE TABLE;\n" +
"//// METADATA\n" +
"";
parser.value(tableChangeType, null, fileContent, objectName, "schema", null);
}
@Test
public void noMetadataContentAllowedAfterFirstLine3() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expect(new ThrowableMessageMatcher<Throwable>(containsString("Instead, found this section in between")));
TableChangeParser parser = new TableChangeParser(new EmptyContentHashStrategy(), getChangeType);
String fileContent = "\n" +
"//// METADATA\n" +
"//// METADATA\n" +
"//// CHANGE name=chng1\n" +
"CREATE TABLE;\n" +
"//// METADATA\n" +
"";
parser.value(tableChangeType, null, fileContent, objectName, "schema", null);
}
@Test
public void noMetadataContentAllowedAfterFirstLine3_FineInBackwardsCompatibleMode() throws Exception {
TableChangeParser parser = new TableChangeParser(new EmptyContentHashStrategy(), true, new DeployMetricsCollectorImpl(), new TextMarkupDocumentReader(false), getChangeType);
String fileContent = "\n" +
"//// METADATA\n" +
"//// METADATA\n" +
"//// CHANGE name=chng1\n" +
"CREATE TABLE;\n" +
"//// METADATA\n" +
"";
parser.value(tableChangeType, null, fileContent, objectName, "schema", null);
}
@Test
public void noContentAtAll1() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expect(new ThrowableMessageMatcher<Throwable>(containsString("No //// " + TextMarkupDocumentReader.TAG_CHANGE + " sections found; at least one is required")));
TableChangeParser parser = new TableChangeParser(new EmptyContentHashStrategy(), getChangeType);
String fileContent = "";
parser.value(tableChangeType, null, fileContent, objectName, "schema", null);
}
@Test
public void noContentAtAll2() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expect(new ThrowableMessageMatcher<Throwable>(containsString("No //// " + TextMarkupDocumentReader.TAG_CHANGE + " sections found; at least one is required")));
TableChangeParser parser = new TableChangeParser(new EmptyContentHashStrategy(), getChangeType);
String fileContent = "\n" +
"//// METADATA\n" +
"";
parser.value(tableChangeType, null, fileContent, objectName, "schema", null);
}
@Test
public void testDbChange() {
ChangeInput change = new TableChangeParser(new EmptyContentHashStrategy(), getChangeType)
.value(tableChangeType,
null, "//// CHANGE name=chng5Rollback applyGrants=true INACTIVE baselinedChanges=\"a,b,c\" \nmychange\n\n// ROLLBACK-IF-ALREADY-DEPLOYED\nmyrollbackcommand\n", objectName
, "schem", null).get(0);
assertEquals("schem", change.getObjectKey().getSchema());
assertEquals("chng5Rollback", change.getChangeKey().getChangeName());
assertEquals("mychange\n", change.getContent());
assertEquals("mychan", change.getContentHash());
assertEquals("myrollbackcommand", change.getRollbackIfAlreadyDeployedContent());
assertEquals(UnifiedSet.newSetWith("a", "b", "c"), change.getBaselinedChanges().toSet());
assertFalse(change.isActive());
assertTrue(change.getApplyGrants());
}
@Test
public void testDbChange2DiffValues() {
ChangeInput change = new TableChangeParser(new EmptyContentHashStrategy(), getChangeType)
.value(tableChangeType,
null, "//// CHANGE name=chng5Rollback INACTIVE baselinedChanges=\"a,b,c\" \nmychange\n\n// ROLLBACK-IF-ALREADY-DEPLOYED\nmyrollbackcommand\n", objectName
, "schem", null).get(0);
assertEquals("schem", change.getObjectKey().getSchema());
assertEquals("chng5Rollback", change.getChangeKey().getChangeName());
assertEquals("mychange\n", change.getContent());
assertEquals("mychan", change.getContentHash());
assertEquals("myrollbackcommand", change.getRollbackIfAlreadyDeployedContent());
assertEquals(UnifiedSet.newSetWith("a", "b", "c"), change.getBaselinedChanges().toSet());
assertFalse(change.isActive());
assertNull(change.getApplyGrants());
}
private FileObject file(String fileName, String fileContent) {
FileName fileNameObj = mock(FileName.class);
when(fileNameObj.getBaseName()).thenReturn(fileName);
FileObject file = mock(FileObject.class);
when(file.getName()).thenReturn(fileNameObj);
when(file.getStringContent()).thenReturn(fileContent);
return file;
}
}
| 44.414141 | 194 | 0.65757 |
d6443c3a9d56d4ec8c8e987681511ccb3025b13a
| 134 |
package com.darly.im.ui.chatting;
public class GlobalConstant {
public static final int ACTIVITY_FOR_RESULT_VIDEORECORD=0x9;
}
| 14.888889 | 61 | 0.791045 |
e551e70c583f416d9bd27671daa3cd412aee4160
| 1,531 |
package net.rubenmartinez.cbcc.logparsing.components.impl;
import net.rubenmartinez.cbcc.logparsing.components.LogLineParser;
import net.rubenmartinez.cbcc.domain.ConnectionLogLine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class BasicLogLineParser implements LogLineParser {
private static final Logger LOGGER = LoggerFactory.getLogger(BasicLogLineParser.class);
private static final String HOSTS_CONNECTION_LINE_SEPARATOR = " ";
@Override
public ConnectionLogLine parseLine(String line) {
//LOGGER.trace("Processing line in Thread [{}]: {}", Thread.currentThread(), line);
String[] items = line.split(HOSTS_CONNECTION_LINE_SEPARATOR);
if (items.length != 3) {
throw new IllegalArgumentException(String.format("Error while parsing host connections file, format must be strictly: <unix_timestamp>'%s'<sourceHost>'%s'<targetHost>, but the following line couldn't be parsed: %s", HOSTS_CONNECTION_LINE_SEPARATOR, HOSTS_CONNECTION_LINE_SEPARATOR, line));
}
long timestamp;
try {
timestamp = Long.valueOf(items[0]);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Error while parsing host connections file line, first item must be a unix timestamp. Line: " + line, e);
}
var hostsConnectionLine = new ConnectionLogLine(timestamp, items[1], items[2]);
return hostsConnectionLine;
}
}
| 40.289474 | 301 | 0.728282 |
aaad5a65fe01bf6733071f120e8fa27e30bdb1bf
| 1,251 |
/*
Copyright 2021 aholinch
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 odutils.ephem.od;
import java.util.List;
import odutils.ephem.CartesianState;
/**
* This class should be expanded to support weights and other observation types.
*
* @author aholinch
*
*/
public class ObservationSet
{
protected String cartsFrame;
protected List<CartesianState> carts;
public ObservationSet()
{
}
public void setCartsFrame(String frame)
{
cartsFrame = frame;
}
public String getCartsFrame()
{
return cartsFrame;
}
public void setCarts(List<CartesianState> list)
{
carts = list;
}
public List<CartesianState> getCarts()
{
return carts;
}
}
| 20.85 | 80 | 0.696243 |
c41a5c61278c0f96e1d2d14076dc12ffe91bb9b8
| 1,889 |
package syncAssit.semaphore2More;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by Yao on 2015/8/27.
*/
public class Printer {
private int iCnt= 3;
private boolean[] printerStatus;
private final Semaphore semaphore;
private Lock lockPriters;
public Printer() {
semaphore= new Semaphore(3);
printerStatus= new boolean[iCnt];
for (int i = 0; i < iCnt; i++) {
printerStatus[i]= true;
}
lockPriters= new ReentrantLock();
}
public void print(){
try{
semaphore.acquire();
System.out.printf("--->%s wait for printer. \n", Thread.currentThread().getName());
int pIdx= getPrinter();
long duration= (long)(Math.random()* 5);
System.out.printf("<---%s print %d seconds. \n", Thread.currentThread().getName(), duration);
TimeUnit.SECONDS.sleep(duration);
printerStatus[pIdx]= true;
System.out.printf("\t%d printer finished\n", pIdx);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
}
/**
* 返回当前空闲的打印机进程
* @return
*/
public int getPrinter(){
int idx= -1;
try{
lockPriters.lock();
for (int i = 0; i < iCnt; i++) {
if(printerStatus[i]){
idx= i;
System.out.printf("\t%d printer is send to use\n", idx);
printerStatus[i]= false;
break;
}
}
}catch (Exception ex){
ex.printStackTrace();
}finally {
lockPriters.unlock();
}
return idx;
}
}
| 26.605634 | 105 | 0.528851 |
5337730cc84bf8bdbce7cd0411dd3aea13d05db0
| 300 |
package by.babroval.bike.utils;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class CurrencyUtils {
public static BigDecimal roundNumber(final BigDecimal number, final boolean isFloor) {
return number.setScale(2, isFloor ? RoundingMode.FLOOR : RoundingMode.CEILING);
}
}
| 23.076923 | 87 | 0.79 |
65c8292cac5c7638198b6601c744bab7e6048ba7
| 1,056 |
package com.yy.admin.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yy.admin.dao.RoleMapper;
import com.yy.admin.entity.Role;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class RoleService {
@Resource
private RoleMapper roleMapper;
public List<Role> getList(Page page, String name) {
roleMapper.selectPage(page, new QueryWrapper<Role>()
.like(name != null, "name", name));
return page.getRecords();
}
public void delete(Integer id) {
roleMapper.deleteById(id);
}
public void save(Role role) {
Assert.hasText(role.getName(), "名称不能为空");
if (role.getId() == null) {
role.setCreateTime(LocalDateTime.now());
role.insert();
} else {
role.updateById();
}
}
}
| 25.756098 | 67 | 0.668561 |
eef1cec12568d6d4c78cb6dfdec807fcf2b931bd
| 3,189 |
package com.taobao.tddl.repo.mysql.spi;
import java.sql.SQLException;
import com.taobao.tddl.executor.common.ExecutionContext;
import com.taobao.tddl.executor.cursor.ICursorMeta;
import com.taobao.tddl.executor.cursor.ISchematicCursor;
import com.taobao.tddl.executor.record.CloneableRecord;
import com.taobao.tddl.executor.rowset.IRowSet;
import com.taobao.tddl.executor.spi.ITable;
import com.taobao.tddl.optimizer.config.table.IndexMeta;
import com.taobao.tddl.optimizer.core.plan.IPut;
/**
* 集中所有jdbc操作到这个Handler. 这样才能支持同步化和异步化执行
*
* @author Whisper 2013-6-20 上午9:32:46
* @since 3.0.1
*/
public interface GeneralQueryHandler {
/**
* 初始化结果集
*
* @param oneQuery
* @param meta
* @param isStreaming
* @throws SQLException
*/
public abstract void executeQuery(ICursorMeta meta, boolean isStreaming) throws SQLException;
/**
* 自动提交?
*
* @return
* @throws SQLException
*/
public abstract boolean isAutoCommit() throws SQLException;
/**
* 获取结果集
*
* @return
*/
public abstract ISchematicCursor getResultCursor();
/**
* 设置dataSource
*
* @param ds
*/
public abstract void setDs(Object ds);
/**
* 关闭,但不是真关闭
*
* @throws SQLException
*/
public abstract void close() throws SQLException;
/**
* 跳转(不过大部分指针都不支持这个)
*
* @param key
* @param indexMeta
* @return
* @throws Exception
*/
public abstract boolean skipTo(CloneableRecord key, ICursorMeta indexMeta) throws SQLException;
/**
* 指针下移 返回null则表示没有后项了
*
* @return
* @throws Exception
*/
public abstract IRowSet next() throws SQLException;
/**
* 最开始的row
*
* @return
* @throws Exception
*/
public abstract IRowSet first() throws SQLException;
/**
* 最后一个row
*
* @return
* @throws Exception
*/
public abstract IRowSet last() throws SQLException;
/**
* 获取当前row
*
* @return
*/
public abstract IRowSet getCurrent();
/**
* 是否触发过initResultSet()这个方法。 与isDone不同的是这个主要是防止多次提交用。(估计)
*
* @return
*/
public abstract boolean isInited();
/**
* 获取上一个数据
*
* @return
* @throws Exception
*/
public abstract IRowSet prev() throws SQLException;
/**
* 执行一个update语句
*
* @param sqlAndParam
* @return
* @throws SQLException
*/
public void executeUpdate(ExecutionContext executionContext, IPut put, ITable table, IndexMeta meta)
throws SQLException;
/**
* 用于异步化,等同于Future.isDone();
*
* @return
*/
public abstract boolean isDone();
/**
* 用于异步化,等同于Future.cancel();
*/
public abstract void cancel(boolean mayInterruptIfRunning);
/**
* 用于异步化,等同于Future.isCancel();
*
* @return
*/
public abstract boolean isCanceled();
/**
* 指针前移
*
* @throws SQLException
*/
public void beforeFirst() throws SQLException;
}
| 20.707792 | 124 | 0.587645 |
a29ecee0b2fda8664498dca50f3f290430d0f3ea
| 2,525 |
package graphql.scalar;
import graphql.Internal;
import graphql.language.IntValue;
import graphql.schema.Coercing;
import graphql.schema.CoercingParseLiteralException;
import graphql.schema.CoercingParseValueException;
import graphql.schema.CoercingSerializeException;
import java.math.BigDecimal;
import java.math.BigInteger;
import static graphql.scalar.CoercingUtil.isNumberIsh;
import static graphql.scalar.CoercingUtil.typeName;
@Internal
public class GraphqlIntCoercing implements Coercing<Integer, Integer> {
private static final BigInteger INT_MAX = BigInteger.valueOf(Integer.MAX_VALUE);
private static final BigInteger INT_MIN = BigInteger.valueOf(Integer.MIN_VALUE);
private Integer convertImpl(Object input) {
if (input instanceof Integer) {
return (Integer) input;
} else if (isNumberIsh(input)) {
BigDecimal value;
try {
value = new BigDecimal(input.toString());
} catch (NumberFormatException e) {
return null;
}
try {
return value.intValueExact();
} catch (ArithmeticException e) {
return null;
}
} else {
return null;
}
}
@Override
public Integer serialize(Object input) {
Integer result = convertImpl(input);
if (result == null) {
throw new CoercingSerializeException(
"Expected type 'Int' but was '" + typeName(input) + "'."
);
}
return result;
}
@Override
public Integer parseValue(Object input) {
Integer result = convertImpl(input);
if (result == null) {
throw new CoercingParseValueException(
"Expected type 'Int' but was '" + typeName(input) + "'."
);
}
return result;
}
@Override
public Integer parseLiteral(Object input) {
if (!(input instanceof IntValue)) {
throw new CoercingParseLiteralException(
"Expected AST type 'IntValue' but was '" + typeName(input) + "'."
);
}
BigInteger value = ((IntValue) input).getValue();
if (value.compareTo(INT_MIN) < 0 || value.compareTo(INT_MAX) > 0) {
throw new CoercingParseLiteralException(
"Expected value to be in the Integer range but it was '" + value.toString() + "'"
);
}
return value.intValue();
}
}
| 31.5625 | 101 | 0.598416 |
5f8e8e2352574457a76532a8fa1bc7c80fad1e79
| 843 |
package LeetCode.无法归类;
import java.util.*;
/**
* @Author Aqinn
* @Date 2021/4/21 8:14 上午
*/
public class 存在重复元素 {
/**
* 题目描述:
* 给定一个整数数组,判断是否存在重复元素。
* 如果存在一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。
* <p>
* 输入: [1,1,1,3,3,4,3,2,4,2]
* 输出: true
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/contains-duplicate
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public boolean containsDuplicate(int[] nums) {
if (nums == null) {
return false;
}
Set<Integer> set = new HashSet<>();
int len = nums.length;
for (int i = 0; i < len; i++) {
if (set.contains(nums[i])) {
return true;
} else {
set.add(nums[i]);
}
}
return false;
}
}
| 20.560976 | 61 | 0.492289 |
d2ebdecd8a0f9ce96485531aae29739dcc459402
| 2,903 |
package com.bytx.admin.controller;
import com.bytx.admin.entity.Media;
import com.bytx.admin.service.CompanyMediaPersistenceService;
import com.bytx.admin.service.MediaQueryService;
import com.bytx.admin.util.SFTPUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@Controller
@RequestMapping("/media")
public class CompanyMediaController extends BaseController
{
@Autowired
private MediaQueryService mediaQueryService;
@Autowired
private CompanyMediaPersistenceService companyMediaPersistenceService;
@RequestMapping("/showMedia")
public String showMediaInfo(Map model)
{
List<Media> mediaList = mediaQueryService.selectAllMedia();
model.put("mediaList", mediaList);
return "admin/companymedia";
}
@RequestMapping("/updateMediaInfo")
@ResponseBody
public Integer updateMediaInfo(HttpServletRequest request, Media media)
{
MultipartFile file = ((MultipartHttpServletRequest) request).getFile("imageFile");
List<Media> mediaList = mediaQueryService.selectAllMedia();
for (var media1 : mediaList)
{
if (media.getId().equals(media1.getId()))
{
media.setMediaId(media1.getMediaId());
break;
}
}
if (!Objects.isNull(file))
{
String originalFileName = file.getOriginalFilename();
String basePath = request.getServletContext().getRealPath("/");
String rootPath = basePath + storageImagePath + "/media";
String tempPath = rootPath + "/" + media.getMediaId() + "/" + originalFileName;
File tempFile = new File(tempPath);
String remotePath = "/data/wwwroot/default" + storageImagePath + "/media/" + media.getMediaId();
String remoteUrl = accessImageUrl + storageImagePath + "/media/" + media.getMediaId() + "/" + originalFileName;
try
{
FileUtils.forceMkdir(tempFile.getParentFile());
file.transferTo(tempFile);
SFTPUtil.uploadFile(BaseController.channelSftp, tempPath, remotePath);
media.setImages(remoteUrl);
}
catch (IOException e)
{
e.printStackTrace();
}
}
return companyMediaPersistenceService.updateMedia(media);
}
}
| 33.755814 | 123 | 0.675853 |
6fcd54f7b5efd3fbb431252d9f37d1e46f1b5df8
| 14,608 |
/*
* Isilon SDK
* Isilon SDK - Language bindings for the OneFS API
*
* OpenAPI spec version: 5
* Contact: sdk@isilon.com
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.client.api;
import io.swagger.client.ApiException;
import java.math.BigDecimal;
import io.swagger.client.model.ClusterAddNodeItem;
import io.swagger.client.model.ClusterConfig;
import io.swagger.client.model.ClusterEmail;
import io.swagger.client.model.ClusterEmailExtended;
import io.swagger.client.model.ClusterIdentity;
import io.swagger.client.model.ClusterNode;
import io.swagger.client.model.ClusterNodesAvailable;
import io.swagger.client.model.ClusterNodesExtendedExtended;
import io.swagger.client.model.ClusterNodesExtendedExtendedExtended;
import io.swagger.client.model.ClusterOwner;
import io.swagger.client.model.ClusterStatfs;
import io.swagger.client.model.ClusterTime;
import io.swagger.client.model.ClusterTimeExtended;
import io.swagger.client.model.ClusterTimezone;
import io.swagger.client.model.ClusterTimezoneExtended;
import io.swagger.client.model.ClusterVersion;
import io.swagger.client.model.DiagnosticsGatherSettings;
import io.swagger.client.model.DiagnosticsGatherSettingsExtended;
import io.swagger.client.model.DiagnosticsGatherStatus;
import io.swagger.client.model.DiagnosticsNetloggerSettings;
import io.swagger.client.model.DiagnosticsNetloggerStatus;
import io.swagger.client.model.Empty;
import io.swagger.client.model.Error;
import io.swagger.client.model.TimezoneRegionTimezone;
import io.swagger.client.model.TimezoneRegions;
import io.swagger.client.model.TimezoneSettings;
import org.junit.Test;
import org.junit.Ignore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* API tests for ClusterApi
*/
@Ignore
public class ClusterApiTest {
private final ClusterApi api = new ClusterApi();
/**
*
*
* Serial number and arguments of node to add.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void createClusterAddNodeItemTest() throws ApiException {
ClusterAddNodeItem clusterAddNodeItem = null;
Empty response = api.createClusterAddNodeItem(clusterAddNodeItem);
// TODO: test validations
}
/**
*
*
* Start a new gather
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void createDiagnosticsGatherStartItemTest() throws ApiException {
DiagnosticsGatherSettingsExtended diagnosticsGatherStartItem = null;
Empty response = api.createDiagnosticsGatherStartItem(diagnosticsGatherStartItem);
// TODO: test validations
}
/**
*
*
* Stop a running gather
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void createDiagnosticsGatherStopItemTest() throws ApiException {
Empty diagnosticsGatherStopItem = null;
Empty response = api.createDiagnosticsGatherStopItem(diagnosticsGatherStopItem);
// TODO: test validations
}
/**
*
*
* Start a new packet caputre
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void createDiagnosticsNetloggerStartItemTest() throws ApiException {
DiagnosticsNetloggerSettings diagnosticsNetloggerStartItem = null;
Empty response = api.createDiagnosticsNetloggerStartItem(diagnosticsNetloggerStartItem);
// TODO: test validations
}
/**
*
*
* Stop a running packet capture
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void createDiagnosticsNetloggerStopItemTest() throws ApiException {
Empty diagnosticsNetloggerStopItem = null;
Empty response = api.createDiagnosticsNetloggerStopItem(diagnosticsNetloggerStopItem);
// TODO: test validations
}
/**
*
*
* Retrieve the cluster information.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getClusterConfigTest() throws ApiException {
ClusterConfig response = api.getClusterConfig();
// TODO: test validations
}
/**
*
*
* Get the cluster email notification settings.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getClusterEmailTest() throws ApiException {
ClusterEmail response = api.getClusterEmail();
// TODO: test validations
}
/**
*
*
* Retrieve the cluster IP addresses including IPV4 and IPV6.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getClusterExternalIpsTest() throws ApiException {
List<String> response = api.getClusterExternalIps();
// TODO: test validations
}
/**
*
*
* Retrieve the login information.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getClusterIdentityTest() throws ApiException {
ClusterIdentity response = api.getClusterIdentity();
// TODO: test validations
}
/**
*
*
* Retrieve node information.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getClusterNodeTest() throws ApiException {
Integer clusterNodeId = null;
BigDecimal timeout = null;
ClusterNodesExtendedExtended response = api.getClusterNode(clusterNodeId, timeout);
// TODO: test validations
}
/**
*
*
* List the nodes on this cluster.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getClusterNodesTest() throws ApiException {
BigDecimal timeout = null;
ClusterNodesExtendedExtendedExtended response = api.getClusterNodes(timeout);
// TODO: test validations
}
/**
*
*
* List all nodes that are available to add to this cluster.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getClusterNodesAvailableTest() throws ApiException {
ClusterNodesAvailable response = api.getClusterNodesAvailable();
// TODO: test validations
}
/**
*
*
* Get the cluster contact info settings
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getClusterOwnerTest() throws ApiException {
ClusterOwner response = api.getClusterOwner();
// TODO: test validations
}
/**
*
*
* Retrieve the filesystem statistics.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getClusterStatfsTest() throws ApiException {
ClusterStatfs response = api.getClusterStatfs();
// TODO: test validations
}
/**
*
*
* Retrieve the current time as reported by each node.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getClusterTimeTest() throws ApiException {
ClusterTime response = api.getClusterTime();
// TODO: test validations
}
/**
*
*
* Get the cluster timezone.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getClusterTimezoneTest() throws ApiException {
ClusterTimezone response = api.getClusterTimezone();
// TODO: test validations
}
/**
*
*
* Retrieve the OneFS version as reported by each node.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getClusterVersionTest() throws ApiException {
ClusterVersion response = api.getClusterVersion();
// TODO: test validations
}
/**
*
*
* Get the status of isi_gather_info.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getDiagnosticsGatherTest() throws ApiException {
DiagnosticsGatherStatus response = api.getDiagnosticsGather();
// TODO: test validations
}
/**
*
*
* Get the default options for isi_gather_info.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getDiagnosticsGatherSettingsTest() throws ApiException {
DiagnosticsGatherSettings response = api.getDiagnosticsGatherSettings();
// TODO: test validations
}
/**
*
*
* Get the status of isi_gather_info.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getDiagnosticsGatherStatusTest() throws ApiException {
DiagnosticsGatherStatus response = api.getDiagnosticsGatherStatus();
// TODO: test validations
}
/**
*
*
* Get the status of isi_netlogger.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getDiagnosticsNetloggerTest() throws ApiException {
DiagnosticsNetloggerStatus response = api.getDiagnosticsNetlogger();
// TODO: test validations
}
/**
*
*
* Get the default options for isi_netlogger.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getDiagnosticsNetloggerSettingsTest() throws ApiException {
DiagnosticsNetloggerSettings response = api.getDiagnosticsNetloggerSettings();
// TODO: test validations
}
/**
*
*
* Get the status of isi_netlogger.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getDiagnosticsNetloggerStatusTest() throws ApiException {
DiagnosticsNetloggerStatus response = api.getDiagnosticsNetloggerStatus();
// TODO: test validations
}
/**
*
*
* List timezone regions.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getTimezoneRegionTest() throws ApiException {
String timezoneRegionId = null;
String sort = null;
String resume = null;
Boolean showAll = null;
Boolean dstReset = null;
Integer limit = null;
String dir = null;
TimezoneRegions response = api.getTimezoneRegion(timezoneRegionId, sort, resume, showAll, dstReset, limit, dir);
// TODO: test validations
}
/**
*
*
* Retrieve the cluster timezone.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getTimezoneSettingsTest() throws ApiException {
TimezoneSettings response = api.getTimezoneSettings();
// TODO: test validations
}
/**
*
*
* Modify the cluster email notification settings. All input fields are optional, but one or more must be supplied.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void updateClusterEmailTest() throws ApiException {
ClusterEmailExtended clusterEmail = null;
api.updateClusterEmail(clusterEmail);
// TODO: test validations
}
/**
*
*
* Modify one or more node settings.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void updateClusterNodeTest() throws ApiException {
ClusterNode clusterNode = null;
Integer clusterNodeId = null;
api.updateClusterNode(clusterNode, clusterNodeId);
// TODO: test validations
}
/**
*
*
* Modify the cluster contact info settings. All input fields are optional, but one or more must be supplied.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void updateClusterOwnerTest() throws ApiException {
ClusterOwner clusterOwner = null;
api.updateClusterOwner(clusterOwner);
// TODO: test validations
}
/**
*
*
* Set cluster time. Time will mostly be synchronized across nodes, but there may be slight drift.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void updateClusterTimeTest() throws ApiException {
ClusterTimeExtended clusterTime = null;
api.updateClusterTime(clusterTime);
// TODO: test validations
}
/**
*
*
* Set a new timezone for the cluster.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void updateClusterTimezoneTest() throws ApiException {
ClusterTimezoneExtended clusterTimezone = null;
api.updateClusterTimezone(clusterTimezone);
// TODO: test validations
}
/**
*
*
* Set the default options for isi_gather_info.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void updateDiagnosticsGatherSettingsTest() throws ApiException {
DiagnosticsGatherSettingsExtended diagnosticsGatherSettings = null;
api.updateDiagnosticsGatherSettings(diagnosticsGatherSettings);
// TODO: test validations
}
/**
*
*
* Set the default options for isi_netlogger.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void updateDiagnosticsNetloggerSettingsTest() throws ApiException {
DiagnosticsNetloggerSettings diagnosticsNetloggerSettings = null;
api.updateDiagnosticsNetloggerSettings(diagnosticsNetloggerSettings);
// TODO: test validations
}
/**
*
*
* Modify the cluster timezone.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void updateTimezoneSettingsTest() throws ApiException {
TimezoneRegionTimezone timezoneSettings = null;
api.updateTimezoneSettings(timezoneSettings);
// TODO: test validations
}
}
| 25.142857 | 120 | 0.621166 |
2a3017d393583ce17b5f4575e9f3b4b7aabbee27
| 3,927 |
/**
* Copyright (C) 2010-18 diirt developers. See COPYRIGHT.TXT
* All rights reserved. Use is subject to license terms. See LICENSE.TXT
*/
package org.diirt.util.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/***
* <p>
* Provides settings from settings.xml in DIIRT.HOME. The settings.xml follows convention:
* <pre>
* {@code
* <settings>
* <mykey value="myvalue">
* </settings>
* }
* </pre>
* Settings are parsed into memory the first time a setting is accessed. Reload method is provided for reloading settings.xml file.
*
* @author Borut Terpinc - borut.terpinc@cosylab.com
*
*/
public class SettingsProvider {
private static Logger LOGGER = Logger.getLogger(Configuration.class.getName());
private static Map<String, String> allSettings;
private SettingsProvider() {
}
private static void getSettingsFromFile() {
final String path = Configuration.getDirectory() + "/settings.xml";
try {
File file = new File(path);
if (!file.exists()) {
return;
}
LOGGER.log(Level.CONFIG, "Loading DIIRT settings from: " + file.getAbsolutePath());
InputStream fileInput = new FileInputStream(file);
parseSettingsFromXml(fileInput, allSettings);
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, "Couldn't load DIIRT_HOME/" + path, ex);
}
}
private static void parseSettingsFromXml(InputStream input, Map<String, String> settingsMap) {
try {
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
final Document document = builder.parse(input);
final XPathFactory xpathFactory = XPathFactory.newInstance();
final XPath xPath = xpathFactory.newXPath();
final XPathExpression xpathExpression = xPath.compile("/settings/*");
NodeList nodeList = (NodeList) xpathExpression.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentNode = nodeList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
if (currentNode.getNodeName() != null) {
settingsMap.put(currentNode.getNodeName(), currentNode.getAttributes().getNamedItem("value").getNodeValue());
LOGGER.log(Level.FINE,
"Loading setting: " + currentNode.getNodeName() + ", value: " + currentNode.getAttributes().getNamedItem("value").getNodeValue());
}
}
}
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, "Couldn't parse settings.xml file", ex);
}
}
/***
* Get setting for given key
*
* @param setting key
* @return setting value as string
*/
public static String getSetting(String setting) {
// all settings are loaded the first time, we want to access them.
if (allSettings == null) {
allSettings = new HashMap<String, String>(1);
getSettingsFromFile();
}
return allSettings.get(setting);
}
/***
* Reloads settings form settings.xml file
*/
public static void reloadSettings() {
getSettingsFromFile();
}
}
| 33.564103 | 163 | 0.638146 |
1b94c5ac9ebda846f942649ff63e8e318024dc9f
| 297 |
package de.gothaer.application;
import de.gothaer.geometrie.Kreis;
import de.gothaer.geometrie.Punkt;
public class PunktTest {
public static void main(String[] args) {
Object o;
Punkt p;
Kreis k;
o = new Kreis();
System.out.println(o.toString());
}
}
| 14.142857 | 42 | 0.632997 |
9a9ff2a4686e2438a7338928b3c60f9c48e9f9ba
| 285 |
/*
* Author: jianqing
* Date: Jun 4, 2021
* Description: This document is created for
*/
package com.vocab85.icy.network;
/**
*
* @author jianqing
*/
public interface ProgressListener
{
public void onSuccess(int id);
public void onFailure(int id, Exception ex);
}
| 15.833333 | 48 | 0.673684 |
8c58fc2db1a415d11bffe38b1784c823943a795c
| 85,507 |
/***************************************
* Copyright (c) Intalio, Inc 2010
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************/
package com.intalio.bpmn2.impl;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.eclipse.bpmn2.Activity;
import org.eclipse.bpmn2.AdHocOrdering;
import org.eclipse.bpmn2.AdHocSubProcess;
import org.eclipse.bpmn2.Artifact;
import org.eclipse.bpmn2.Association;
import org.eclipse.bpmn2.BaseElement;
import org.eclipse.bpmn2.BoundaryEvent;
import org.eclipse.bpmn2.BusinessRuleTask;
import org.eclipse.bpmn2.CallActivity;
import org.eclipse.bpmn2.CallableElement;
import org.eclipse.bpmn2.CatchEvent;
import org.eclipse.bpmn2.Choreography;
import org.eclipse.bpmn2.Collaboration;
import org.eclipse.bpmn2.CompensateEventDefinition;
import org.eclipse.bpmn2.ComplexGateway;
import org.eclipse.bpmn2.ConditionalEventDefinition;
import org.eclipse.bpmn2.Conversation;
import org.eclipse.bpmn2.DataInput;
import org.eclipse.bpmn2.DataInputAssociation;
import org.eclipse.bpmn2.DataObject;
import org.eclipse.bpmn2.DataOutput;
import org.eclipse.bpmn2.DataOutputAssociation;
import org.eclipse.bpmn2.Definitions;
import org.eclipse.bpmn2.EndEvent;
import org.eclipse.bpmn2.Error;
import org.eclipse.bpmn2.ErrorEventDefinition;
import org.eclipse.bpmn2.Escalation;
import org.eclipse.bpmn2.EscalationEventDefinition;
import org.eclipse.bpmn2.Event;
import org.eclipse.bpmn2.EventBasedGateway;
import org.eclipse.bpmn2.EventDefinition;
import org.eclipse.bpmn2.ExclusiveGateway;
import org.eclipse.bpmn2.Expression;
import org.eclipse.bpmn2.ExtensionAttributeValue;
import org.eclipse.bpmn2.FlowElement;
import org.eclipse.bpmn2.FlowNode;
import org.eclipse.bpmn2.FormalExpression;
import org.eclipse.bpmn2.Gateway;
import org.eclipse.bpmn2.GlobalBusinessRuleTask;
import org.eclipse.bpmn2.GlobalChoreographyTask;
import org.eclipse.bpmn2.GlobalManualTask;
import org.eclipse.bpmn2.GlobalScriptTask;
import org.eclipse.bpmn2.GlobalTask;
import org.eclipse.bpmn2.GlobalUserTask;
import org.eclipse.bpmn2.Group;
import org.eclipse.bpmn2.InclusiveGateway;
import org.eclipse.bpmn2.InputSet;
import org.eclipse.bpmn2.Interface;
import org.eclipse.bpmn2.IntermediateCatchEvent;
import org.eclipse.bpmn2.IntermediateThrowEvent;
import org.eclipse.bpmn2.ItemDefinition;
import org.eclipse.bpmn2.Lane;
import org.eclipse.bpmn2.LaneSet;
import org.eclipse.bpmn2.ManualTask;
import org.eclipse.bpmn2.Message;
import org.eclipse.bpmn2.MessageEventDefinition;
import org.eclipse.bpmn2.Operation;
import org.eclipse.bpmn2.OutputSet;
import org.eclipse.bpmn2.ParallelGateway;
import org.eclipse.bpmn2.PotentialOwner;
import org.eclipse.bpmn2.Process;
import org.eclipse.bpmn2.Property;
import org.eclipse.bpmn2.ReceiveTask;
import org.eclipse.bpmn2.Resource;
import org.eclipse.bpmn2.ResourceRole;
import org.eclipse.bpmn2.RootElement;
import org.eclipse.bpmn2.ScriptTask;
import org.eclipse.bpmn2.SendTask;
import org.eclipse.bpmn2.SequenceFlow;
import org.eclipse.bpmn2.ServiceTask;
import org.eclipse.bpmn2.Signal;
import org.eclipse.bpmn2.SignalEventDefinition;
import org.eclipse.bpmn2.StartEvent;
import org.eclipse.bpmn2.SubProcess;
import org.eclipse.bpmn2.Task;
import org.eclipse.bpmn2.TerminateEventDefinition;
import org.eclipse.bpmn2.TextAnnotation;
import org.eclipse.bpmn2.ThrowEvent;
import org.eclipse.bpmn2.TimerEventDefinition;
import org.eclipse.bpmn2.UserTask;
import org.eclipse.bpmn2.di.BPMNDiagram;
import org.eclipse.bpmn2.di.BPMNEdge;
import org.eclipse.bpmn2.di.BPMNPlane;
import org.eclipse.bpmn2.di.BPMNShape;
import org.eclipse.dd.dc.Bounds;
import org.eclipse.dd.dc.Point;
import org.eclipse.dd.di.DiagramElement;
import org.eclipse.emf.ecore.util.FeatureMap;
import org.jbpm.bpmn2.emfextmodel.EmfextmodelPackage;
import org.jbpm.bpmn2.emfextmodel.GlobalType;
import org.jbpm.bpmn2.emfextmodel.ImportType;
import org.jbpm.bpmn2.emfextmodel.OnEntryScriptType;
import org.jbpm.bpmn2.emfextmodel.OnExitScriptType;
import com.intalio.web.profile.IDiagramProfile;
/**
* @author Antoine Toulme
* @author Tihomir Surdilovic
*
* a marshaller to transform BPMN 2.0 elements into JSON format.
*
*/
public class Bpmn2JsonMarshaller {
private Map<String, DiagramElement> _diagramElements = new HashMap<String, DiagramElement>();
private Map<String,Association> _diagramAssociations = new HashMap<String, Association>();
private static final Logger _logger = Logger.getLogger(Bpmn2JsonMarshaller.class);
private IDiagramProfile profile;
public void setProfile(IDiagramProfile profile) {
this.profile = profile;
}
public String marshall(Definitions def, String preProcessingData) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JsonFactory f = new JsonFactory();
JsonGenerator generator = f.createJsonGenerator(baos, JsonEncoding.UTF8);
marshallDefinitions(def, generator, preProcessingData);
generator.close();
return baos.toString("UTF-8");
}
private void linkSequenceFlows(List<FlowElement> flowElements) {
Map<String, FlowNode> nodes = new HashMap<String, FlowNode>();
for (FlowElement flowElement: flowElements) {
if (flowElement instanceof FlowNode) {
nodes.put(flowElement.getId(), (FlowNode) flowElement);
if (flowElement instanceof SubProcess) {
linkSequenceFlows(((SubProcess) flowElement).getFlowElements());
}
}
}
for (FlowElement flowElement: flowElements) {
if (flowElement instanceof SequenceFlow) {
SequenceFlow sequenceFlow = (SequenceFlow) flowElement;
if (sequenceFlow.getSourceRef() == null && sequenceFlow.getTargetRef() == null) {
String id = sequenceFlow.getId();
try {
String[] subids = id.split("-_");
String id1 = subids[0];
String id2 = "_" + subids[1];
FlowNode source = nodes.get(id1);
if (source != null) {
sequenceFlow.setSourceRef(source);
}
FlowNode target = nodes.get(id2);
if (target != null) {
sequenceFlow.setTargetRef(target);
}
} catch (Throwable t) {
// Do nothing
}
}
}
}
}
private void marshallDefinitions(Definitions def, JsonGenerator generator, String preProcessingData) throws JsonGenerationException, IOException {
try{
generator.writeStartObject();
generator.writeObjectField("resourceId", def.getId());
/**
* "properties":{"name":"",
* "documentation":"",
* "auditing":"",
* "monitoring":"",
* "executable":"true",
* "package":"com.sample",
* "vardefs":"a,b,c,d",
* "lanes" : "a,b,c",
* "id":"",
* "version":"",
* "author":"",
* "language":"",
* "namespaces":"",
* "targetnamespace":"",
* "expressionlanguage":"",
* "typelanguage":"",
* "creationdate":"",
* "modificationdate":""
* }
*/
Map<String, Object> props = new LinkedHashMap<String, Object>();
props.put("namespaces", "");
//props.put("targetnamespace", def.getTargetNamespace());
props.put("targetnamespace", "http://www.omg.org/bpmn20");
props.put("typelanguage", def.getTypeLanguage());
props.put("name",def.getName());
props.put("id", def.getId());
props.put("expressionlanguage", def.getExpressionLanguage());
if( def.getDocumentation() != null && def.getDocumentation().size() > 0 ) {
props.put("documentation", def.getDocumentation().get(0).getText());
}
for (RootElement rootElement : def.getRootElements()) {
if (rootElement instanceof Process) {
// have to wait for process node to finish properties and stencil marshalling
props.put("executable", ((Process) rootElement).isIsExecutable() + "");
props.put("id", ((Process) rootElement).getId());
props.put("name", ((Process) rootElement).getName());
List<Property> processProperties = ((Process) rootElement).getProperties();
if(processProperties != null && processProperties.size() > 0) {
String propVal = "";
for(int i=0; i<processProperties.size(); i++) {
Property p = processProperties.get(i);
propVal += p.getId();
// check the structureRef value
if(p.getItemSubjectRef() != null && p.getItemSubjectRef().getStructureRef() != null) {
propVal += ":" + p.getItemSubjectRef().getStructureRef();
}
if(i != processProperties.size()-1) {
propVal += ",";
}
}
props.put("vardefs", propVal);
}
// packageName and version are jbpm-specific extension attribute
Iterator<FeatureMap.Entry> iter = ((Process) rootElement).getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("packageName")) {
props.put("package", entry.getValue());
}
if(entry.getEStructuralFeature().getName().equals("version")) {
props.put("version", entry.getValue());
}
}
// process imports and globals extension elements
if(((Process) rootElement).getExtensionValues() != null && ((Process) rootElement).getExtensionValues().size() > 0) {
String importsStr = "";
String globalsStr = "";
for(ExtensionAttributeValue extattrval : ((Process) rootElement).getExtensionValues()) {
FeatureMap extensionElements = extattrval.getValue();
@SuppressWarnings("unchecked")
List<ImportType> importExtensions = (List<ImportType>) extensionElements
.get(EmfextmodelPackage.Literals.DOCUMENT_ROOT__IMPORT, true);
@SuppressWarnings("unchecked")
List<GlobalType> globalExtensions = (List<GlobalType>) extensionElements
.get(EmfextmodelPackage.Literals.DOCUMENT_ROOT__GLOBAL, true);
for(ImportType importType : importExtensions) {
importsStr += importType.getName();
importsStr += ",";
}
for(GlobalType globalType : globalExtensions) {
globalsStr += (globalType.getIdentifier() + ":" + globalType.getType());
globalsStr += ",";
}
}
if(importsStr.length() > 0) {
if(importsStr.endsWith(",")) {
importsStr = importsStr.substring(0, importsStr.length() - 1);
}
props.put("imports", importsStr);
}
if(globalsStr.length() > 0) {
if(globalsStr.endsWith(",")) {
globalsStr = globalsStr.substring(0, globalsStr.length() - 1);
}
props.put("globals", globalsStr);
}
}
marshallProperties(props, generator);
marshallStencil("BPMNDiagram", generator);
linkSequenceFlows(((Process) rootElement).getFlowElements());
marshallProcess((Process) rootElement, def, generator, preProcessingData);
} else if (rootElement instanceof Interface) {
// TODO
} else if (rootElement instanceof ItemDefinition) {
// TODO
} else if (rootElement instanceof Resource) {
// TODO
} else if (rootElement instanceof Error) {
// TODO
} else if (rootElement instanceof Message) {
// TODO
} else if (rootElement instanceof Signal) {
// TODO
} else if (rootElement instanceof Escalation) {
// TODO
} else if (rootElement instanceof Collaboration) {
} else {
_logger.warn("Unknown root element " + rootElement + ". This element will not be parsed.");
}
}
generator.writeObjectFieldStart("stencilset");
generator.writeObjectField("url", this.profile.getStencilSetURL());
generator.writeObjectField("namespace", this.profile.getStencilSetNamespaceURL());
generator.writeEndObject();
generator.writeArrayFieldStart("ssextensions");
generator.writeObject(this.profile.getStencilSetExtensionURL());
generator.writeEndArray();
generator.writeEndObject();
} finally {
_diagramElements.clear();
}
}
/** private void marshallMessage(Message message, Definitions def, JsonGenerator generator) throws JsonGenerationException, IOException {
Map<String, Object> properties = new LinkedHashMap<String, Object>();
generator.writeStartObject();
generator.writeObjectField("resourceId", message.getId());
properties.put("name", message.getName());
if(message.getDocumentation() != null && message.getDocumentation().size() > 0) {
properties.put("documentation", message.getDocumentation().get(0).getText());
}
marshallProperties(properties, generator);
generator.writeObjectFieldStart("stencil");
generator.writeObjectField("id", "Message");
generator.writeEndObject();
generator.writeArrayFieldStart("childShapes");
generator.writeEndArray();
generator.writeArrayFieldStart("outgoing");
generator.writeEndArray();
generator.writeEndObject();
} **/
private void marshallCallableElement(CallableElement callableElement, Definitions def, JsonGenerator generator) throws JsonGenerationException, IOException {
generator.writeStartObject();
generator.writeObjectField("resourceId", callableElement.getId());
if (callableElement instanceof Choreography) {
marshallChoreography((Choreography) callableElement, generator);
} else if (callableElement instanceof Conversation) {
marshallConversation((Conversation) callableElement, generator);
} else if (callableElement instanceof GlobalChoreographyTask) {
marshallGlobalChoreographyTask((GlobalChoreographyTask) callableElement, generator);
} else if (callableElement instanceof GlobalTask) {
marshallGlobalTask((GlobalTask) callableElement, generator);
} else if (callableElement instanceof Process) {
marshallProcess((Process) callableElement, def, generator, "");
} else {
throw new UnsupportedOperationException("TODO"); //TODO!
}
generator.writeEndObject();
}
private void marshallProcess(Process process, Definitions def, JsonGenerator generator, String preProcessingData) throws JsonGenerationException, IOException {
BPMNPlane plane = null;
for (BPMNDiagram d: def.getDiagrams()) {
if (d != null) {
BPMNPlane p = d.getPlane();
if (p != null) {
if (p.getBpmnElement() == process) {
plane = p;
break;
}
}
}
}
if (plane == null) {
throw new IllegalArgumentException("Could not find BPMNDI information");
}
generator.writeArrayFieldStart("childShapes");
List<String> laneFlowElementsIds = new ArrayList<String>();
for(LaneSet laneSet : process.getLaneSets()) {
for(Lane lane : laneSet.getLanes()) {
// we only want to marshall lanes if we have the bpmndi info for them!
if(findDiagramElement(plane, lane) != null) {
laneFlowElementsIds.addAll( marshallLanes(lane, plane, generator, 0, 0, preProcessingData, def) );
}
}
}
for (FlowElement flowElement: process.getFlowElements()) {
if( !laneFlowElementsIds.contains(flowElement.getId()) ) {
marshallFlowElement(flowElement, plane, generator, 0, 0, preProcessingData, def);
}
}
for (Artifact artifact: process.getArtifacts()) {
marshallArtifact(artifact, plane, generator, 0, 0, preProcessingData, def);
}
generator.writeEndArray();
}
private void setCatchEventProperties(CatchEvent event, Map<String, Object> properties) {
if(event.getOutputSet() != null) {
List<DataOutput> dataOutputs = event.getOutputSet().getDataOutputRefs();
StringBuffer doutbuff = new StringBuffer();
for(DataOutput dout : dataOutputs) {
doutbuff.append(dout.getName());
doutbuff.append(",");
}
if(doutbuff.length() > 0) {
doutbuff.setLength(doutbuff.length() - 1);
}
properties.put("dataoutput", doutbuff.toString());
List<DataOutputAssociation> outputAssociations = event.getDataOutputAssociation();
StringBuffer doutassociationbuff = new StringBuffer();
for(DataOutputAssociation doa : outputAssociations) {
doutassociationbuff.append(((DataOutput)doa.getSourceRef().get(0)).getName());
doutassociationbuff.append("->");
doutassociationbuff.append(doa.getTargetRef().getId());
doutassociationbuff.append(",");
}
if(doutassociationbuff.length() > 0) {
doutassociationbuff.setLength(doutassociationbuff.length() - 1);
}
properties.put("dataoutputassociations", doutassociationbuff.toString());
}
// event definitions
List<EventDefinition> eventdefs = event.getEventDefinitions();
for(EventDefinition ed : eventdefs) {
if(ed instanceof TimerEventDefinition) {
TimerEventDefinition ted = (TimerEventDefinition) ed;
if(ted.getTimeDate() != null) {
properties.put("timedate", ((FormalExpression) ted.getTimeDate()).getBody());
}
if(ted.getTimeDuration() != null) {
properties.put("timeduration", ((FormalExpression) ted.getTimeDuration()).getBody());
}
if(ted.getTimeCycle() != null) {
properties.put("timecycle", ((FormalExpression) ted.getTimeCycle()).getBody());
}
} else if( ed instanceof SignalEventDefinition) {
if(((SignalEventDefinition) ed).getSignalRef() != null && ((SignalEventDefinition) ed).getSignalRef().getName() != null) {
properties.put("signalref", ((SignalEventDefinition) ed).getSignalRef().getName());
} else {
properties.put("signalref", "");
}
} else if( ed instanceof ErrorEventDefinition) {
if(((ErrorEventDefinition) ed).getErrorRef() != null && ((ErrorEventDefinition) ed).getErrorRef().getErrorCode() != null) {
properties.put("errorref", ((ErrorEventDefinition) ed).getErrorRef().getErrorCode());
} else {
properties.put("errorref", "");
}
} else if( ed instanceof ConditionalEventDefinition ) {
FormalExpression conditionalExp = (FormalExpression) ((ConditionalEventDefinition) ed).getCondition();
if(conditionalExp.getBody() != null) {
properties.put("conditionexpression", conditionalExp.getBody());
}
if(conditionalExp.getLanguage() != null) {
String languageVal = conditionalExp.getLanguage();
if(languageVal.equals("http://www.jboss.org/drools/rule")) {
properties.put("conditionlanguage", "drools");
} else if(languageVal.equals("http://www.mvel.org/2.0")) {
properties.put("conditionlanguage", "mvel");
} else {
// default to drools
properties.put("conditionlanguage", "drools");
}
}
} else if( ed instanceof EscalationEventDefinition ) {
if(((EscalationEventDefinition) ed).getEscalationRef() != null) {
Escalation esc = ((EscalationEventDefinition) ed).getEscalationRef();
if(esc.getEscalationCode() != null && esc.getEscalationCode().length() > 0) {
properties.put("escalationcode", esc.getEscalationCode());
} else {
properties.put("escalationcode", "");
}
}
} else if( ed instanceof MessageEventDefinition) {
if(((MessageEventDefinition) ed).getMessageRef() != null) {
Message msg = ((MessageEventDefinition) ed).getMessageRef();
properties.put("messageref", msg.getId());
}
} else if( ed instanceof CompensateEventDefinition) {
if(((CompensateEventDefinition) ed).getActivityRef() != null) {
Activity act = ((CompensateEventDefinition) ed).getActivityRef();
properties.put("activityref", act.getName());
}
}
}
}
private void setThrowEventProperties(ThrowEvent event, Map<String, Object> properties) {
if(event.getInputSet() != null) {
List<DataInput> dataInputs = event.getInputSet().getDataInputRefs();
StringBuffer dinbuff = new StringBuffer();
for(DataInput din : dataInputs) {
dinbuff.append(din.getName());
dinbuff.append(",");
}
if(dinbuff.length() > 0) {
dinbuff.setLength(dinbuff.length() - 1);
}
properties.put("datainput", dinbuff.toString());
List<DataInputAssociation> inputAssociations = event.getDataInputAssociation();
StringBuffer dinassociationbuff = new StringBuffer();
for(DataInputAssociation din : inputAssociations) {
dinassociationbuff.append(din.getSourceRef().get(0).getId());
dinassociationbuff.append("->");
dinassociationbuff.append( ((DataInput)din.getTargetRef()).getName());
dinassociationbuff.append(",");
}
if(dinassociationbuff.length() > 0) {
dinassociationbuff.setLength(dinassociationbuff.length() - 1);
}
properties.put("datainputassociations", dinassociationbuff.toString());
}
// event definitions
List<EventDefinition> eventdefs = event.getEventDefinitions();
for(EventDefinition ed : eventdefs) {
if(ed instanceof TimerEventDefinition) {
TimerEventDefinition ted = (TimerEventDefinition) ed;
if(ted.getTimeDate() != null) {
properties.put("timedate", ((FormalExpression) ted.getTimeDate()).getBody());
}
if(ted.getTimeDuration() != null) {
properties.put("timeduration", ((FormalExpression) ted.getTimeDuration()).getBody());
}
if(ted.getTimeCycle() != null) {
properties.put("timecycle", ((FormalExpression) ted.getTimeCycle()).getBody());
}
} else if( ed instanceof SignalEventDefinition) {
if(((SignalEventDefinition) ed).getSignalRef() != null && ((SignalEventDefinition) ed).getSignalRef().getName() != null) {
properties.put("signalref", ((SignalEventDefinition) ed).getSignalRef().getName());
} else {
properties.put("signalref", "");
}
} else if( ed instanceof ErrorEventDefinition) {
if(((ErrorEventDefinition) ed).getErrorRef() != null && ((ErrorEventDefinition) ed).getErrorRef().getErrorCode() != null) {
properties.put("errorref", ((ErrorEventDefinition) ed).getErrorRef().getErrorCode());
} else {
properties.put("errorref", "");
}
} else if( ed instanceof ConditionalEventDefinition ) {
FormalExpression conditionalExp = (FormalExpression) ((ConditionalEventDefinition) ed).getCondition();
if(conditionalExp.getBody() != null) {
properties.put("conditionexpression", conditionalExp.getBody());
}
if(conditionalExp.getLanguage() != null) {
String languageVal = conditionalExp.getLanguage();
if(languageVal.equals("http://www.jboss.org/drools/rule")) {
properties.put("conditionlanguage", "drools");
} else if(languageVal.equals("http://www.mvel.org/2.0")) {
properties.put("conditionlanguage", "mvel");
} else {
// default to drools
properties.put("conditionlanguage", "drools");
}
}
} else if( ed instanceof EscalationEventDefinition ) {
if(((EscalationEventDefinition) ed).getEscalationRef() != null) {
Escalation esc = ((EscalationEventDefinition) ed).getEscalationRef();
if(esc.getEscalationCode() != null && esc.getEscalationCode().length() > 0) {
properties.put("escalationcode", esc.getEscalationCode());
} else {
properties.put("escalationcode", "");
}
}
} else if( ed instanceof MessageEventDefinition) {
if(((MessageEventDefinition) ed).getMessageRef() != null) {
Message msg = ((MessageEventDefinition) ed).getMessageRef();
properties.put("messageref", msg.getId());
}
} else if( ed instanceof CompensateEventDefinition) {
if(((CompensateEventDefinition) ed).getActivityRef() != null) {
Activity act = ((CompensateEventDefinition) ed).getActivityRef();
properties.put("activityref", act.getName());
}
}
}
}
private List<String> marshallLanes(Lane lane, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, String preProcessingData, Definitions def) throws JsonGenerationException, IOException {
List<String> nodeRefIds = new ArrayList<String>();
generator.writeStartObject();
generator.writeObjectField("resourceId", lane.getId());
Map<String, Object> laneProperties = new LinkedHashMap<String, Object>();
laneProperties.put("name", lane.getName());
marshallProperties(laneProperties, generator);
generator.writeObjectFieldStart("stencil");
generator.writeObjectField("id", "Lane");
generator.writeEndObject();
generator.writeArrayFieldStart("childShapes");
Bounds bounds = ((BPMNShape) findDiagramElement(plane, lane)).getBounds();
for (FlowElement flowElement: lane.getFlowNodeRefs()) {
nodeRefIds.add(flowElement.getId());
// we dont want an offset here!
marshallFlowElement(flowElement, plane, generator, 0, 0, preProcessingData, def);
}
generator.writeEndArray();
generator.writeArrayFieldStart("outgoing");
generator.writeEndArray();
generator.writeObjectFieldStart("bounds");
generator.writeObjectFieldStart("lowerRight");
generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset);
generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset);
generator.writeEndObject();
generator.writeObjectFieldStart("upperLeft");
generator.writeObjectField("x", bounds.getX() - xOffset);
generator.writeObjectField("y", bounds.getY() - yOffset);
generator.writeEndObject();
generator.writeEndObject();
generator.writeEndObject();
return nodeRefIds;
}
private void marshallFlowElement(FlowElement flowElement, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, String preProcessingData, Definitions def) throws JsonGenerationException, IOException {
generator.writeStartObject();
generator.writeObjectField("resourceId", flowElement.getId());
Map<String, Object> flowElementProperties = new LinkedHashMap<String, Object>();
Iterator<FeatureMap.Entry> iter = flowElement.getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("bgcolor")) {
flowElementProperties.put("bgcolor", entry.getValue());
}
}
Map<String, Object> catchEventProperties = new LinkedHashMap<String, Object>(flowElementProperties);
Map<String, Object> throwEventProperties = new LinkedHashMap<String, Object>(flowElementProperties);
if(flowElement instanceof CatchEvent) {
setCatchEventProperties((CatchEvent) flowElement, catchEventProperties);
}
if(flowElement instanceof ThrowEvent) {
setThrowEventProperties((ThrowEvent) flowElement, throwEventProperties);
}
if (flowElement instanceof StartEvent) {
marshallStartEvent((StartEvent) flowElement, plane, generator, xOffset, yOffset, catchEventProperties);
} else if (flowElement instanceof EndEvent) {
marshallEndEvent((EndEvent) flowElement, plane, generator, xOffset, yOffset, throwEventProperties);
} else if (flowElement instanceof IntermediateThrowEvent) {
marshallIntermediateThrowEvent((IntermediateThrowEvent) flowElement, plane, generator, xOffset, yOffset, throwEventProperties);
} else if (flowElement instanceof IntermediateCatchEvent) {
marshallIntermediateCatchEvent((IntermediateCatchEvent) flowElement, plane, generator, xOffset, yOffset, catchEventProperties);
} else if (flowElement instanceof BoundaryEvent) {
marshallBoundaryEvent((BoundaryEvent) flowElement, plane, generator, xOffset, yOffset, catchEventProperties);
} else if (flowElement instanceof Task) {
marshallTask((Task) flowElement, plane, generator, xOffset, yOffset, preProcessingData, def, flowElementProperties);
} else if (flowElement instanceof SequenceFlow) {
marshallSequenceFlow((SequenceFlow) flowElement, plane, generator, xOffset, yOffset);
} else if (flowElement instanceof ParallelGateway) {
marshallParallelGateway((ParallelGateway) flowElement, plane, generator, xOffset, yOffset, flowElementProperties);
} else if (flowElement instanceof ExclusiveGateway) {
marshallExclusiveGateway((ExclusiveGateway) flowElement, plane, generator, xOffset, yOffset, flowElementProperties);
} else if (flowElement instanceof InclusiveGateway) {
marshallInclusiveGateway((InclusiveGateway) flowElement, plane, generator, xOffset, yOffset, flowElementProperties);
} else if (flowElement instanceof EventBasedGateway) {
marshallEventBasedGateway((EventBasedGateway) flowElement, plane, generator, xOffset, yOffset, flowElementProperties);
} else if (flowElement instanceof ComplexGateway) {
marshallComplexGateway((ComplexGateway) flowElement, plane, generator, xOffset, yOffset, flowElementProperties);
} else if (flowElement instanceof CallActivity) {
marshallCallActivity((CallActivity) flowElement, plane, generator, xOffset, yOffset, flowElementProperties);
} else if (flowElement instanceof SubProcess) {
if(flowElement instanceof AdHocSubProcess) {
marshallSubProcess((AdHocSubProcess) flowElement, plane, generator, xOffset, yOffset, preProcessingData, def, flowElementProperties);
} else {
marshallSubProcess((SubProcess) flowElement, plane, generator, xOffset, yOffset, preProcessingData, def, flowElementProperties);
}
} else if (flowElement instanceof DataObject) {
marshallDataObject((DataObject) flowElement, plane, generator, xOffset, yOffset, flowElementProperties);
} else {
throw new UnsupportedOperationException("Unknown flow element " + flowElement);
}
generator.writeEndObject();
}
private void marshallStartEvent(StartEvent startEvent, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, Map<String, Object> properties) throws JsonGenerationException, IOException {
List<EventDefinition> eventDefinitions = startEvent.getEventDefinitions();
if (eventDefinitions == null || eventDefinitions.size() == 0) {
marshallNode(startEvent, properties, "StartNoneEvent", plane, generator, xOffset, yOffset);
} else if (eventDefinitions.size() == 1) {
EventDefinition eventDefinition = eventDefinitions.get(0);
if (eventDefinition instanceof ConditionalEventDefinition) {
marshallNode(startEvent, properties, "StartConditionalEvent", plane, generator, xOffset, yOffset);
} else if (eventDefinition instanceof SignalEventDefinition) {
marshallNode(startEvent, properties, "StartSignalEvent", plane, generator, xOffset, yOffset);
} else if (eventDefinition instanceof MessageEventDefinition) {
marshallNode(startEvent, properties, "StartMessageEvent", plane, generator, xOffset, yOffset);
} else if (eventDefinition instanceof TimerEventDefinition) {
marshallNode(startEvent, properties, "StartTimerEvent", plane, generator, xOffset, yOffset);
} else if (eventDefinition instanceof ErrorEventDefinition) {
marshallNode(startEvent, properties, "StartErrorEvent", plane, generator, xOffset, yOffset);
} else if(eventDefinition instanceof ConditionalEventDefinition) {
marshallNode(startEvent, properties, "StartConditionalEvent", plane, generator, xOffset, yOffset);
} else if(eventDefinition instanceof EscalationEventDefinition) {
marshallNode(startEvent, properties, "StartEscalationEvent", plane, generator, xOffset, yOffset);
} else if(eventDefinition instanceof CompensateEventDefinition) {
marshallNode(startEvent, properties, "StartCompensationEvent", plane, generator, xOffset, yOffset);
}
else {
throw new UnsupportedOperationException("Event definition not supported: " + eventDefinition);
}
} else {
throw new UnsupportedOperationException("Multiple event definitions not supported for start event");
}
}
private void marshallEndEvent(EndEvent endEvent, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, Map<String, Object> properties) throws JsonGenerationException, IOException {
List<EventDefinition> eventDefinitions = endEvent.getEventDefinitions();
if (eventDefinitions == null || eventDefinitions.size() == 0) {
marshallNode(endEvent, properties, "EndNoneEvent", plane, generator, xOffset, yOffset);
} else if (eventDefinitions.size() == 1) {
EventDefinition eventDefinition = eventDefinitions.get(0);
if (eventDefinition instanceof TerminateEventDefinition) {
marshallNode(endEvent, properties, "EndTerminateEvent", plane, generator, xOffset, yOffset);
} else if (eventDefinition instanceof SignalEventDefinition) {
marshallNode(endEvent, properties, "EndSignalEvent", plane, generator, xOffset, yOffset);
} else if (eventDefinition instanceof MessageEventDefinition) {
marshallNode(endEvent, properties, "EndMessageEvent", plane, generator, xOffset, yOffset);
} else if (eventDefinition instanceof ErrorEventDefinition) {
marshallNode(endEvent, properties, "EndErrorEvent", plane, generator, xOffset, yOffset);
} else if (eventDefinition instanceof EscalationEventDefinition) {
marshallNode(endEvent, properties, "EndEscalationEvent", plane, generator, xOffset, yOffset);
} else if (eventDefinition instanceof CompensateEventDefinition) {
marshallNode(endEvent, properties, "EndCompensationEvent", plane, generator, xOffset, yOffset);
} else {
throw new UnsupportedOperationException("Event definition not supported: " + eventDefinition);
}
} else {
throw new UnsupportedOperationException("Multiple event definitions not supported for end event");
}
}
private void marshallIntermediateCatchEvent(IntermediateCatchEvent catchEvent, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, Map<String, Object> properties) throws JsonGenerationException, IOException {
List<EventDefinition> eventDefinitions = catchEvent.getEventDefinitions();
if (eventDefinitions.size() == 1) {
EventDefinition eventDefinition = eventDefinitions.get(0);
if (eventDefinition instanceof SignalEventDefinition) {
marshallNode(catchEvent, properties, "IntermediateSignalEventCatching", plane, generator, xOffset, yOffset);
} else if (eventDefinition instanceof MessageEventDefinition) {
marshallNode(catchEvent, properties, "IntermediateMessageEventCatching", plane, generator, xOffset, yOffset);
} else if (eventDefinition instanceof TimerEventDefinition) {
marshallNode(catchEvent, properties, "IntermediateTimerEvent", plane, generator, xOffset, yOffset);
} else if (eventDefinition instanceof ConditionalEventDefinition) {
marshallNode(catchEvent, properties, "IntermediateConditionalEvent", plane, generator, xOffset, yOffset);
} else if(eventDefinition instanceof ErrorEventDefinition) {
marshallNode(catchEvent, properties, "IntermediateErrorEvent", plane, generator, xOffset, yOffset);
} else if(eventDefinition instanceof EscalationEventDefinition) {
marshallNode(catchEvent, properties, "IntermediateEscalationEvent", plane, generator, xOffset, yOffset);
} else if(eventDefinition instanceof CompensateEventDefinition) {
marshallNode(catchEvent, properties, "IntermediateCompensationEventCatching", plane, generator, xOffset, yOffset);
}
else {
throw new UnsupportedOperationException("Event definition not supported: " + eventDefinition);
}
} else {
throw new UnsupportedOperationException("None or multiple event definitions not supported for intermediate catch event");
}
}
private void marshallBoundaryEvent(BoundaryEvent boundaryEvent, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, Map<String, Object> catchEventProperties) throws JsonGenerationException, IOException {
List<EventDefinition> eventDefinitions = boundaryEvent.getEventDefinitions();
if (eventDefinitions.size() == 1) {
EventDefinition eventDefinition = eventDefinitions.get(0);
if (eventDefinition instanceof EscalationEventDefinition) {
marshallNode(boundaryEvent, catchEventProperties, "IntermediateEscalationEvent", plane, generator, xOffset, yOffset);
} else if (eventDefinition instanceof ErrorEventDefinition) {
marshallNode(boundaryEvent, catchEventProperties, "IntermediateErrorEvent", plane, generator, xOffset, yOffset);
} else if (eventDefinition instanceof TimerEventDefinition) {
marshallNode(boundaryEvent, catchEventProperties, "IntermediateTimerEvent", plane, generator, xOffset, yOffset);
} else if (eventDefinition instanceof CompensateEventDefinition) {
marshallNode(boundaryEvent, catchEventProperties, "IntermediateCompensationEventCatching", plane, generator, xOffset, yOffset);
} else if(eventDefinition instanceof ConditionalEventDefinition) {
marshallNode(boundaryEvent, catchEventProperties, "IntermediateConditionalEvent", plane, generator, xOffset, yOffset);
} else if(eventDefinition instanceof MessageEventDefinition) {
marshallNode(boundaryEvent, catchEventProperties, "IntermediateMessageEventCatching", plane, generator, xOffset, yOffset);
}else {
throw new UnsupportedOperationException("Event definition not supported: " + eventDefinition);
}
} else {
throw new UnsupportedOperationException("None or multiple event definitions not supported for boundary event");
}
}
private void marshallIntermediateThrowEvent(IntermediateThrowEvent throwEvent, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, Map<String, Object> properties) throws JsonGenerationException, IOException {
List<EventDefinition> eventDefinitions = throwEvent.getEventDefinitions();
if (eventDefinitions.size() == 0) {
marshallNode(throwEvent, properties, "IntermediateEventThrowing", plane, generator, xOffset, yOffset);
} else if (eventDefinitions.size() == 1) {
EventDefinition eventDefinition = eventDefinitions.get(0);
if (eventDefinition instanceof SignalEventDefinition) {
marshallNode(throwEvent, properties, "IntermediateSignalEventThrowing", plane, generator, xOffset, yOffset);
} else if (eventDefinition instanceof MessageEventDefinition) {
marshallNode(throwEvent, properties, "IntermediateMessageEventThrowing", plane, generator, xOffset, yOffset);
} else if (eventDefinition instanceof EscalationEventDefinition) {
marshallNode(throwEvent, properties, "IntermediateEscalationEventThrowing", plane, generator, xOffset, yOffset);
} else if (eventDefinition instanceof CompensateEventDefinition) {
marshallNode(throwEvent, properties, "IntermediateCompensationEventThrowing", plane, generator, xOffset, yOffset);
} else {
throw new UnsupportedOperationException("Event definition not supported: " + eventDefinition);
}
} else {
throw new UnsupportedOperationException("None or multiple event definitions not supported for intermediate throw event");
}
}
private void marshallTask(Task task, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, String preProcessingData, Definitions def, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException {
Map<String, Object> properties = new LinkedHashMap<String, Object>(flowElementProperties);
String taskType = "None";
if (task instanceof BusinessRuleTask) {
taskType = "Business Rule";
Iterator<FeatureMap.Entry> iter = task.getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("ruleFlowGroup")) {
properties.put("ruleflowgroup", entry.getValue());
}
}
} else if (task instanceof ScriptTask) {
ScriptTask scriptTask = (ScriptTask) task;
properties.put("script", scriptTask.getScript());
properties.put("script_language", scriptTask.getScriptFormat());
taskType = "Script";
} else if (task instanceof ServiceTask) {
taskType = "Service";
ServiceTask serviceTask = (ServiceTask) task;
if(serviceTask.getOperationRef() != null) {
Operation oper = serviceTask.getOperationRef();
if(oper.getName() != null) {
properties.put("operation", oper.getName());
}
if(def != null) {
List<RootElement> roots = def.getRootElements();
for(RootElement root : roots) {
if(root instanceof Interface) {
Interface inter = (Interface) root;
List<Operation> interOperations = inter.getOperations();
for(Operation interOper : interOperations) {
if(interOper.getId().equals(oper.getId())) {
properties.put("interface", inter.getName());
}
}
}
}
}
}
} else if (task instanceof ManualTask) {
taskType = "Manual";
} else if (task instanceof UserTask) {
taskType = "User";
// get the user task actors
List<ResourceRole> roles = task.getResources();
StringBuilder sb = new StringBuilder();
for(ResourceRole role : roles) {
if(role instanceof PotentialOwner) {
FormalExpression fe = (FormalExpression) ( (PotentialOwner)role).getResourceAssignmentExpression().getExpression();
if(fe.getBody() != null && fe.getBody().length() > 0) {
sb.append(fe.getBody());
sb.append(",");
}
}
}
if(sb.length() > 0) {
sb.setLength(sb.length() - 1);
}
properties.put("actors", sb.toString());
Iterator<FeatureMap.Entry> iter = task.getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("onEntry-script")) {
properties.put("onentryactions", entry.getValue());
} else if(entry.getEStructuralFeature().getName().equals("onExit-script")) {
properties.put("onexitactions", entry.getValue());
} else if(entry.getEStructuralFeature().getName().equals("scriptFormat")) {
String format = (String) entry.getValue();
String formatToWrite = "";
if(format.equals("http://www.java.com/java")) {
formatToWrite = "java";
} else if(format.equals("http://www.mvel.org/2.0")) {
formatToWrite = "mvel";
} else {
formatToWrite = "java";
}
properties.put("script_language", formatToWrite);
}
}
} else if (task instanceof SendTask) {
taskType = "Send";
} else if (task instanceof ReceiveTask) {
taskType = "Receive";
}
// get out the droolsjbpm-specific attributes "ruleflowGroup" and "taskName"
Iterator<FeatureMap.Entry> iter = task.getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("taskName")) {
properties.put("taskname", entry.getValue());
}
}
// check if we are dealing with a custom task
if(isCustomElement((String) properties.get("taskname"), preProcessingData)) {
properties.put("tasktype", properties.get("taskname"));
} else {
properties.put("tasktype", taskType);
}
// data inputs
if(task.getIoSpecification() != null) {
List<InputSet> inputSetList = task.getIoSpecification().getInputSets();
StringBuilder dataInBuffer = new StringBuilder();
for(InputSet inset : inputSetList) {
List<DataInput> dataInputList = inset.getDataInputRefs();
for(DataInput dataIn : dataInputList) {
// dont add "TaskName" as that is added manually
if(dataIn.getName() != null && !dataIn.getName().equals("TaskName")) {
dataInBuffer.append(dataIn.getName());
dataInBuffer.append(",");
}
}
}
if(dataInBuffer.length() > 0) {
dataInBuffer.setLength(dataInBuffer.length() - 1);
}
properties.put("datainputset", dataInBuffer.toString());
}
// data outputs
if(task.getIoSpecification() != null) {
List<OutputSet> outputSetList = task.getIoSpecification().getOutputSets();
StringBuilder dataOutBuffer = new StringBuilder();
for(OutputSet outset : outputSetList) {
List<DataOutput> dataOutputList = outset.getDataOutputRefs();
for(DataOutput dataOut : dataOutputList) {
dataOutBuffer.append(dataOut.getName());
dataOutBuffer.append(",");
}
}
if(dataOutBuffer.length() > 0) {
dataOutBuffer.setLength(dataOutBuffer.length() - 1);
}
properties.put("dataoutputset", dataOutBuffer.toString());
}
// assignments
StringBuilder associationBuff = new StringBuilder();
List<DataInputAssociation> inputAssociations = task.getDataInputAssociations();
List<DataOutputAssociation> outputAssociations = task.getDataOutputAssociations();
List<String> uniDirectionalAssociations = new ArrayList<String>();
List<String> biDirectionalAssociations = new ArrayList<String>();
for(DataInputAssociation datain : inputAssociations) {
String lhsAssociation = "";
if(datain.getSourceRef() != null && datain.getSourceRef().size() > 0) {
if(datain.getTransformation() != null && datain.getTransformation().getBody() != null) {
lhsAssociation = datain.getTransformation().getBody();
} else {
lhsAssociation = datain.getSourceRef().get(0).getId();
}
}
String rhsAssociation = "";
if(datain.getTargetRef() != null) {
rhsAssociation = ((DataInput) datain.getTargetRef()).getName();
}
boolean isBiDirectional = false;
boolean isAssignment = false;
if(datain.getAssignment() != null && datain.getAssignment().size() > 0) {
isAssignment = true;
} else {
// check if this is a bi-directional association
for(DataOutputAssociation dataout : outputAssociations) {
if(dataout.getTargetRef().getId().equals(lhsAssociation) &&
((DataOutput) dataout.getSourceRef().get(0)).getName().equals(rhsAssociation)) {
isBiDirectional = true;
break;
}
}
}
if(isAssignment) {
// only know how to deal with formal expressions
if( datain.getAssignment().get(0).getFrom() instanceof FormalExpression) {
String associationValue = ((FormalExpression) datain.getAssignment().get(0).getFrom()).getBody();
if(associationValue == null) {
associationValue = "";
}
associationBuff.append(rhsAssociation).append("=").append(associationValue);
associationBuff.append(",");
}
} else if(isBiDirectional) {
associationBuff.append(lhsAssociation).append("<->").append(rhsAssociation);
associationBuff.append(",");
biDirectionalAssociations.add(lhsAssociation + "," + rhsAssociation);
} else {
associationBuff.append(lhsAssociation).append("->").append(rhsAssociation);
associationBuff.append(",");
uniDirectionalAssociations.add(lhsAssociation + "," + rhsAssociation);
}
}
for(DataOutputAssociation dataout : outputAssociations) {
if(dataout.getSourceRef().size() > 0) {
String lhsAssociation = ((DataOutput) dataout.getSourceRef().get(0)).getName();
String rhsAssociation = dataout.getTargetRef().getId();
boolean wasBiDirectional = false;
// check if we already addressed this association as bidirectional
for(String bda : biDirectionalAssociations) {
String[] dbaparts = bda.split( ",\\s*" );
if(dbaparts[0].equals(rhsAssociation) && dbaparts[1].equals(lhsAssociation)) {
wasBiDirectional = true;
break;
}
}
if(dataout.getTransformation() != null && dataout.getTransformation().getBody() != null) {
rhsAssociation = dataout.getTransformation().getBody();
}
if(!wasBiDirectional) {
associationBuff.append(lhsAssociation).append("->").append(rhsAssociation);
associationBuff.append(",");
}
}
}
String assignmentString = associationBuff.toString();
if(assignmentString.endsWith(",")) {
assignmentString = assignmentString.substring(0, assignmentString.length() - 1);
}
properties.put("assignments", assignmentString);
// on-entry and on-exit actions
if(task.getExtensionValues() != null && task.getExtensionValues().size() > 0) {
String onEntryStr = "";
String onExitStr = "";
for(ExtensionAttributeValue extattrval : task.getExtensionValues()) {
FeatureMap extensionElements = extattrval.getValue();
@SuppressWarnings("unchecked")
List<OnEntryScriptType> onEntryExtensions = (List<OnEntryScriptType>) extensionElements
.get(EmfextmodelPackage.Literals.DOCUMENT_ROOT__ON_ENTRY_SCRIPT, true);
@SuppressWarnings("unchecked")
List<OnExitScriptType> onExitExtensions = (List<OnExitScriptType>) extensionElements
.get(EmfextmodelPackage.Literals.DOCUMENT_ROOT__ON_EXIT_SCRIPT, true);
for(OnEntryScriptType onEntryScript : onEntryExtensions) {
onEntryStr += onEntryScript.getScript();
onEntryStr += ",";
if(onEntryScript.getScriptFormat() != null) {
String format = onEntryScript.getScriptFormat();
String formatToWrite = "";
if(format.equals("http://www.java.com/java")) {
formatToWrite = "java";
} else if(format.equals("http://www.mvel.org/2.0")) {
formatToWrite = "mvel";
} else {
formatToWrite = "java";
}
properties.put("script_language", formatToWrite);
}
}
for(OnExitScriptType onExitScript : onExitExtensions) {
onExitStr += onExitScript.getScript();
onExitStr += ",";
if(onExitScript.getScriptFormat() != null) {
String format = onExitScript.getScriptFormat();
String formatToWrite = "";
if(format.equals("http://www.java.com/java")) {
formatToWrite = "java";
} else if(format.equals("http://www.mvel.org/2.0")) {
formatToWrite = "mvel";
} else {
formatToWrite = "java";
}
if(properties.get("script_language") != null) {
properties.put("script_language", formatToWrite);
}
}
}
}
if(onEntryStr.length() > 0) {
if(onEntryStr.endsWith(",")) {
onEntryStr = onEntryStr.substring(0, onEntryStr.length() - 1);
}
properties.put("onentryactions", onEntryStr);
}
if(onExitStr.length() > 0) {
if(onExitStr.endsWith(",")) {
onExitStr = onExitStr.substring(0, onExitStr.length() - 1);
}
properties.put("onexitactions", onExitStr);
}
}
// marshall the node out
if(isCustomElement((String) properties.get("taskname"), preProcessingData)) {
marshallNode(task, properties, (String) properties.get("taskname"), plane, generator, xOffset, yOffset);
} else {
marshallNode(task, properties, "Task", plane, generator, xOffset, yOffset);
}
}
private void marshallParallelGateway(ParallelGateway gateway, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException {
marshallNode(gateway, flowElementProperties, "ParallelGateway", plane, generator, xOffset, yOffset);
}
private void marshallExclusiveGateway(ExclusiveGateway gateway, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException {
marshallNode(gateway, flowElementProperties, "Exclusive_Databased_Gateway", plane, generator, xOffset, yOffset);
}
private void marshallInclusiveGateway(InclusiveGateway gateway, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException {
if(gateway.getDefault() != null) {
flowElementProperties.put("defaultgate", gateway.getDefault().getId());
}
marshallNode(gateway, flowElementProperties, "InclusiveGateway", plane, generator, xOffset, yOffset);
}
private void marshallEventBasedGateway(EventBasedGateway gateway, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException {
marshallNode(gateway, flowElementProperties, "EventbasedGateway", plane, generator, xOffset, yOffset);
}
private void marshallComplexGateway(ComplexGateway gateway, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException {
marshallNode(gateway, flowElementProperties, "ComplexGateway", plane, generator, xOffset, yOffset);
}
private void marshallCallActivity(CallActivity callActivity, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException {
marshallNode(callActivity, flowElementProperties, "CollapsedSubprocess", plane, generator, xOffset, yOffset);
}
private void marshallNode(FlowNode node, Map<String, Object> properties, String stencil, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset) throws JsonGenerationException, IOException {
if (properties == null) {
properties = new LinkedHashMap<String, Object>();
}
if(node.getDocumentation() != null && node.getDocumentation().size() > 0) {
properties.put("documentation", node.getDocumentation().get(0).getText());
}
properties.put("name", node.getName());
marshallProperties(properties, generator);
generator.writeObjectFieldStart("stencil");
generator.writeObjectField("id", stencil);
generator.writeEndObject();
generator.writeArrayFieldStart("childShapes");
generator.writeEndArray();
generator.writeArrayFieldStart("outgoing");
for (SequenceFlow outgoing: node.getOutgoing()) {
generator.writeStartObject();
generator.writeObjectField("resourceId", outgoing.getId());
generator.writeEndObject();
}
// we need to also add associations as outgoing elements
Process process = (Process) plane.getBpmnElement();
for (Artifact artifact : process.getArtifacts()) {
if (artifact instanceof Association){
Association association = (Association) artifact;
if (association.getSourceRef().getId().equals(node.getId())) {
generator.writeStartObject();
generator.writeObjectField("resourceId", association.getId());
generator.writeEndObject();
}
}
}
// and boundary events for activities
for(FlowElement fe : process.getFlowElements()) {
if(fe instanceof BoundaryEvent) {
if(((BoundaryEvent) fe).getAttachedToRef().getId().equals(node.getId())) {
generator.writeStartObject();
generator.writeObjectField("resourceId", fe.getId());
generator.writeEndObject();
}
}
}
generator.writeEndArray();
// boundary events have a docker
if(node instanceof BoundaryEvent) {
// find the edge associated with this boundary event
for (DiagramElement element: plane.getPlaneElement()) {
if(element instanceof BPMNEdge && ((BPMNEdge) element).getBpmnElement() == node) {
List<Point> waypoints = ((BPMNEdge) element).getWaypoint();
if(waypoints != null && waypoints.size() > 0) {
// one per boundary event
Point p = waypoints.get(0);
if(p != null) {
generator.writeArrayFieldStart("dockers");
generator.writeStartObject();
generator.writeObjectField("x", p.getX());
generator.writeObjectField("y", p.getY());
generator.writeEndObject();
generator.writeEndArray();
}
}
}
}
}
BPMNShape shape = (BPMNShape) findDiagramElement(plane, node);
Bounds bounds = shape.getBounds();
correctEventNodeSize(shape);
generator.writeObjectFieldStart("bounds");
generator.writeObjectFieldStart("lowerRight");
generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset);
generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset);
generator.writeEndObject();
generator.writeObjectFieldStart("upperLeft");
generator.writeObjectField("x", bounds.getX() - xOffset);
generator.writeObjectField("y", bounds.getY() - yOffset);
generator.writeEndObject();
generator.writeEndObject();
}
private void correctEventNodeSize(BPMNShape shape) {
BaseElement element = shape.getBpmnElement();
if (element instanceof Event) {
Bounds bounds = shape.getBounds();
float width = bounds.getWidth();
float height = bounds.getHeight();
if (width != 30 || height != 30) {
bounds.setWidth(30);
bounds.setHeight(30);
float x = bounds.getX();
float y = bounds.getY();
x = x - ((30 - width)/2);
y = y - ((30 - height)/2);
bounds.setX(x);
bounds.setY(y);
}
} else if (element instanceof Gateway) {
Bounds bounds = shape.getBounds();
float width = bounds.getWidth();
float height = bounds.getHeight();
if (width != 40 || height != 40) {
bounds.setWidth(40);
bounds.setHeight(40);
float x = bounds.getX();
float y = bounds.getY();
x = x - ((40 - width)/2);
y = y - ((40 - height)/2);
bounds.setX(x);
bounds.setY(y);
}
}
}
private void marshallDataObject(DataObject dataObject, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException {
Map<String, Object> properties = new LinkedHashMap<String, Object>(flowElementProperties);
properties.put("name", dataObject.getName());
marshallProperties(properties, generator);
generator.writeObjectFieldStart("stencil");
generator.writeObjectField("id", "DataObject");
generator.writeEndObject();
generator.writeArrayFieldStart("childShapes");
generator.writeEndArray();
generator.writeArrayFieldStart("outgoing");
generator.writeEndArray();
Bounds bounds = ((BPMNShape) findDiagramElement(plane, dataObject)).getBounds();
generator.writeObjectFieldStart("bounds");
generator.writeObjectFieldStart("lowerRight");
generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset);
generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset);
generator.writeEndObject();
generator.writeObjectFieldStart("upperLeft");
generator.writeObjectField("x", bounds.getX() - xOffset);
generator.writeObjectField("y", bounds.getY() - yOffset);
generator.writeEndObject();
generator.writeEndObject();
}
private void marshallSubProcess(SubProcess subProcess, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, String preProcessingData, Definitions def, Map<String, Object> flowElementProperties) throws JsonGenerationException, IOException {
Map<String, Object> properties = new LinkedHashMap<String, Object>(flowElementProperties);
properties.put("name", subProcess.getName());
if(subProcess instanceof AdHocSubProcess) {
AdHocSubProcess ahsp = (AdHocSubProcess) subProcess;
if(ahsp.getOrdering().equals(AdHocOrdering.PARALLEL)) {
properties.put("adhocordering", "parallel");
} else if(ahsp.getOrdering().equals(AdHocOrdering.SEQUENTIAL)) {
properties.put("adhocordering", "Sequential");
} else {
// default to parallel
properties.put("adhocordering", "Parallel");
}
}
marshallProperties(properties, generator);
generator.writeObjectFieldStart("stencil");
if(subProcess instanceof AdHocSubProcess) {
generator.writeObjectField("id", "AdHocSubprocess");
} else {
generator.writeObjectField("id", "Subprocess");
}
generator.writeEndObject();
generator.writeArrayFieldStart("childShapes");
Bounds bounds = ((BPMNShape) findDiagramElement(plane, subProcess)).getBounds();
for (FlowElement flowElement: subProcess.getFlowElements()) {
// dont want to set the offset
marshallFlowElement(flowElement, plane, generator, 0, 0, preProcessingData, def);
}
for (Artifact artifact: subProcess.getArtifacts()) {
marshallArtifact(artifact, plane, generator, 0, 0, preProcessingData, def);
}
generator.writeEndArray();
generator.writeArrayFieldStart("outgoing");
for (BoundaryEvent boundaryEvent: subProcess.getBoundaryEventRefs()) {
generator.writeStartObject();
generator.writeObjectField("resourceId", boundaryEvent.getId());
generator.writeEndObject();
}
for (SequenceFlow outgoing: subProcess.getOutgoing()) {
generator.writeStartObject();
generator.writeObjectField("resourceId", outgoing.getId());
generator.writeEndObject();
}
// subprocess boundary events
Process process = (Process) plane.getBpmnElement();
for(FlowElement fe : process.getFlowElements()) {
if(fe instanceof BoundaryEvent) {
if(((BoundaryEvent) fe).getAttachedToRef().getId().equals(subProcess.getId())) {
generator.writeStartObject();
generator.writeObjectField("resourceId", fe.getId());
generator.writeEndObject();
}
}
}
generator.writeEndArray();
generator.writeObjectFieldStart("bounds");
generator.writeObjectFieldStart("lowerRight");
generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset);
generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset);
generator.writeEndObject();
generator.writeObjectFieldStart("upperLeft");
generator.writeObjectField("x", bounds.getX() - xOffset);
generator.writeObjectField("y", bounds.getY() - yOffset);
generator.writeEndObject();
generator.writeEndObject();
}
private void marshallSequenceFlow(SequenceFlow sequenceFlow, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset) throws JsonGenerationException, IOException {
Map<String, Object> properties = new LinkedHashMap<String, Object>();
// check null for sequence flow name
if(sequenceFlow.getName() != null && !"".equals(sequenceFlow.getName())) {
properties.put("name", sequenceFlow.getName());
} else {
properties.put("name", "");
}
Expression conditionExpression = sequenceFlow.getConditionExpression();
if (conditionExpression instanceof FormalExpression) {
if(((FormalExpression) conditionExpression).getBody() != null) {
properties.put("conditionexpression", ((FormalExpression) conditionExpression).getBody());
}
if(((FormalExpression) conditionExpression).getLanguage() != null) {
String cd = ((FormalExpression) conditionExpression).getLanguage();
String cdStr = "";
if(cd.equalsIgnoreCase("http://www.java.com/java")) {
cdStr = "java";
} else if(cd.equalsIgnoreCase("http://www.jboss.org/drools/rule")) {
cdStr = "drools";
} else if(cd.equalsIgnoreCase("http://www.mvel.org/2.0")) {
cdStr = "mvel";
} else {
// default to mvel
cdStr = "mvel";
}
properties.put("conditionexpressionlanguage", cdStr);
}
}
// priority value
Iterator<FeatureMap.Entry> iter = sequenceFlow.getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("priority")) {
String priorityStr = (String) entry.getValue();
if(priorityStr != null) {
try {
Integer priorityInt = Integer.parseInt(priorityStr);
if(priorityInt >= 1) {
properties.put("priority", entry.getValue());
} else {
_logger.error("Priority must be equal or greater than 1.");
}
} catch (NumberFormatException e) {
_logger.error("Priority must be a number.");
}
}
}
}
marshallProperties(properties, generator);
generator.writeObjectFieldStart("stencil");
generator.writeObjectField("id", "SequenceFlow");
generator.writeEndObject();
generator.writeArrayFieldStart("childShapes");
generator.writeEndArray();
generator.writeArrayFieldStart("outgoing");
generator.writeStartObject();
generator.writeObjectField("resourceId", sequenceFlow.getTargetRef().getId());
generator.writeEndObject();
generator.writeEndArray();
Bounds sourceBounds = ((BPMNShape) findDiagramElement(plane, sequenceFlow.getSourceRef())).getBounds();
Bounds targetBounds = ((BPMNShape) findDiagramElement(plane, sequenceFlow.getTargetRef())).getBounds();
generator.writeArrayFieldStart("dockers");
generator.writeStartObject();
generator.writeObjectField("x", sourceBounds.getWidth() / 2);
generator.writeObjectField("y", sourceBounds.getHeight() / 2);
generator.writeEndObject();
List<Point> waypoints = ((BPMNEdge) findDiagramElement(plane, sequenceFlow)).getWaypoint();
for (int i = 1; i < waypoints.size() - 1; i++) {
Point waypoint = waypoints.get(i);
generator.writeStartObject();
generator.writeObjectField("x", waypoint.getX());
generator.writeObjectField("y", waypoint.getY());
generator.writeEndObject();
}
generator.writeStartObject();
generator.writeObjectField("x", targetBounds.getWidth() / 2);
generator.writeObjectField("y", targetBounds.getHeight() / 2);
generator.writeEndObject();
generator.writeEndArray();
}
private DiagramElement findDiagramElement(BPMNPlane plane, BaseElement baseElement) {
DiagramElement result = _diagramElements.get(baseElement.getId());
if (result != null) {
return result;
}
for (DiagramElement element: plane.getPlaneElement()) {
if ((element instanceof BPMNEdge && ((BPMNEdge) element).getBpmnElement() == baseElement) ||
(element instanceof BPMNShape && ((BPMNShape) element).getBpmnElement() == baseElement)) {
_diagramElements.put(baseElement.getId(), element);
return element;
}
}
throw new IllegalArgumentException(
"Could not find BPMNDI information for " + baseElement.getId());
}
private void marshallGlobalTask(GlobalTask globalTask, JsonGenerator generator) {
if (globalTask instanceof GlobalBusinessRuleTask) {
} else if (globalTask instanceof GlobalManualTask) {
} else if (globalTask instanceof GlobalScriptTask) {
} else if (globalTask instanceof GlobalUserTask) {
} else {
}
}
private void marshallGlobalChoreographyTask(GlobalChoreographyTask callableElement, JsonGenerator generator) {
throw new UnsupportedOperationException("TODO"); //TODO!
}
private void marshallConversation(Conversation callableElement, JsonGenerator generator) {
throw new UnsupportedOperationException("TODO"); //TODO!
}
private void marshallChoreography(Choreography callableElement, JsonGenerator generator) {
throw new UnsupportedOperationException("TODO"); //TODO!
}
private void marshallProperties(Map<String, Object> properties, JsonGenerator generator) throws JsonGenerationException, IOException {
generator.writeObjectFieldStart("properties");
for (Entry<String, Object> entry : properties.entrySet()) {
generator.writeObjectField(entry.getKey(), String.valueOf(entry.getValue()));
}
generator.writeEndObject();
}
private void marshallArtifact(Artifact artifact, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, String preProcessingData, Definitions def) throws IOException {
generator.writeStartObject();
generator.writeObjectField("resourceId", artifact.getId());
if (artifact instanceof Association) {
marshallAssociation((Association)artifact, plane, generator, xOffset, yOffset, preProcessingData, def);
} else if (artifact instanceof TextAnnotation) {
marshallTextAnnotation((TextAnnotation) artifact, plane, generator, xOffset, yOffset, preProcessingData, def);
} else if (artifact instanceof Group) {
marshallGroup((Group) artifact, plane, generator, xOffset, yOffset, preProcessingData, def);
}
generator.writeEndObject();
}
private void marshallAssociation(Association association, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, String preProcessingData, Definitions def) throws JsonGenerationException, IOException {
Map<String, Object> properties = new LinkedHashMap<String, Object>();
Iterator<FeatureMap.Entry> iter = association.getAnyAttribute().iterator();
while(iter.hasNext()) {
FeatureMap.Entry entry = iter.next();
if(entry.getEStructuralFeature().getName().equals("type")) {
properties.put("type", entry.getValue());
}
}
marshallProperties(properties, generator);
generator.writeObjectFieldStart("stencil");
generator.writeObjectField("id", "Association_Undirected");
generator.writeEndObject();
generator.writeArrayFieldStart("childShapes");
generator.writeEndArray();
generator.writeArrayFieldStart("outgoing");
generator.writeStartObject();
generator.writeObjectField("resourceId", association.getTargetRef().getId());
generator.writeEndObject();
generator.writeEndArray();
Bounds sourceBounds = ((BPMNShape) findDiagramElement(plane, association.getSourceRef())).getBounds();
Bounds targetBounds = ((BPMNShape) findDiagramElement(plane, association.getTargetRef())).getBounds();
generator.writeArrayFieldStart("dockers");
generator.writeStartObject();
generator.writeObjectField("x", sourceBounds.getWidth() / 2);
generator.writeObjectField("y", sourceBounds.getHeight() / 2);
generator.writeEndObject();
List<Point> waypoints = ((BPMNEdge) findDiagramElement(plane, association)).getWaypoint();
for (int i = 1; i < waypoints.size() - 1; i++) {
Point waypoint = waypoints.get(i);
generator.writeStartObject();
generator.writeObjectField("x", waypoint.getX());
generator.writeObjectField("y", waypoint.getY());
generator.writeEndObject();
}
generator.writeStartObject();
generator.writeObjectField("x", targetBounds.getWidth() / 2);
generator.writeObjectField("y", targetBounds.getHeight() / 2);
generator.writeEndObject();
generator.writeEndArray();
}
protected void marshallTextAnnotation(TextAnnotation textAnnotation, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, String preProcessingData, Definitions def) throws JsonGenerationException, IOException{
Map<String, Object> properties = new LinkedHashMap<String, Object>();
properties.put("text", textAnnotation.getText());
properties.put("artifacttype", "Annotation");
marshallProperties(properties, generator);
generator.writeObjectFieldStart("stencil");
generator.writeObjectField("id", "TextAnnotation");
generator.writeEndObject();
generator.writeArrayFieldStart("childShapes");
generator.writeEndArray();
generator.writeArrayFieldStart("outgoing");
if(findOutgoingAssociation(plane, textAnnotation) != null) {
generator.writeStartObject();
generator.writeObjectField("resourceId", findOutgoingAssociation(plane, textAnnotation).getId());
generator.writeEndObject();
}
generator.writeEndArray();
Bounds bounds = ((BPMNShape) findDiagramElement(plane, textAnnotation)).getBounds();
generator.writeObjectFieldStart("bounds");
generator.writeObjectFieldStart("lowerRight");
generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset);
generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset);
generator.writeEndObject();
generator.writeObjectFieldStart("upperLeft");
generator.writeObjectField("x", bounds.getX() - xOffset);
generator.writeObjectField("y", bounds.getY() - yOffset);
generator.writeEndObject();
generator.writeEndObject();
}
protected void marshallGroup(Group group, BPMNPlane plane, JsonGenerator generator, int xOffset, int yOffset, String preProcessingData, Definitions def) throws JsonGenerationException, IOException{
Map<String, Object> properties = new LinkedHashMap<String, Object>();
if(group.getCategoryValueRef() != null && group.getCategoryValueRef().getValue() != null) {
properties.put("name", group.getCategoryValueRef().getValue());
}
marshallProperties(properties, generator);
generator.writeObjectFieldStart("stencil");
generator.writeObjectField("id", "Group");
generator.writeEndObject();
generator.writeArrayFieldStart("childShapes");
generator.writeEndArray();
generator.writeArrayFieldStart("outgoing");
if(findOutgoingAssociation(plane, group) != null) {
generator.writeStartObject();
generator.writeObjectField("resourceId", findOutgoingAssociation(plane, group).getId());
generator.writeEndObject();
}
generator.writeEndArray();
Bounds bounds = ((BPMNShape) findDiagramElement(plane, group)).getBounds();
generator.writeObjectFieldStart("bounds");
generator.writeObjectFieldStart("lowerRight");
generator.writeObjectField("x", bounds.getX() + bounds.getWidth() - xOffset);
generator.writeObjectField("y", bounds.getY() + bounds.getHeight() - yOffset);
generator.writeEndObject();
generator.writeObjectFieldStart("upperLeft");
generator.writeObjectField("x", bounds.getX() - xOffset);
generator.writeObjectField("y", bounds.getY() - yOffset);
generator.writeEndObject();
generator.writeEndObject();
}
protected Association findOutgoingAssociation(BPMNPlane plane, BaseElement baseElement) {
Association result = _diagramAssociations.get(baseElement.getId());
if (result != null) {
return result;
}
if (!(plane.getBpmnElement() instanceof Process)){
throw new IllegalArgumentException("Don't know how to get associations from a non-Process Diagram");
}
org.eclipse.bpmn2.Process process = (org.eclipse.bpmn2.Process) plane.getBpmnElement();
for (Artifact artifact : process.getArtifacts()) {
if (artifact instanceof Association){
Association association = (Association) artifact;
if (association.getSourceRef() == baseElement){
_diagramAssociations.put(baseElement.getId(), association);
return association;
}
}
}
return null;
}
private void marshallStencil(String stencilId, JsonGenerator generator) throws JsonGenerationException, IOException {
generator.writeObjectFieldStart("stencil");
generator.writeObjectField("id", stencilId);
generator.writeEndObject();
}
private boolean isCustomElement(String taskType, String preProcessingData) {
if(taskType != null && taskType.length() > 0 && preProcessingData != null && preProcessingData.length() > 0) {
String[] preProcessingDataElements = preProcessingData.split( ",\\s*" );
for(String preProcessingDataElement : preProcessingDataElements) {
if(taskType.equals(preProcessingDataElement)) {
return true;
}
}
}
return false;
}
}
| 50.806298 | 258 | 0.631375 |
d62096b6eb5f5b4fde3e00d238aefba92d0db695
| 3,016 |
package uk.gov.pay.connector.model.domain;
import uk.gov.pay.connector.charge.model.domain.ChargeEntity;
import uk.gov.pay.connector.gatewayaccount.model.GatewayAccountEntity;
import uk.gov.pay.connector.refund.model.domain.RefundEntity;
import uk.gov.pay.connector.refund.model.domain.RefundStatus;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import static org.apache.commons.lang.math.RandomUtils.nextLong;
import static uk.gov.pay.connector.model.domain.ChargeEntityFixture.aValidChargeEntity;
public class RefundEntityFixture {
private Long id = nextLong();
private Long amount = 500L;
private RefundStatus status = RefundStatus.CREATED;
private GatewayAccountEntity gatewayAccountEntity = ChargeEntityFixture.defaultGatewayAccountEntity();
private ChargeEntity charge;
private String reference = "reference";
public static String userExternalId = "AA213FD51B3801043FBC";
private String externalId = "someExternalId";
private ZonedDateTime createdDate = ZonedDateTime.now(ZoneId.of("UTC"));
public static RefundEntityFixture aValidRefundEntity() {
return new RefundEntityFixture();
}
public RefundEntity build() {
ChargeEntity chargeEntity = charge == null ? buildChargeEntity() : charge;
RefundEntity refundEntity = new RefundEntity(chargeEntity, amount, userExternalId);
refundEntity.setId(id);
refundEntity.setStatus(status);
refundEntity.setReference(reference);
refundEntity.setExternalId(externalId);
refundEntity.setUserExternalId(userExternalId);
refundEntity.setCreatedDate(createdDate);
return refundEntity;
}
public RefundEntityFixture withStatus(RefundStatus status) {
this.status = status;
return this;
}
public RefundEntityFixture withCreatedDate(ZonedDateTime createdDate) {
this.createdDate = createdDate;
return this;
}
public RefundEntityFixture withAmount(Long amount) {
this.amount = amount;
return this;
}
public RefundEntityFixture withReference(String reference) {
this.reference = reference;
return this;
}
public RefundEntityFixture withGatewayAccountEntity(GatewayAccountEntity gatewayAccountEntity) {
this.gatewayAccountEntity = gatewayAccountEntity;
return this;
}
public RefundEntityFixture withUserExternalId(String userExternalId) {
this.userExternalId = userExternalId;
return this;
}
public Long getAmount() {
return amount;
}
private ChargeEntity buildChargeEntity() {
return aValidChargeEntity().withGatewayAccountEntity(gatewayAccountEntity).withTransactionId("1234abc").build();
}
public RefundEntityFixture withCharge(ChargeEntity charge) {
this.charge = charge;
return this;
}
public RefundEntityFixture withExternalId(String externalId) {
this.externalId = externalId;
return this;
}
}
| 33.511111 | 120 | 0.729111 |
13e258db975aae356e1db6b0bb6a290f36ada361
| 654 |
/*******************************************************************************
* Copyright Duke Comprehensive Cancer Center and SemanticBits
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/c3pr/LICENSE.txt for details.
******************************************************************************/
package edu.duke.cabig.c3pr.rules.common.adapter;
import edu.duke.cabig.c3pr.rules.exception.RuleException;
import gov.nih.nci.cabig.c3pr.rules.brxml.RuleSet;
import org.drools.rule.Package;
public interface RuleAdapter {
public Package adapt(RuleSet ruleSet) throws RuleException;
}
| 40.875 | 81 | 0.577982 |
46ac0e6900835dea38e0a5d2b78caae89ac9e909
| 15,697 |
package me.gorgeousone.netherview.listeners;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.ProtocolManager;
import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.wrappers.BlockPosition;
import com.comphenix.protocol.wrappers.ChunkCoordIntPair;
import com.comphenix.protocol.wrappers.EnumWrappers;
import com.comphenix.protocol.wrappers.MultiBlockChangeInfo;
import com.comphenix.protocol.wrappers.WrappedBlockData;
import me.gorgeousone.netherview.ConfigSettings;
import me.gorgeousone.netherview.NetherViewPlugin;
import me.gorgeousone.netherview.blockcache.BlockCache;
import me.gorgeousone.netherview.blockcache.BlockCacheFactory;
import me.gorgeousone.netherview.blockcache.ProjectionCache;
import me.gorgeousone.netherview.customportal.CustomPortal;
import me.gorgeousone.netherview.geometry.BlockVec;
import me.gorgeousone.netherview.handlers.PlayerViewSession;
import me.gorgeousone.netherview.handlers.PortalHandler;
import me.gorgeousone.netherview.handlers.ViewHandler;
import me.gorgeousone.netherview.packet.PacketHandler;
import me.gorgeousone.netherview.portal.Portal;
import me.gorgeousone.netherview.utils.VersionUtils;
import me.gorgeousone.netherview.wrapper.blocktype.BlockType;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockExplodeEvent;
import org.bukkit.event.block.BlockFadeEvent;
import org.bukkit.event.block.BlockFormEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockGrowEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockSpreadEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.world.StructureGrowEvent;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
/**
* Listens to block changes in portal block caches to let the ViewHandler update portal animations live.
*/
public class BlockChangeListener implements Listener {
private final JavaPlugin plugin;
private final ConfigSettings configSettings;
private final PortalHandler portalHandler;
private final ViewHandler viewHandler;
private final PacketHandler packetHandler;
private final Material portalMaterial;
public BlockChangeListener(NetherViewPlugin plugin,
ConfigSettings configSettings, PortalHandler portalHandler,
ViewHandler viewHandler, PacketHandler packetHandler, Material portalMaterial) {
this.plugin = plugin;
this.configSettings = configSettings;
this.portalHandler = portalHandler;
this.viewHandler = viewHandler;
this.packetHandler = packetHandler;
this.portalMaterial = portalMaterial;
ProtocolManager protocolManager = ProtocolLibrary.getProtocolManager();
addBlockUpdateInterception(protocolManager);
addMultiBlockUpdateInterception(protocolManager);
addBlockDigInterception(protocolManager);
}
/**
* Prevents players from breaking a portal projection when they are breaking or stopping to break a block.
* (Still feels like im missing a some packet or event that is fired before)
*/
private void addBlockDigInterception(ProtocolManager protocolManager) {
protocolManager.addPacketListener(new PacketAdapter(plugin, ListenerPriority.HIGHEST, PacketType.Play.Client.BLOCK_DIG) {
@Override
public void onPacketReceiving(PacketEvent event) {
PacketContainer packet = event.getPacket();
Player player = event.getPlayer();
if (packetHandler.isCustomPacket(packet) || !viewHandler.hasViewSession(player)) {
return;
}
EnumWrappers.PlayerDigType digType = packet.getPlayerDigTypes().read(0);
if (digType != EnumWrappers.PlayerDigType.ABORT_DESTROY_BLOCK &&
digType != EnumWrappers.PlayerDigType.STOP_DESTROY_BLOCK) {
return;
}
BlockPosition blockPos = packet.getBlockPositionModifier().read(0);
BlockType projectedBlockType = getProjectedBlockType(player, new BlockVec(blockPos));
if (projectedBlockType == null) {
return;
}
event.setCancelled(true);
if (digType == EnumWrappers.PlayerDigType.STOP_DESTROY_BLOCK) {
packetHandler.refreshFakeBlock(player, blockPos, projectedBlockType);
}
}
});
}
private void addBlockUpdateInterception(ProtocolManager protocolManager) {
protocolManager.addPacketListener(
new PacketAdapter(plugin, ListenerPriority.NORMAL, PacketType.Play.Server.BLOCK_CHANGE) {
@Override
public void onPacketSending(PacketEvent event) {
PacketContainer packet = event.getPacket();
Player player = event.getPlayer();
if (packetHandler.isCustomPacket(packet) || !viewHandler.hasViewSession(player)) {
return;
}
BlockPosition blockPos = packet.getBlockPositionModifier().read(0);
BlockType projectedBlockType = getProjectedBlockType(player, new BlockVec(blockPos));
if (projectedBlockType != null) {
packet.getBlockData().write(0, projectedBlockType.getWrapped());
}
}
}
);
}
/**
* Intercepts multi block changes and edits any changed block data inside a portal animation back to the animation block data
*/
private void addMultiBlockUpdateInterception(ProtocolManager protocolManager) {
protocolManager.addPacketListener(
new PacketAdapter(plugin, ListenerPriority.HIGHEST, PacketType.Play.Server.MULTI_BLOCK_CHANGE) {
@Override
public void onPacketSending(PacketEvent event) {
PacketContainer packet = event.getPacket();
Player player = event.getPlayer();
//call the custom packet check first so the packet handler will definitely flush the packet from the list
if (packetHandler.isCustomPacket(packet) || !viewHandler.hasViewSession(player)) {
return;
}
PlayerViewSession session = viewHandler.getViewSession(player);
Portal viewedPortal = session.getViewedPortal();
ProjectionCache viewedCache = session.getViewedPortalSide();
Map<BlockVec, BlockType> viewSession = session.getProjectedBlocks();
if (VersionUtils.serverIsAtOrAbove("1.16.2")) {
rewriteProjectionBlockTypes1_16_2(packet, viewedPortal, viewedCache, viewSession);
} else {
rewriteProjectionBlockTypes(packet, viewedPortal, viewedCache, viewSession);
}
}
}
);
}
private void rewriteProjectionBlockTypes(PacketContainer packet,
Portal viewedPortal,
ProjectionCache viewedCache,
Map<BlockVec, BlockType> viewSession) {
ChunkCoordIntPair chunkLoc = packet.getChunkCoordIntPairs().read(0);
int chunkWorldX = chunkLoc.getChunkX() << 4;
int chunkWorldZ = chunkLoc.getChunkZ() << 4;
Object[] blockInfoArray = packet.getMultiBlockChangeInfoArrays().getValues().get(0);
for (Object object : blockInfoArray) {
MultiBlockChangeInfo blockInfo = (MultiBlockChangeInfo) object;
BlockVec blockPos = new BlockVec(
blockInfo.getX() + chunkWorldX,
blockInfo.getY(),
blockInfo.getZ() + chunkWorldZ);
if (getProjectedBlockType(blockPos, viewedPortal, viewedCache, viewSession) != null) {
blockInfo.setData(viewSession.get(blockPos).getWrapped());
}
}
packet.getMultiBlockChangeInfoArrays().write(0, Arrays.copyOf(blockInfoArray, blockInfoArray.length, MultiBlockChangeInfo[].class));
}
private void rewriteProjectionBlockTypes1_16_2(PacketContainer packet,
Portal viewedPortal,
ProjectionCache viewedCache,
Map<BlockVec, BlockType> viewSession) {
//it's somehow an Object array and not a WrappedBlockData array, don't ask me
Object[] blockTypes = packet.getBlockDataArrays().read(0);
short[] blockLocs = packet.getShortArrays().read(0);
BlockVec chunkLoc = new BlockVec(packet.getSectionPositions().read(0)).multiply(16);
int x = 0;
for (int i = 0; i < blockLocs.length; i++) {
BlockVec blockPos = new BlockVec(blockLocs[i]).add(chunkLoc);
if (getProjectedBlockType(blockPos, viewedPortal, viewedCache, viewSession) != null) {
blockTypes[i] = viewSession.get(blockPos).getWrapped();
x++;
}
}
//have to copy wrapped block data into WrappedBlockData[] manually here
packet.getBlockDataArrays().write(0, Arrays.copyOf(blockTypes, blockTypes.length, WrappedBlockData[].class));
}
/**
* Returns the BlockType that is displayed the player in the projection at the block position.
* Returns null if no block is being displayed at the position.
*/
private BlockType getProjectedBlockType(BlockVec blockPos,
Portal viewedPortal,
ProjectionCache viewedCache,
Map<BlockVec, BlockType> viewSession) {
return (viewedPortal.getFrame().contains(blockPos) || viewedCache.contains(blockPos)) ? viewSession.get(blockPos) : null;
}
private BlockType getProjectedBlockType(Player player, BlockVec blockPos) {
PlayerViewSession session = viewHandler.getViewSession(player);
if (session.getViewedPortal().getFrame().contains(blockPos) ||
session.getViewedPortalSide().contains(blockPos)) {
return viewHandler.getViewSession(player).getProjectedBlocks().get(blockPos);
}
return null;
}
private void removeDamagedPortals(Block block) {
World blockWorld = block.getWorld();
if (!portalHandler.hasPortals(blockWorld)) {
return;
}
for (Portal portal : new HashSet<>(portalHandler.getPortals(blockWorld))) {
if (!(portal instanceof CustomPortal) && portal.getFrame().contains(block)) {
viewHandler.removePortal(portal);
portalHandler.removePortal(portal);
}
}
}
private void updateBlockCaches(Block block, BlockType newBlockType, boolean blockWasOccluding) {
World blockWorld = block.getWorld();
if (!portalHandler.hasPortals(blockWorld)) {
return;
}
BlockVec blockPos = new BlockVec(block);
for (BlockCache cache : portalHandler.getBlockCaches(blockWorld)) {
if (!cache.contains(blockPos)) {
continue;
}
Map<BlockVec, BlockType> updatedCopies = BlockCacheFactory.updateBlockInCache(cache, block, newBlockType, blockWasOccluding);
if (!updatedCopies.isEmpty()) {
viewHandler.updateProjections(cache, updatedCopies);
}
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockInteract(PlayerInteractEvent event) {
if (event.getAction() != Action.LEFT_CLICK_BLOCK && event.getAction() != Action.RIGHT_CLICK_BLOCK) {
return;
}
Player player = event.getPlayer();
if (!viewHandler.hasViewSession(player)) {
return;
}
Map<BlockVec, BlockType> viewSession = viewHandler.getViewSession(player).getProjectedBlocks();
BlockVec blockPos = new BlockVec(event.getClickedBlock());
if (viewSession.containsKey(blockPos)) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent event) {
Block block = event.getBlock();
Material blockType = block.getType();
updateBlockCaches(block, BlockType.of(Material.AIR), blockType.isOccluding());
if (blockType == portalMaterial || blockType.isOccluding()) {
removeDamagedPortals(block);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
Block block = event.getBlock();
updateBlockCaches(block, BlockType.of(block), false);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockExplode(BlockExplodeEvent event) {
for (Block block : event.blockList()) {
updateBlockCaches(block, BlockType.of(Material.AIR), block.getType().isOccluding());
}
if (!configSettings.canCreatePortalViews(event.getBlock().getWorld())) {
return;
}
for (Block block : event.blockList()) {
Material material = block.getType();
if (material == portalMaterial || material.isOccluding()) {
removeDamagedPortals(block);
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityExplode(EntityExplodeEvent event) {
for (Block block : event.blockList()) {
updateBlockCaches(block, BlockType.of(Material.AIR), block.getType().isOccluding());
}
if (configSettings.canCreatePortalViews(event.getEntity().getWorld())) {
for (Block block : event.blockList()) {
if (block.getType() == portalMaterial) {
removeDamagedPortals(block);
}
}
}
}
//water, lava, dragon eggs
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockSpill(BlockFromToEvent event) {
Block block = event.getToBlock();
updateBlockCaches(block, BlockType.of(event.getBlock()), false);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockBurn(BlockBurnEvent event) {
Block block = event.getBlock();
updateBlockCaches(block, BlockType.of(Material.AIR), block.getType().isOccluding());
}
private void onAnyGrowEvent(BlockGrowEvent event) {
Block block = event.getBlock();
updateBlockCaches(block, BlockType.of(event.getNewState()), block.getType().isOccluding());
}
//pumpkin/melon growing
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockGrow(BlockGrowEvent event) {
onAnyGrowEvent(event);
}
//grass, mycelium spreading
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockSpread(BlockSpreadEvent event) {
onAnyGrowEvent(event);
}
//obsidian, concrete
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockForm(BlockFormEvent event) {
onAnyGrowEvent(event);
}
//ice melting
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockFade(BlockFadeEvent event) {
Block block = event.getBlock();
updateBlockCaches(block, BlockType.of(event.getNewState()), block.getType().isOccluding());
}
//falling sand and maybe endermen (actually also sheep but that doesn't work)
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityChangeBlock(EntityChangeBlockEvent event) {
//TODO check what 1.8 uses instead of event.getBlockData()
Block block = event.getBlock();
updateBlockCaches(block, BlockType.of(event.getBlock()), false);
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlantGrow(StructureGrowEvent event) {
for (BlockState state : event.getBlocks()) {
updateBlockCaches(state.getBlock(), BlockType.of(state), false);
}
}
}
| 35.116331 | 134 | 0.731477 |
a314f272029b849da6f754030c8f9c0900080ae3
| 6,924 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-257
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.09.11 at 01:11:57 PM BST
//
package OctopusConsortium.Models.ITK;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for PQ_inc complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="PQ_inc">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="translation" type="{urn:hl7-org:v3}PQR" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute name="value" type="{urn:hl7-org:v3}real" />
* <attribute name="unit" type="{urn:hl7-org:v3}cs" default="1" />
* <attribute name="originalValue" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
* <attribute name="originalUnit" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
* <attribute name="nullFlavor" type="{urn:hl7-org:v3}cs_NullFlavor" />
* <attribute name="inclusive" type="{urn:hl7-org:v3}bl" default="true" />
* <attribute name="updateMode" type="{urn:hl7-org:v3}cs_UpdateMode" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PQ_inc", propOrder = {
"translation"
})
public class PQInc {
protected List<PQR> translation;
@XmlAttribute
protected String value;
@XmlAttribute
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String unit;
@XmlAttribute
@XmlSchemaType(name = "anySimpleType")
protected String originalValue;
@XmlAttribute
@XmlSchemaType(name = "anySimpleType")
protected String originalUnit;
@XmlAttribute
protected CsNullFlavor nullFlavor;
@XmlAttribute
protected Boolean inclusive;
@XmlAttribute
protected CsUpdateMode updateMode;
/**
* Gets the value of the translation property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the translation property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTranslation().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PQR }
*
*
*/
public List<PQR> getTranslation() {
if (translation == null) {
translation = new ArrayList<PQR>();
}
return this.translation;
}
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets the value of the unit property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUnit() {
if (unit == null) {
return "1";
} else {
return unit;
}
}
/**
* Sets the value of the unit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUnit(String value) {
this.unit = value;
}
/**
* Gets the value of the originalValue property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOriginalValue() {
return originalValue;
}
/**
* Sets the value of the originalValue property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOriginalValue(String value) {
this.originalValue = value;
}
/**
* Gets the value of the originalUnit property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOriginalUnit() {
return originalUnit;
}
/**
* Sets the value of the originalUnit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOriginalUnit(String value) {
this.originalUnit = value;
}
/**
* Gets the value of the nullFlavor property.
*
* @return
* possible object is
* {@link CsNullFlavor }
*
*/
public CsNullFlavor getNullFlavor() {
return nullFlavor;
}
/**
* Sets the value of the nullFlavor property.
*
* @param value
* allowed object is
* {@link CsNullFlavor }
*
*/
public void setNullFlavor(CsNullFlavor value) {
this.nullFlavor = value;
}
/**
* Gets the value of the inclusive property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public boolean isInclusive() {
if (inclusive == null) {
return true;
} else {
return inclusive;
}
}
/**
* Sets the value of the inclusive property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setInclusive(Boolean value) {
this.inclusive = value;
}
/**
* Gets the value of the updateMode property.
*
* @return
* possible object is
* {@link CsUpdateMode }
*
*/
public CsUpdateMode getUpdateMode() {
return updateMode;
}
/**
* Sets the value of the updateMode property.
*
* @param value
* allowed object is
* {@link CsUpdateMode }
*
*/
public void setUpdateMode(CsUpdateMode value) {
this.updateMode = value;
}
}
| 24.728571 | 126 | 0.572068 |
ce9da79dea7771eb0e72917daf54920c6a0820fa
| 204 |
package cn.lite.flow.executor.common.exception;
/**
* rpc调用异常
*/
public class ExecutorRpcRuntimeException extends RuntimeException {
public ExecutorRpcRuntimeException(String msg) {super(msg);}
}
| 20.4 | 67 | 0.77451 |
63ac01ce3ad1993a39664c2cbdacf0b0d024300b
| 381 |
package com.example.test.java;
/**
* Created by cosmin on 1/22/17.
*/
public class B {
public int x;
public B(int x) {
this.x = x;
}
public static void swap(B b1, B b2) {
B aux = b1;
b1 = b2;
b2 = aux;
}
public static void swapCorrect(B b1, B b2) {
int aux = b1.x;
b1.x = b2.x;
b2.x = aux;
}
}
| 17.318182 | 48 | 0.475066 |
c8f6626709f4f36edd4415d7da78bdad261a09d5
| 371 |
package com.github.knightliao.middle.http.common.service.loadbalance;
import java.util.List;
import com.github.knightliao.middle.http.common.service.server.helper.server.ServerStatus;
/**
* @author knightliao
* @email knightliao@gmail.com
* @date 2021/8/23 11:49
*/
public interface ILoadBalancer {
ServerStatus select(List<ServerStatus> serverStatusList);
}
| 23.1875 | 90 | 0.77628 |
b55d6e71d5950dbc2435cdccb159b0fcfd06718b
| 379 |
package com.luv2code.springdemo;
public class TrackCoach implements Coach {
private Fortune fortune;
public TrackCoach(Fortune fortune) {
this.fortune = fortune;
}
public TrackCoach() {
}
@Override
public String getDailyWorkout() {
return "Run a hard 5k";
}
@Override
public String getFortune() {
return "TrackCoach :"+fortune.getFortune();
}
}
| 10.828571 | 45 | 0.693931 |
cff4b49fb2d0404976f3305c0a9c9f3f4aebaa23
| 3,891 |
package com.dell.doradus.spider3;
import java.util.HashSet;
import java.util.Set;
import com.dell.doradus.common.ApplicationDefinition;
import com.dell.doradus.common.FieldDefinition;
import com.dell.doradus.common.TableDefinition;
import com.dell.doradus.common.Utils;
import com.dell.doradus.logservice.pattern.Pattern;
import com.dell.doradus.service.db.DBService;
import com.dell.doradus.service.db.DColumn;
import com.dell.doradus.service.db.Tenant;
public class DocSet {
private Set<String> m_ids = new HashSet<>();
public DocSet() {}
public Set<String> getIDs() { return m_ids; }
public void addId(String id) {
m_ids.add(id);
}
public boolean contains(String id) {
return m_ids.contains(id);
}
public void clear() {
m_ids.clear();
}
public void and(DocSet set) {
Set<String> newids = new HashSet<String>();
for(String s: m_ids) {
if(set.contains(s)) newids.add(s);
}
m_ids = newids;
}
public void or(DocSet set) {
m_ids.addAll(set.m_ids);
}
public void andNot(DocSet set) {
m_ids.removeAll(set.m_ids);
}
public void fillAll(TableDefinition tableDef) {
ApplicationDefinition appDef = tableDef.getAppDef();
Tenant tenant = Spider3.instance().getTenant(tableDef.getAppDef());
String store = appDef.getAppName();
String table = tableDef.getTableName();
String row = table + "/_id";
for(DColumn column: DBService.instance(tenant).getAllColumns(store, row)) {
m_ids.add(column.getName());
}
}
public void fillLink(FieldDefinition linkDef, DocSet linkedSet) {
m_ids.clear();
if(linkedSet.m_ids.size() == 0) return;
TableDefinition tableDef = linkDef.getTableDef();
ApplicationDefinition appDef = tableDef.getAppDef();
Tenant tenant = Spider3.instance().getTenant(tableDef.getAppDef());
String store = appDef.getAppName();
String table = tableDef.getTableName();
String row = table + "/" + linkDef.getName();
if(linkedSet.m_ids.size() < 10) {
String inverseRow = linkDef.getLinkExtent() + "/" + linkDef.getLinkInverse();
for(String id: linkedSet.m_ids) {
for(DColumn column: DBService.instance(tenant).getColumnSlice(store, inverseRow, id, id + "~")) {
String[] nv = Spider3.split(column.getName());
m_ids.add(nv[1]);
}
}
} else {
for(DColumn column: DBService.instance(tenant).getAllColumns(store, row)) {
String[] nv = Spider3.split(column.getName());
if(!linkedSet.contains(nv[1])) continue;
m_ids.add(nv[0]);
}
}
}
public void fillField(FieldDefinition fieldDef, String pattern) {
TableDefinition tableDef = fieldDef.getTableDef();
ApplicationDefinition appDef = tableDef.getAppDef();
Tenant tenant = Spider3.instance().getTenant(tableDef.getAppDef());
String store = appDef.getAppName();
String table = tableDef.getTableName();
String row = table + "/" + fieldDef.getName();
Pattern p = new Pattern(pattern);
for(DColumn column: DBService.instance(tenant).getAllColumns(store, row)) {
if(fieldDef.isCollection()) {
String[] nv = Spider3.split(column.getName());
byte[] value = Utils.toBytes(nv[1]);
if(!p.match(value, 0, value.length)) continue;
m_ids.add(nv[0]);
} else {
byte[] value = column.getRawValue();
if(!p.match(value, 0, value.length)) continue;
m_ids.add(column.getName());
}
}
}
}
| 34.741071 | 113 | 0.593421 |
2bf4a07296de00d749ffe71d8c5312deb3625ecc
| 1,667 |
package arc.math.geom;
/**
* A Segment is a line in 3-space having a staring and an ending position.
* @author mzechner
*/
public class Segment{
/** the starting position **/
public final Vec3 a = new Vec3();
/** the ending position **/
public final Vec3 b = new Vec3();
/**
* Constructs a new Segment from the two points given.
* @param a the first point
* @param b the second point
*/
public Segment(Vec3 a, Vec3 b){
this.a.set(a);
this.b.set(b);
}
/**
* Constructs a new Segment from the two points given.
* @param aX the x-coordinate of the first point
* @param aY the y-coordinate of the first point
* @param aZ the z-coordinate of the first point
* @param bX the x-coordinate of the second point
* @param bY the y-coordinate of the second point
* @param bZ the z-coordinate of the second point
*/
public Segment(float aX, float aY, float aZ, float bX, float bY, float bZ){
this.a.set(aX, aY, aZ);
this.b.set(bX, bY, bZ);
}
public float len(){
return a.dst(b);
}
public float len2(){
return a.dst2(b);
}
@Override
public boolean equals(Object o){
if(o == this) return true;
if(o == null || o.getClass() != this.getClass()) return false;
Segment s = (Segment)o;
return this.a.equals(s.a) && this.b.equals(s.b);
}
@Override
public int hashCode(){
final int prime = 71;
int result = 1;
result = prime * result + this.a.hashCode();
result = prime * result + this.b.hashCode();
return result;
}
}
| 26.887097 | 79 | 0.579484 |
a7aa98c1bf51098aa5ace4d59afb87d13310b764
| 3,406 |
<%#
Copyright 2013-2017 the original author or authors from the JBooter project.
This file is part of the JBooter project, see https://jbooter.github.io/
for more information.
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 <%=packageName%>.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension;
import javax.annotation.PostConstruct;
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class UaaWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
private final UserDetailsService userDetailsService;
private final AuthenticationManagerBuilder authenticationManagerBuilder;
public UaaWebSecurityConfiguration(UserDetailsService userDetailsService, AuthenticationManagerBuilder authenticationManagerBuilder) {
this.userDetailsService = userDetailsService;
this.authenticationManagerBuilder = authenticationManagerBuilder;
}
@PostConstruct
public void init() throws Exception {
authenticationManagerBuilder
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers("/app/**/*.{js,html}")
.antMatchers("/bower_components/**")
.antMatchers("/i18n/**")
.antMatchers("/content/**")
.antMatchers("/swagger-ui/index.html")
.antMatchers("/test/**")
.antMatchers("/h2-console/**");
}
@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
}
| 40.070588 | 138 | 0.767763 |
8d9d6efe971ec4cfd8a3fe14042938cc15561b1f
| 2,756 |
package svenhjol.charm.module;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.Identifier;
import net.minecraft.village.VillagerProfession;
import net.minecraft.world.poi.PointOfInterestType;
import svenhjol.charm.Charm;
import svenhjol.charm.village.BeekeeperTradeOffers;
import svenhjol.charm.event.StructureSetupCallback;
import svenhjol.charm.event.StructureSetupCallback.VillageType;
import svenhjol.charm.mixin.accessor.PointOfInterestTypeAccessor;
import svenhjol.charm.base.CharmModule;
import svenhjol.charm.base.helper.VillagerHelper;
import svenhjol.charm.base.iface.Module;
import static svenhjol.charm.event.StructureSetupCallback.addVillageHouse;
import static svenhjol.charm.base.helper.VillagerHelper.addTrade;
@Module(mod = Charm.MOD_ID, description = "Beekeepers are villagers that trade beekeeping items. Their job site is the beehive.")
public class Beekeepers extends CharmModule {
public static Identifier ID = new Identifier(Charm.MOD_ID, "beekeeper");
public static VillagerProfession BEEKEEPER;
@Override
public void init() {
BEEKEEPER = VillagerHelper.addProfession(ID, PointOfInterestType.BEEHIVE, SoundEvents.BLOCK_BEEHIVE_WORK);
// HACK: set ticketCount so that villager can use it as job site
((PointOfInterestTypeAccessor)PointOfInterestType.BEEHIVE).setTicketCount(1);
// register beekeeper trades
addTrade(BEEKEEPER, 1, new BeekeeperTradeOffers.EmeraldsForFlowers());
addTrade(BEEKEEPER, 1, new BeekeeperTradeOffers.BottlesForEmerald());
addTrade(BEEKEEPER, 2, new BeekeeperTradeOffers.EmeraldsForCharcoal());
addTrade(BEEKEEPER, 2, new BeekeeperTradeOffers.BeeswaxForEmeralds());
addTrade(BEEKEEPER, 3, new BeekeeperTradeOffers.EmeraldsForHoneycomb());
addTrade(BEEKEEPER, 3, new BeekeeperTradeOffers.CampfireForEmerald());
addTrade(BEEKEEPER, 4, new BeekeeperTradeOffers.LeadForEmeralds());
addTrade(BEEKEEPER, 5, new BeekeeperTradeOffers.PopulatedBeehiveForEmeralds());
// register beekeeper structures
StructureSetupCallback.EVENT.register(() -> {
addVillageHouse(VillageType.PLAINS, new Identifier("charm:village/plains/houses/plains_beekeeper_1"), 10);
addVillageHouse(VillageType.DESERT, new Identifier("charm:village/desert/houses/desert_beekeeper_1"), 10);
addVillageHouse(VillageType.SAVANNA, new Identifier("charm:village/savanna/houses/savanna_beekeeper_1"), 10);
addVillageHouse(VillageType.SAVANNA, new Identifier("charm:village/savanna/houses/savanna_beekeeper_2"), 10);
addVillageHouse(VillageType.TAIGA, new Identifier("charm:village/taiga/houses/taiga_beekeeper_1"), 10);
});
}
}
| 54.039216 | 129 | 0.772134 |
8a3e0b658d8e0342473105cd869fa38a413060ca
| 3,234 |
package org.infinispan.api.annotations.indexing;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.hibernate.search.engine.environment.bean.BeanRetrieval;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.processing.PropertyMapping;
import org.hibernate.search.mapper.pojo.mapping.definition.annotation.processing.PropertyMappingAnnotationProcessorRef;
import org.infinispan.api.annotations.indexing.model.Values;
import org.infinispan.api.common.annotations.indexing._private.BasicProcessor;
/**
* Maps an entity property to a field in the index.
* <p>
* This is a generic annotation that will work for any standard field type:
* {@link String}, {@link Integer}, {@link java.time.LocalDate}, ...
* <p>
* Note that this annotation, being generic, does not offer configuration options
* that are specific to only some types of fields.
* Use more specific annotations if you want that kind of configuration.
* For example, to define a tokenized (multi-word) text field, use {@link Text}.
* To define a non-tokenized (single-word), but normalized (lowercased, ...) text field, use {@link Keyword}.
* <p>
* Simplified version for Infinispan of {@link org.hibernate.search.mapper.pojo.mapping.definition.annotation.GenericField}
*
* @since 14.0
*/
@Documented
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Basic.List.class)
@PropertyMapping(processor = @PropertyMappingAnnotationProcessorRef(type = BasicProcessor.class, retrieval = BeanRetrieval.CONSTRUCTOR))
public @interface Basic {
/**
* @return The name of the index field.
*/
String name() default "";
/**
* Whether we want to be able to obtain the value of the field as a projection.
* <p>
* This usually means that the field will be stored in the index, but it is more subtle than that, for instance in the
* case of projection by distance.
*
* @return Whether projections are enabled for this field.
*/
boolean projectable() default false;
/**
* Whether a field can be used in sorts.
*
* @return Whether this field should be sortable.
*/
boolean sortable() default false;
/**
* Whether we want to be able to search the document using this field.
* <p>
* If the field is not searchable, search predicates cannot be applied to it.
*
* @return Whether this field should be searchable.
*/
boolean searchable() default true;
/**
* Whether the field can be used in aggregations.
* <p>
* This usually means that the field will have doc-values stored in the index.
*
* @return Whether aggregations are enabled for this field.
*/
boolean aggregable() default false;
/**
* @return A value used instead of null values when indexing.
*/
String indexNullAs() default Values.DO_NOT_INDEX_NULL;
@Documented
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface List {
Basic[] value();
}
}
| 35.538462 | 136 | 0.729437 |
cf92589c3fbf728e7685fe2b26c972d7073ab001
| 5,762 |
/*******************************************************************************
* Copyright (c) 2010 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.engine.executor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import org.eclipse.birt.core.btree.BTree;
import org.eclipse.birt.core.btree.BTreeOption;
import org.eclipse.birt.core.btree.BTreeSerializer;
import org.eclipse.birt.core.btree.BTreeUtils;
import org.eclipse.birt.core.btree.FileBTreeFile;
import org.eclipse.birt.report.engine.api.EngineException;
public class BookmarkManager
{
static final Integer VALUE = new Integer( 0 );
int sequenceID = 0;
BookmarkHashSet hashset;
ExecutionContext context;
public BookmarkManager( ExecutionContext context, int size )
{
this.context = context;
hashset = new BookmarkHashSet( context, size );
}
public void close()
{
hashset.close( );
}
public boolean exist( String bookmark )
{
try
{
return hashset.exist( bookmark );
}
catch ( IOException ex )
{
context.addException( new EngineException( ex.getMessage( ), ex ) );
}
return false;
}
public void addBookmark( String bookmark )
{
try
{
hashset.addBookmark( bookmark );
}
catch ( IOException ex )
{
context.addException( new EngineException( ex.getMessage( ), ex ) );
}
}
public String createBookmark( String bookmark )
{
return "_recreated__bookmark__" + ( ++sequenceID );
}
static private class StringSerializer implements BTreeSerializer<String>
{
public byte[] getBytes( String object ) throws IOException
{
ByteArrayOutputStream out = new ByteArrayOutputStream( 1024 );
DataOutput oo = new DataOutputStream( out );
oo.writeUTF( object );
return out.toByteArray( );
}
public String getObject( byte[] bytes ) throws IOException,
ClassNotFoundException
{
DataInput input = new DataInputStream( new ByteArrayInputStream(
bytes ) );
return input.readUTF( );
}
}
static private class IntegerSerializer implements BTreeSerializer<Integer>
{
public byte[] getBytes( Integer object ) throws IOException
{
byte[] bytes = new byte[4];
BTreeUtils.integerToBytes( object.intValue( ), bytes );
return bytes;
}
public Integer getObject( byte[] bytes ) throws IOException,
ClassNotFoundException
{
return new Integer( BTreeUtils.bytesToInteger( bytes ) );
}
}
private class BookmarkHashSet
{
protected HashMap<String, Integer> inlineMap = new HashMap<String, Integer>( );
protected BTree<String, Integer> btree = null;
protected String fileName;
protected ExecutionContext context;
protected int size;
public BookmarkHashSet( ExecutionContext context, int size )
{
this.context = context;
this.size = size;
}
public boolean exist( String bookmark ) throws IOException
{
if ( inlineMap != null )
{
return inlineMap.containsKey( bookmark );
}
else
{
if ( btree == null )
{
btree = createBtree( );
}
return btree.exist( bookmark );
}
}
public void addBookmark( String bookmark ) throws IOException
{
if ( inlineMap != null )
{
if ( inlineMap.size( ) < size )
{
inlineMap.put( bookmark, VALUE );
}
else
{
flush( );
inlineMap = null;
btree.insert( bookmark, VALUE );
}
}
else
{
if ( btree == null )
{
btree = createBtree( );
}
btree.insert( bookmark, VALUE );
}
}
protected void flush( ) throws IOException
{
if ( btree == null )
{
btree = createBtree( );
}
ArrayList<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(
inlineMap.entrySet( ) );
Collections.sort( entries,
new Comparator<Map.Entry<String, Integer>>( ) {
public int compare( Entry<String, Integer> o1,
Entry<String, Integer> o2 )
{
return o1.getKey( ).compareTo( o2.getKey( ) );
}
} );
for ( Map.Entry<String, Integer> entry : entries )
{
btree.insert( entry.getKey( ), VALUE );
}
}
protected BTree<String, Integer> createBtree( ) throws IOException
{
String tmpdir = context.getEngine( ).getConfig( ).getTempDir( );
fileName = tmpdir + File.separator + UUID.randomUUID( );
FileBTreeFile file = new FileBTreeFile( fileName );
BTreeOption<String, Integer> option = new BTreeOption<String, Integer>( );
option.setHasValue( true );
option.setKeySerializer( new StringSerializer( ) );
option.setValueSerializer( new IntegerSerializer( ) );
option.setValueSize( 4 );
option.setFile( file );
return new BTree<String, Integer>( option );
}
public void close( )
{
inlineMap = null;
if ( btree != null )
{
try
{
btree.close( );
File file = new File( fileName );
if ( file.exists( ) )
{
file.delete( );
}
}
catch ( IOException e )
{
context.addException( new EngineException( e.getMessage( ),
e ) );
}
}
}
}
}
| 23.908714 | 93 | 0.656543 |
3d9aef06a1feb8e25be31a62fadf4dc673a9bd6b
| 31,412 |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: resources.proto
package counters.minter.grpc.client;
/**
* Protobuf type {@code api_pb.FrozenAllRequest}
*/
public final class FrozenAllRequest extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:api_pb.FrozenAllRequest)
FrozenAllRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use FrozenAllRequest.newBuilder() to construct.
private FrozenAllRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private FrozenAllRequest() {
addresses_ = com.google.protobuf.LazyStringArrayList.EMPTY;
coinIds_ = emptyLongList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new FrozenAllRequest();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private FrozenAllRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 8: {
startHeight_ = input.readUInt64();
break;
}
case 16: {
endHeight_ = input.readUInt64();
break;
}
case 24: {
height_ = input.readUInt64();
break;
}
case 34: {
java.lang.String s = input.readStringRequireUtf8();
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
addresses_ = new com.google.protobuf.LazyStringArrayList();
mutable_bitField0_ |= 0x00000001;
}
addresses_.add(s);
break;
}
case 40: {
if (!((mutable_bitField0_ & 0x00000002) != 0)) {
coinIds_ = newLongList();
mutable_bitField0_ |= 0x00000002;
}
coinIds_.addLong(input.readUInt64());
break;
}
case 42: {
int length = input.readRawVarint32();
int limit = input.pushLimit(length);
if (!((mutable_bitField0_ & 0x00000002) != 0) && input.getBytesUntilLimit() > 0) {
coinIds_ = newLongList();
mutable_bitField0_ |= 0x00000002;
}
while (input.getBytesUntilLimit() > 0) {
coinIds_.addLong(input.readUInt64());
}
input.popLimit(limit);
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) != 0)) {
addresses_ = addresses_.getUnmodifiableView();
}
if (((mutable_bitField0_ & 0x00000002) != 0)) {
coinIds_.makeImmutable(); // C
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return counters.minter.grpc.client.Resources.internal_static_api_pb_FrozenAllRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return counters.minter.grpc.client.Resources.internal_static_api_pb_FrozenAllRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
counters.minter.grpc.client.FrozenAllRequest.class, counters.minter.grpc.client.FrozenAllRequest.Builder.class);
}
public static final int START_HEIGHT_FIELD_NUMBER = 1;
private long startHeight_;
/**
* <code>uint64 start_height = 1;</code>
* @return The startHeight.
*/
@java.lang.Override
public long getStartHeight() {
return startHeight_;
}
public static final int END_HEIGHT_FIELD_NUMBER = 2;
private long endHeight_;
/**
* <code>uint64 end_height = 2;</code>
* @return The endHeight.
*/
@java.lang.Override
public long getEndHeight() {
return endHeight_;
}
public static final int HEIGHT_FIELD_NUMBER = 3;
private long height_;
/**
* <code>uint64 height = 3;</code>
* @return The height.
*/
@java.lang.Override
public long getHeight() {
return height_;
}
public static final int ADDRESSES_FIELD_NUMBER = 4;
private com.google.protobuf.LazyStringList addresses_;
/**
* <code>repeated string addresses = 4;</code>
* @return A list containing the addresses.
*/
public com.google.protobuf.ProtocolStringList
getAddressesList() {
return addresses_;
}
/**
* <code>repeated string addresses = 4;</code>
* @return The count of addresses.
*/
public int getAddressesCount() {
return addresses_.size();
}
/**
* <code>repeated string addresses = 4;</code>
* @param index The index of the element to return.
* @return The addresses at the given index.
*/
public java.lang.String getAddresses(int index) {
return addresses_.get(index);
}
/**
* <code>repeated string addresses = 4;</code>
* @param index The index of the value to return.
* @return The bytes of the addresses at the given index.
*/
public com.google.protobuf.ByteString
getAddressesBytes(int index) {
return addresses_.getByteString(index);
}
public static final int COIN_IDS_FIELD_NUMBER = 5;
private com.google.protobuf.Internal.LongList coinIds_;
/**
* <code>repeated uint64 coin_ids = 5;</code>
* @return A list containing the coinIds.
*/
@java.lang.Override
public java.util.List<java.lang.Long>
getCoinIdsList() {
return coinIds_;
}
/**
* <code>repeated uint64 coin_ids = 5;</code>
* @return The count of coinIds.
*/
public int getCoinIdsCount() {
return coinIds_.size();
}
/**
* <code>repeated uint64 coin_ids = 5;</code>
* @param index The index of the element to return.
* @return The coinIds at the given index.
*/
public long getCoinIds(int index) {
return coinIds_.getLong(index);
}
private int coinIdsMemoizedSerializedSize = -1;
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (startHeight_ != 0L) {
output.writeUInt64(1, startHeight_);
}
if (endHeight_ != 0L) {
output.writeUInt64(2, endHeight_);
}
if (height_ != 0L) {
output.writeUInt64(3, height_);
}
for (int i = 0; i < addresses_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, addresses_.getRaw(i));
}
if (getCoinIdsList().size() > 0) {
output.writeUInt32NoTag(42);
output.writeUInt32NoTag(coinIdsMemoizedSerializedSize);
}
for (int i = 0; i < coinIds_.size(); i++) {
output.writeUInt64NoTag(coinIds_.getLong(i));
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (startHeight_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeUInt64Size(1, startHeight_);
}
if (endHeight_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeUInt64Size(2, endHeight_);
}
if (height_ != 0L) {
size += com.google.protobuf.CodedOutputStream
.computeUInt64Size(3, height_);
}
{
int dataSize = 0;
for (int i = 0; i < addresses_.size(); i++) {
dataSize += computeStringSizeNoTag(addresses_.getRaw(i));
}
size += dataSize;
size += 1 * getAddressesList().size();
}
{
int dataSize = 0;
for (int i = 0; i < coinIds_.size(); i++) {
dataSize += com.google.protobuf.CodedOutputStream
.computeUInt64SizeNoTag(coinIds_.getLong(i));
}
size += dataSize;
if (!getCoinIdsList().isEmpty()) {
size += 1;
size += com.google.protobuf.CodedOutputStream
.computeInt32SizeNoTag(dataSize);
}
coinIdsMemoizedSerializedSize = dataSize;
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof counters.minter.grpc.client.FrozenAllRequest)) {
return super.equals(obj);
}
counters.minter.grpc.client.FrozenAllRequest other = (counters.minter.grpc.client.FrozenAllRequest) obj;
if (getStartHeight()
!= other.getStartHeight()) return false;
if (getEndHeight()
!= other.getEndHeight()) return false;
if (getHeight()
!= other.getHeight()) return false;
if (!getAddressesList()
.equals(other.getAddressesList())) return false;
if (!getCoinIdsList()
.equals(other.getCoinIdsList())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + START_HEIGHT_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getStartHeight());
hash = (37 * hash) + END_HEIGHT_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getEndHeight());
hash = (37 * hash) + HEIGHT_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getHeight());
if (getAddressesCount() > 0) {
hash = (37 * hash) + ADDRESSES_FIELD_NUMBER;
hash = (53 * hash) + getAddressesList().hashCode();
}
if (getCoinIdsCount() > 0) {
hash = (37 * hash) + COIN_IDS_FIELD_NUMBER;
hash = (53 * hash) + getCoinIdsList().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static counters.minter.grpc.client.FrozenAllRequest parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static counters.minter.grpc.client.FrozenAllRequest parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static counters.minter.grpc.client.FrozenAllRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static counters.minter.grpc.client.FrozenAllRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static counters.minter.grpc.client.FrozenAllRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static counters.minter.grpc.client.FrozenAllRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static counters.minter.grpc.client.FrozenAllRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static counters.minter.grpc.client.FrozenAllRequest parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static counters.minter.grpc.client.FrozenAllRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static counters.minter.grpc.client.FrozenAllRequest parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static counters.minter.grpc.client.FrozenAllRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static counters.minter.grpc.client.FrozenAllRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(counters.minter.grpc.client.FrozenAllRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code api_pb.FrozenAllRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:api_pb.FrozenAllRequest)
counters.minter.grpc.client.FrozenAllRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return counters.minter.grpc.client.Resources.internal_static_api_pb_FrozenAllRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return counters.minter.grpc.client.Resources.internal_static_api_pb_FrozenAllRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
counters.minter.grpc.client.FrozenAllRequest.class, counters.minter.grpc.client.FrozenAllRequest.Builder.class);
}
// Construct using counters.minter.grpc.client.FrozenAllRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
startHeight_ = 0L;
endHeight_ = 0L;
height_ = 0L;
addresses_ = com.google.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000001);
coinIds_ = emptyLongList();
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return counters.minter.grpc.client.Resources.internal_static_api_pb_FrozenAllRequest_descriptor;
}
@java.lang.Override
public counters.minter.grpc.client.FrozenAllRequest getDefaultInstanceForType() {
return counters.minter.grpc.client.FrozenAllRequest.getDefaultInstance();
}
@java.lang.Override
public counters.minter.grpc.client.FrozenAllRequest build() {
counters.minter.grpc.client.FrozenAllRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public counters.minter.grpc.client.FrozenAllRequest buildPartial() {
counters.minter.grpc.client.FrozenAllRequest result = new counters.minter.grpc.client.FrozenAllRequest(this);
int from_bitField0_ = bitField0_;
result.startHeight_ = startHeight_;
result.endHeight_ = endHeight_;
result.height_ = height_;
if (((bitField0_ & 0x00000001) != 0)) {
addresses_ = addresses_.getUnmodifiableView();
bitField0_ = (bitField0_ & ~0x00000001);
}
result.addresses_ = addresses_;
if (((bitField0_ & 0x00000002) != 0)) {
coinIds_.makeImmutable();
bitField0_ = (bitField0_ & ~0x00000002);
}
result.coinIds_ = coinIds_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof counters.minter.grpc.client.FrozenAllRequest) {
return mergeFrom((counters.minter.grpc.client.FrozenAllRequest)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(counters.minter.grpc.client.FrozenAllRequest other) {
if (other == counters.minter.grpc.client.FrozenAllRequest.getDefaultInstance()) return this;
if (other.getStartHeight() != 0L) {
setStartHeight(other.getStartHeight());
}
if (other.getEndHeight() != 0L) {
setEndHeight(other.getEndHeight());
}
if (other.getHeight() != 0L) {
setHeight(other.getHeight());
}
if (!other.addresses_.isEmpty()) {
if (addresses_.isEmpty()) {
addresses_ = other.addresses_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureAddressesIsMutable();
addresses_.addAll(other.addresses_);
}
onChanged();
}
if (!other.coinIds_.isEmpty()) {
if (coinIds_.isEmpty()) {
coinIds_ = other.coinIds_;
bitField0_ = (bitField0_ & ~0x00000002);
} else {
ensureCoinIdsIsMutable();
coinIds_.addAll(other.coinIds_);
}
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
counters.minter.grpc.client.FrozenAllRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (counters.minter.grpc.client.FrozenAllRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private long startHeight_ ;
/**
* <code>uint64 start_height = 1;</code>
* @return The startHeight.
*/
@java.lang.Override
public long getStartHeight() {
return startHeight_;
}
/**
* <code>uint64 start_height = 1;</code>
* @param value The startHeight to set.
* @return This builder for chaining.
*/
public Builder setStartHeight(long value) {
startHeight_ = value;
onChanged();
return this;
}
/**
* <code>uint64 start_height = 1;</code>
* @return This builder for chaining.
*/
public Builder clearStartHeight() {
startHeight_ = 0L;
onChanged();
return this;
}
private long endHeight_ ;
/**
* <code>uint64 end_height = 2;</code>
* @return The endHeight.
*/
@java.lang.Override
public long getEndHeight() {
return endHeight_;
}
/**
* <code>uint64 end_height = 2;</code>
* @param value The endHeight to set.
* @return This builder for chaining.
*/
public Builder setEndHeight(long value) {
endHeight_ = value;
onChanged();
return this;
}
/**
* <code>uint64 end_height = 2;</code>
* @return This builder for chaining.
*/
public Builder clearEndHeight() {
endHeight_ = 0L;
onChanged();
return this;
}
private long height_ ;
/**
* <code>uint64 height = 3;</code>
* @return The height.
*/
@java.lang.Override
public long getHeight() {
return height_;
}
/**
* <code>uint64 height = 3;</code>
* @param value The height to set.
* @return This builder for chaining.
*/
public Builder setHeight(long value) {
height_ = value;
onChanged();
return this;
}
/**
* <code>uint64 height = 3;</code>
* @return This builder for chaining.
*/
public Builder clearHeight() {
height_ = 0L;
onChanged();
return this;
}
private com.google.protobuf.LazyStringList addresses_ = com.google.protobuf.LazyStringArrayList.EMPTY;
private void ensureAddressesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
addresses_ = new com.google.protobuf.LazyStringArrayList(addresses_);
bitField0_ |= 0x00000001;
}
}
/**
* <code>repeated string addresses = 4;</code>
* @return A list containing the addresses.
*/
public com.google.protobuf.ProtocolStringList
getAddressesList() {
return addresses_.getUnmodifiableView();
}
/**
* <code>repeated string addresses = 4;</code>
* @return The count of addresses.
*/
public int getAddressesCount() {
return addresses_.size();
}
/**
* <code>repeated string addresses = 4;</code>
* @param index The index of the element to return.
* @return The addresses at the given index.
*/
public java.lang.String getAddresses(int index) {
return addresses_.get(index);
}
/**
* <code>repeated string addresses = 4;</code>
* @param index The index of the value to return.
* @return The bytes of the addresses at the given index.
*/
public com.google.protobuf.ByteString
getAddressesBytes(int index) {
return addresses_.getByteString(index);
}
/**
* <code>repeated string addresses = 4;</code>
* @param index The index to set the value at.
* @param value The addresses to set.
* @return This builder for chaining.
*/
public Builder setAddresses(
int index, java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureAddressesIsMutable();
addresses_.set(index, value);
onChanged();
return this;
}
/**
* <code>repeated string addresses = 4;</code>
* @param value The addresses to add.
* @return This builder for chaining.
*/
public Builder addAddresses(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureAddressesIsMutable();
addresses_.add(value);
onChanged();
return this;
}
/**
* <code>repeated string addresses = 4;</code>
* @param values The addresses to add.
* @return This builder for chaining.
*/
public Builder addAllAddresses(
java.lang.Iterable<java.lang.String> values) {
ensureAddressesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, addresses_);
onChanged();
return this;
}
/**
* <code>repeated string addresses = 4;</code>
* @return This builder for chaining.
*/
public Builder clearAddresses() {
addresses_ = com.google.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <code>repeated string addresses = 4;</code>
* @param value The bytes of the addresses to add.
* @return This builder for chaining.
*/
public Builder addAddressesBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
ensureAddressesIsMutable();
addresses_.add(value);
onChanged();
return this;
}
private com.google.protobuf.Internal.LongList coinIds_ = emptyLongList();
private void ensureCoinIdsIsMutable() {
if (!((bitField0_ & 0x00000002) != 0)) {
coinIds_ = mutableCopy(coinIds_);
bitField0_ |= 0x00000002;
}
}
/**
* <code>repeated uint64 coin_ids = 5;</code>
* @return A list containing the coinIds.
*/
public java.util.List<java.lang.Long>
getCoinIdsList() {
return ((bitField0_ & 0x00000002) != 0) ?
java.util.Collections.unmodifiableList(coinIds_) : coinIds_;
}
/**
* <code>repeated uint64 coin_ids = 5;</code>
* @return The count of coinIds.
*/
public int getCoinIdsCount() {
return coinIds_.size();
}
/**
* <code>repeated uint64 coin_ids = 5;</code>
* @param index The index of the element to return.
* @return The coinIds at the given index.
*/
public long getCoinIds(int index) {
return coinIds_.getLong(index);
}
/**
* <code>repeated uint64 coin_ids = 5;</code>
* @param index The index to set the value at.
* @param value The coinIds to set.
* @return This builder for chaining.
*/
public Builder setCoinIds(
int index, long value) {
ensureCoinIdsIsMutable();
coinIds_.setLong(index, value);
onChanged();
return this;
}
/**
* <code>repeated uint64 coin_ids = 5;</code>
* @param value The coinIds to add.
* @return This builder for chaining.
*/
public Builder addCoinIds(long value) {
ensureCoinIdsIsMutable();
coinIds_.addLong(value);
onChanged();
return this;
}
/**
* <code>repeated uint64 coin_ids = 5;</code>
* @param values The coinIds to add.
* @return This builder for chaining.
*/
public Builder addAllCoinIds(
java.lang.Iterable<? extends java.lang.Long> values) {
ensureCoinIdsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, coinIds_);
onChanged();
return this;
}
/**
* <code>repeated uint64 coin_ids = 5;</code>
* @return This builder for chaining.
*/
public Builder clearCoinIds() {
coinIds_ = emptyLongList();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:api_pb.FrozenAllRequest)
}
// @@protoc_insertion_point(class_scope:api_pb.FrozenAllRequest)
private static final counters.minter.grpc.client.FrozenAllRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new counters.minter.grpc.client.FrozenAllRequest();
}
public static counters.minter.grpc.client.FrozenAllRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<FrozenAllRequest>
PARSER = new com.google.protobuf.AbstractParser<FrozenAllRequest>() {
@java.lang.Override
public FrozenAllRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new FrozenAllRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<FrozenAllRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<FrozenAllRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public counters.minter.grpc.client.FrozenAllRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| 31.761375 | 126 | 0.654495 |
02b403812bca89dfd97135a2a3a840bb3aea2aca
| 2,096 |
package com.leammin.leetcode.medium;
import com.leammin.leetcode.util.AbstractTest;
import com.leammin.leetcode.util.ExpectedTestcase;
import com.leammin.leetcode.util.Testsuite;
/**
* @author Leammin
* @date 2020-03-15
*/
class MaxAreaOfIslandTest extends AbstractTest<MaxAreaOfIsland> {
@Override
protected Testsuite<MaxAreaOfIsland> testsuite() {
return Testsuite.<MaxAreaOfIsland>builder()
.add(ExpectedTestcase.of(t -> t.maxAreaOfIsland(new int[][]{
{0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
{0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0},
{0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0}
}), 6))
.add(ExpectedTestcase.of(t -> t.maxAreaOfIsland(new int[][]{
{0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
{0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0},
{0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0}
}), 6))
.add(ExpectedTestcase.of(t -> t.maxAreaOfIsland(new int[][]{
{0,0,0,0,0,0,0,0},
}), 0))
.add(ExpectedTestcase.of(t -> t.maxAreaOfIsland(new int[][]{
{1, 1, 0, 0, 0},
{1, 1, 0, 0, 0},
{0, 0, 0, 1, 1},
{0, 0, 0, 1, 1}
}), 4))
.build();
}
}
| 45.565217 | 76 | 0.354485 |
1e0188b3bcfe7ac4a6f5b435ebae85cc0cd2e85a
| 983 |
package Easy.E301_400;
/**
* Given a positive integer num, write a function which returns True if num is a perfect square else False.
* https://leetcode.com/submissions/detail/187746270/
* 此题关键为将int转化为long然后二分
* Created by liuxiang on 2018/11/6.
*/
public class E367_Valid_Perfect_Square {
public static void main(String[] args) {
int num = 808201;
boolean result = isPerfectSquare(num);
System.out.println(result);
}
public static boolean isPerfectSquare(int num) {
if (num == 1) {
return true;
}
long begin = 1;
long end = num / 2;
long nums = (long)num;
while (begin <= end) {
long mid = (end - begin) / 2 + begin;
if (mid * mid == nums) {
return true;
} else if (mid * mid < nums) {
begin = mid + 1;
} else {
end = mid - 1;
}
}
return false;
}
}
| 25.868421 | 107 | 0.525941 |
87d8f4d988102285e85ca9a115a4f01d9980fb26
| 13,174 |
/*
* OpenRemote, the Home of the Digital Home.
* Copyright 2008-2012, OpenRemote Inc.
*
* See the contributors.txt file in the distribution for a
* full listing of individual contributors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.openremote.controller.utils;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.ConsoleHandler;
import java.util.logging.LogRecord;
import org.openremote.controller.Constants;
/**
* This is a facade for the java.util.logging API to provide additional convenience methods that
* closely matches those used in log4j API. <p>
*
* Classes in controller implementation should use this API for maximum portability and to reduce
* direct compile-time dependencies to third party libraries. <p>
*
* Logging categories should be child groups of
* {@link org.openremote.controller.Constants#CONTROLLER_ROOT_LOG_CATEGORY}.
*
* @author <a href="mailto:juha@openremote.org">Juha Lindfors</a>
*/
public class Logger extends java.util.logging.Logger
{
/**
* Reference to the global JUL log manager.
*/
private static LogManager logManager = LogManager.getLogManager();
/**
* Returns a logger instance registered with a global java.util.logging LogManager. <p>
*
* This instance provides additional convenience API on top of the default
* java.util.logging.Logger API to make it easier to switch implementations between JUL
* and Log4j.
*
* @param name A log category name. This should always be a subcategory of
* {@link Constants#CONTROLLER_ROOT_LOG_CATEGORY}.
*
* @return A JUL Logger subclass with additional convenience API for logging.
*/
public static Logger getLogger(String name)
{
// Sanity check and warn of suspicious use pattern...
if (!name.startsWith(Constants.CONTROLLER_ROOT_LOG_CATEGORY))
{
java.util.logging.Logger.getLogger("").warning(
"Log category '" + name + "' is not using parent log category " +
Constants.CONTROLLER_ROOT_LOG_CATEGORY + ". The logging behavior may not be " +
"what was expected."
);
}
Logger l = new Logger(name);
logManager.addLogger(l);
try
{
return (Logger)logManager.getLogger(name);
}
catch (ClassCastException e)
{
System.err.println(
"\n\n" +
"---------------------------------------------------------------------------------\n\n" +
" An incompatible logger was already associated " +
" with category '" + name + "'.\n\n" +
" Logging to this category is unlikely to work as intended.\n\n" +
"---------------------------------------------------------------------------------\n\n"
);
// The logging is unlikely to work but return a valid reference anyway to avoid
// NPE's and such...
l.addHandler(new ConsoleHandler());
return l;
}
}
// Constructors ---------------------------------------------------------------------------------
/**
* Private constructor accessed from {@link #getLogger(String)}
*
* @param name log category name
*/
private Logger(String name)
{
super(name, null /* no localization */);
}
// Public Instance Methods ----------------------------------------------------------------------
/**
* Synonymous to using {@link java.util.logging.Logger#severe}.
*
* Further, {@link org.openremote.controller.bootstrap.Startup#redirectJULtoLog4j()} maps
* JUL {@link java.util.logging.Level#SEVERE} to log4j <tt>ERROR</tt> priority.
*
* @param msg log message
*/
public void error(String msg)
{
super.log(Level.SEVERE, msg);
}
/**
* Same as {@link #error} but allows parameterized log messages.
*
* @param msg log message
* @param params log message parameters -- message parameterization must be compatible with
* {@link java.text.MessageFormat} API
*
* @see java.text.MessageFormat
*/
public void error(String msg, Object... params)
{
super.log(Level.SEVERE, msg, params);
}
/**
* Same as {@link #error} with an additional exception stack trace added to the logging record.
*
* @param msg log message
* @param throwable exception or error associated with the log message
*/
public void error(String msg, Throwable throwable)
{
super.log(Level.SEVERE, msg, throwable);
}
/**
* Same as {@link #error} with an additional exception stack trace and message parameterization
* added to the logging record.
*
* @param msg log message
* @param throwable exception or error associated with the log message
* @param params log message parameters -- message parameterization must be compatible with
* {@link java.text.MessageFormat} API
*
* @see java.text.MessageFormat
*/
public void error(String msg, Throwable throwable, Object... params)
{
LogRecord record = new LogRecord(Level.SEVERE, msg);
record.setThrown(throwable);
record.setParameters(params);
record.setLoggerName(getName());
super.log(record);
}
// Warning Logging ------------------------------------------------------------------------------
/**
* Synonymous to using {@link java.util.logging.Logger#warning}.
*
* @param msg log message
*/
public void warn(String msg)
{
super.log(Level.WARNING, msg);
}
/**
* Same as {@link #warn} but allows parameterized log messages.
*
* @param msg log message
* @param params log message parameters -- message parameterization must be compatible with
* {@link java.text.MessageFormat} API
*
* @see java.text.MessageFormat
*/
public void warn(String msg, Object... params)
{
super.log(Level.WARNING, msg, params);
}
/**
* Same as {@link #warn} with an additional exception stack trace added to the logging record.
*
* @param msg log message
* @param throwable exception or error associated with the log message
*/
public void warn(String msg, Throwable throwable)
{
super.log(Level.WARNING, msg, throwable);
}
/**
* Same as {@link #warn} with an additional exception stack trace and message parameterization
* added to the logging record.
*
* @param msg log message
* @param throwable exception or error associated with the log message
* @param params log message parameters -- message parameterization must be compatible with
* {@link java.text.MessageFormat} API
*
* @see java.text.MessageFormat
*/
public void warn(String msg, Throwable throwable, Object... params)
{
LogRecord record = new LogRecord(Level.WARNING, msg);
record.setThrown(throwable);
record.setParameters(params);
record.setLoggerName(getName());
super.log(record);
}
// Info Logging ---------------------------------------------------------------------------------
/**
* Synonymous to using {@link java.util.logging.Logger#info(String)}.
*
* Further, {@link org.openremote.controller.bootstrap.Startup#redirectJULtoLog4j()} maps
* JUL {@link java.util.logging.Level#INFO} to log4j <tt>INFO</tt> priority.
*
* @param msg log message
*/
public void info(String msg)
{
super.log(Level.INFO, msg);
}
/**
* Same as {@link #info} but allows parameterized log messages.
*
* @param msg log message
* @param params log message parameters -- message parameterization must be compatible with
* {@link java.text.MessageFormat} API
*
* @see java.text.MessageFormat
*/
public void info(String msg, Object... params)
{
super.log(Level.INFO, msg, params);
}
/**
* Same as {@link #info} with an additional exception stack trace added to the logging record.
*
* @param msg log message
* @param throwable exception or error associated with the log message
*/
public void info(String msg, Throwable throwable)
{
super.log(Level.INFO, msg, throwable);
}
/**
* Same as {@link #info} with an additional exception stack trace and message parameterization
* added to the logging record.
*
* @param msg log message
* @param throwable exception or error associated with the log message
* @param params log message parameters -- message parameterization must be compatible with
* {@link java.text.MessageFormat} API
*
* @see java.text.MessageFormat
*/
public void info(String msg, Throwable throwable, Object... params)
{
LogRecord record = new LogRecord(Level.INFO, msg);
record.setThrown(throwable);
record.setParameters(params);
record.setLoggerName(getName());
super.log(record);
}
// Debug Logging --------------------------------------------------------------------------------
/**
* Synonymous to using {@link java.util.logging.Logger#fine}.
*
* Further, {@link org.openremote.controller.bootstrap.Startup#redirectJULtoLog4j()} maps
* JUL {@link java.util.logging.Level#FINE} to log4j <tt>DEBUG</tt> priority.
*
* @param msg log message
*/
public void debug(String msg)
{
super.log(Level.FINE, msg);
}
/**
* Same as {@link #debug} but allows parameterized log messages.
*
* @param msg log message
* @param params log message parameters -- message parameterization must be compatible with
* {@link java.text.MessageFormat} API
*
* @see java.text.MessageFormat
*/
public void debug(String msg, Object... params)
{
super.log(Level.FINE, msg, params);
}
/**
* Same as {@link #debug} with an additional exception stack trace added to the logging record.
*
* @param msg log message
* @param throwable exception or error associated with the log message
*/
public void debug(String msg, Throwable throwable)
{
super.log(Level.FINE, msg, throwable);
}
/**
* Same as {@link #debug} with an additional exception stack trace and message parameterization
* added to the logging record.
*
* @param msg log message
* @param throwable exception or error associated with the log message
* @param params log message parameters -- message parameterization must be compatible with
* {@link java.text.MessageFormat} API
*
* @see java.text.MessageFormat
*/
public void debug(String msg, Throwable throwable, Object... params)
{
LogRecord record = new LogRecord(Level.FINE, msg);
record.setThrown(throwable);
record.setParameters(params);
record.setLoggerName(getName());
super.log(record);
}
// Trace Logging --------------------------------------------------------------------------------
/**
* Synonymous to using {@link java.util.logging.Logger#finer}.
*
* @param msg log message
*/
public void trace(String msg)
{
super.log(Level.FINER, msg);
}
/**
* Same as {@link #trace} but allows parameterized log messages.
*
* @param msg log message
* @param params log message parameters -- message parameterization must be compatible with
* {@link java.text.MessageFormat} API
*
* @see java.text.MessageFormat
*/
public void trace(String msg, Object... params)
{
super.log(Level.FINER, msg, params);
}
/**
* Same as {@link #trace} with an additional exception stack trace added to the logging record.
*
* @param msg log message
* @param throwable exception or error associated with the log message
*/
public void trace(String msg, Throwable throwable)
{
super.log(Level.FINER, msg, throwable);
}
/**
* Same as {@link #trace} with an additional exception stack trace and message parameterization
* added to the logging record.
*
* @param msg log message
* @param throwable exception or error associated with the log message
* @param params log message parameters -- message parameterization must be compatible with
* {@link java.text.MessageFormat} API
*
* @see java.text.MessageFormat
*/
public void trace(String msg, Throwable throwable, Object... params)
{
LogRecord record = new LogRecord(Level.FINER, msg);
record.setThrown(throwable);
record.setParameters(params);
record.setLoggerName(getName());
super.log(record);
}
}
| 30.637209 | 99 | 0.62927 |
9562755ec380575be85542cb9c7b76c3040c2ce7
| 506 |
package com.daiwj.invoker.demo.okhttp.extra;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class TestRequestInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request oldRequest = chain.request();
Request.Builder builder = oldRequest.newBuilder();
builder.addHeader("Connection", "close");
return chain.proceed(builder.build());
}
}
| 23 | 63 | 0.727273 |
64e7d8f79445aaaf284cd0942ce74c369f70e0c3
| 1,351 |
/*============================================================* /
* UPI: enau831 *
* ID: 768485633 *
* NAME: Etienne Naude *
* *
* File: MovingCircle *
* Decription: class for MovingCircle objects *
/*============================================================*/
import java.awt.*;
public class MovingCircle extends MovingEllipse{
Point center = new Point();
/*======Constructors======*/
MovingCircle(int x, int y,int size, int marginX, int marginY,Color fill, Color border, int path){
super(x,y,size,size,marginX,marginY,fill,border,path);
center.setLocation(x+width/2,y+height/2);}
MovingCircle(){
this(0,0,50,50,50,Color.pink,Color.blue,0);}
MovingCircle(int size){
this(0,0,size,size,size,Color.pink,Color.blue,0);}
/*======Accessors and mutators======*/
public void setWidth(int nee){
if(nee<width){
width =nee;height =nee;
}else
height =width;
}
public void setHeight(int nee){
if(nee<width){
width =nee;height =nee;
}else
height =width;
}
}
| 40.939394 | 101 | 0.427831 |
0b56c56bb7d7688a976a640aa520ce2acf1eba97
| 730 |
class Solution {
public String XXX(String[] strs) {
// 默认前缀
String prefix = strs[0];
String pubPrefix = "";
// 按前缀顺序匹配
for (int i = 0; i < prefix.length(); i++) {
char c = prefix.charAt(i);
boolean flag = false;
for (int j = 0; j < strs.length; j++) {
// 如果当前的词出现不相等,结束内循环并标记结束外循环
if (i>strs[j].length()-1 || c != strs[j].charAt(i)) {
flag = true;
break;
}
}
// 结束外循环
if (flag) {
break;
}
pubPrefix = pubPrefix + new String(new char[]{c});
}
return pubPrefix;
}
}
| 27.037037 | 70 | 0.394521 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.