code
stringlengths
5
1.04M
repo_name
stringlengths
7
108
path
stringlengths
6
299
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1.04M
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.uiserver.internal.deployment.msf4j; import org.osgi.framework.ServiceRegistration; import org.testng.Assert; import org.testng.annotations.Test; import org.wso2.carbon.uiserver.internal.http.HttpTransport; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Test cases for {@link MicroserviceRegistration} class. * * @since 0.15.0 */ public class MicroserviceRegistrationTest { @Test @SuppressWarnings("unchecked") public void testGetRegisteredHttpTransport() { HttpTransport httpTransport = createHttpTransport(); ServiceRegistration serviceRegistration = mock(ServiceRegistration.class); MicroserviceRegistration microserviceRegistration = new MicroserviceRegistration(httpTransport, serviceRegistration); Assert.assertEquals(microserviceRegistration.getRegisteredHttpTransport(), httpTransport); } @Test @SuppressWarnings("unchecked") public void testUnregister() { HttpTransport httpTransport = createHttpTransport(); ServiceRegistration serviceRegistration = mock(ServiceRegistration.class); new MicroserviceRegistration(httpTransport, serviceRegistration).unregister(); verify(serviceRegistration).unregister(); } private static HttpTransport createHttpTransport() { return new HttpTransport("foo", "bar", "http", "localhost", 9292); } }
this/carbon-ui-server
components/org.wso2.carbon.uiserver/src/test/java/org/wso2/carbon/uiserver/internal/deployment/msf4j/MicroserviceRegistrationTest.java
Java
apache-2.0
2,191
package com.example.google.playservices.placepicker.cardstream; import android.os.Bundle; import android.support.v4.app.Fragment; public class StreamRetentionFragment extends Fragment { CardStreamState mState; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setRetainInstance(true); } public void storeCardStream(CardStreamState state) { mState = state; } public CardStreamState getCardStream() { return mState; } }
swapnanil/GooglePlacesAPIpractice
Application/src/main/java/com/example/google/playservices/placepicker/cardstream/StreamRetentionFragment.java
Java
apache-2.0
552
/*- * #%L * Slice - Mapper API * %% * Copyright (C) 2012 Cognifide Limited * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.cognifide.slice.mapper.api.processor; /** * Its purpose is to add a possibility to register custom processors with defined priority. Objects of this * class should be registered with Guice's multibindings. <br/> * The priority parameter is used to sort processors. Processors with higher priority will take precedence * over those with lower prioroty. Notice that all {@link PriorityFieldProcessor}s always take precedence over * any other {@link FieldProcessor}s. * * @author maciej.dybek */ public interface PriorityFieldProcessor extends FieldProcessor, PriorityProcessor { }
Sivaramvt/Slice
slice-mapper-api/src/main/java/com/cognifide/slice/mapper/api/processor/PriorityFieldProcessor.java
Java
apache-2.0
1,254
package cn.addapp.pickers.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.os.Build; import android.os.Handler; import android.text.TextUtils; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.view.GestureDetector; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import java.util.Locale; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import cn.addapp.pickers.adapter.WheelAdapter; import cn.addapp.pickers.common.InertiaTimerTask; import cn.addapp.pickers.common.LineConfig; import cn.addapp.pickers.common.MessageHandler; import cn.addapp.pickers.common.OnItemPickedRunnable; import cn.addapp.pickers.common.SmoothScrollTimerTask; import cn.addapp.pickers.listeners.OnItemPickListener; import cn.addapp.pickers.listeners.WheelViewGestureListener; import cn.addapp.pickers.model.IPickerViewData; import cn.addapp.pickers.wheelpicker.R; /** * 3d滚轮控件 * @author matt * blog: addapp.cn */ public class WheelView extends View { public enum ACTION { // 点击,滑翔(滑到尽头),拖拽事件 CLICK, FLING, DRAG } private LineConfig lineConfig = null;//分割线配置 private LineConfig.DividerType dividerType;//分隔线类型 Context context; public Handler handler; private GestureDetector gestureDetector;//控制滑动 private OnItemPickListener onItemPickListener; private boolean isOptions = false; private boolean isCenterLabel = true; // Timer mTimer; ScheduledExecutorService mExecutor = Executors.newSingleThreadScheduledExecutor(); private ScheduledFuture<?> mFuture; Paint paintOuterText; Paint paintCenterText; Paint paintLine; WheelAdapter adapter; private String label;//附加单位 public int textSize;//选项的文字大小 public int maxTextWidth; public int maxTextHeight; public float itemHeight;//每行高度 Typeface typeface = Typeface.MONOSPACE;//字体样式,默认是等宽字体 int textColorOut = 0xFFa8a8a8; int textColorCenter = 0xFF2a2a2a; int dividerColor = 0xFFd5d5d5; // 条目间距倍数 float lineSpacingMultiplier = 1.6F; public boolean isLoop; // 第一条线Y坐标值 float firstLineY; //第二条线Y坐标 float secondLineY; //中间label绘制的Y坐标 float centerY; //滚动总高度y值 public float totalScrollY; //初始化默认选中项 public int initPosition; //选中的Item private String selectedItem; //选中的Item是第几个 private int selectedPosition; int preCurrentIndex; //滚动偏移值,用于记录滚动了多少个item int change; // 绘制几个条目,实际上第一项和最后一项Y轴压缩成0%了,所以可见的数目实际为9 int itemsVisible = 11; int measuredHeight;// WheelView 控件高度 int measuredWidth;// WheelView 控件宽度 // 半圆周长 int halfCircumference; // 半径 int radius; private int mOffset = 0; private float previousY = 0; long startTime = 0; // 修改这个值可以改变滑行速度 private static final int VELOCITY_FLING = 15; int widthMeasureSpec,heightMeasureSpec; private int mGravity = Gravity.CENTER; private int drawCenterContentStart = 0;//中间选中文字开始绘制位置 private int drawOutContentStart = 0;//非中间文字开始绘制位置 private static final float SCALE_CONTENT = 0.8F;//非中间文字则用此控制高度,压扁形成3d错觉 private float centerContentOffset ;//偏移量 public WheelView(Context context) { this(context, null); } public WheelView(Context context, AttributeSet attrs) { super(context, attrs); textSize = getResources().getDimensionPixelSize(R.dimen.view_text_size);//默认大小 DisplayMetrics dm = getResources().getDisplayMetrics(); float density = dm.density; // 屏幕密度(0.75/1.0/1.5/2.0/3.0) if (density<1){//根据密度不同进行适配 centerContentOffset=2.4F; }else if (1<=density&&density<2){ centerContentOffset = 3.6F; }else if (1<=density&&density<2){ centerContentOffset = 4.5F; }else if (2<=density&&density<3){ centerContentOffset = 6.0F; }else if (density>=3){ centerContentOffset= density * 2.5F; } if (attrs != null) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LoopView, 0, 0); mGravity = a.getInt(R.styleable.LoopView_view_gravity, Gravity.CENTER); textColorOut = a.getColor(R.styleable.LoopView_topBottomTextColor, textColorOut); textColorCenter = a.getColor(R.styleable.LoopView_centerTextColor, textColorCenter); dividerColor = a.getColor(R.styleable.LoopView_lineColor, dividerColor); textSize = a.getDimensionPixelOffset(R.styleable.LoopView_textSize, textSize); lineSpacingMultiplier = a.getFloat(R.styleable.LoopView_lineSpacingMultiplier, lineSpacingMultiplier); a.recycle();//回收内存 } judgeLineSpae(); initLoopView(context); } /** * 判断间距是否在1.0-2.0之间 */ private void judgeLineSpae() { if (lineSpacingMultiplier < 1.2f) { lineSpacingMultiplier = 1.2f; } else if (lineSpacingMultiplier > 2.0f) { lineSpacingMultiplier = 2.0f; } } private void initLoopView(Context context) { this.context = context; handler = new MessageHandler(this); gestureDetector = new GestureDetector(context, new WheelViewGestureListener(this)); gestureDetector.setIsLongpressEnabled(false); isLoop = true; totalScrollY = 0; initPosition = -1; initPaints(); } private void initPaints() { paintOuterText = new Paint(); paintOuterText.setColor(textColorOut); paintOuterText.setAntiAlias(true); paintOuterText.setTypeface(typeface); paintOuterText.setTextSize(textSize); paintCenterText = new Paint(); paintCenterText.setColor(textColorCenter); paintCenterText.setAntiAlias(true); paintCenterText.setTextScaleX(1.1F); paintCenterText.setTypeface(typeface); paintCenterText.setTextSize(textSize); paintLine = new Paint(); paintLine.setColor(dividerColor); paintLine.setAntiAlias(true); if(lineConfig==null){ lineConfig = new LineConfig(); paintLine.setColor(lineConfig.getColor()); paintLine.setAlpha(lineConfig.getAlpha()); paintLine.setStrokeWidth(lineConfig.getThick()); } if (Build.VERSION.SDK_INT >= 11) { setLayerType(LAYER_TYPE_SOFTWARE, null); } } private void remeasure() {//重新测量 if (adapter == null) { return; } int widthSize = MeasureSpec.getSize(widthMeasureSpec); // int heightSize = MeasureSpec.getSize(heightMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); // int heightMode = MeasureSpec.getMode(heightMeasureSpec); measureTextWidthHeight(); //半圆的周长 = item高度乘以item数目-1 halfCircumference = (int) (itemHeight * (itemsVisible - 1)); //整个圆的周长除以PI得到直径,这个直径用作控件的总高度 measuredHeight = (int) ((halfCircumference * 2) / Math.PI); //求出半径 radius = (int) (halfCircumference / Math.PI); //控件宽度,这里支持weight int diffWidth = 10; measuredWidth = maxTextWidth+diffWidth;//加上diffWidth 线的长度就比文本长diffWidth measuredWidth = measureSize(widthMode,widthSize,measuredWidth); //计算两条横线 和 选中项画笔的基线Y位置 firstLineY = (measuredHeight - itemHeight) / 2.0F; secondLineY = (measuredHeight + itemHeight) / 2.0F; centerY = secondLineY - (itemHeight-maxTextHeight)/2.0f - centerContentOffset; //初始化显示的item的position if (initPosition == -1) { if (isLoop) { initPosition = (adapter.getItemsCount() + 1) / 2; } else { initPosition = 0; } } preCurrentIndex = initPosition; } private int measureSize(int mode, int sizeExpect, int sizeActual) { // MeasureSpec.getMode()方法返回的结果有三种: // UNSPECIFIED:父节点对子节点的大小没有任何要求。 // EXACTLY: 父节点要求其子节点的大小指定为某个确切的值。其子节点以及其他子孙节点都需要适应该大小。 // AT MOST:父节点要求其子节点的大小不能超过某个最大值,其子节点以及其他子孙节点的大小都需要小于这个值 int realSize; if (mode == MeasureSpec.EXACTLY) { realSize = sizeExpect; } else { realSize = sizeActual; if (mode == MeasureSpec.AT_MOST) realSize = Math.min(realSize, sizeExpect); } return realSize; } /** * 计算最大length的Text的宽高度 */ private void measureTextWidthHeight() { Rect rect = new Rect(); for (int i = 0; i < adapter.getItemsCount(); i++) { String s1 = getContentText(adapter.getItem(i)); paintCenterText.getTextBounds(s1, 0, s1.length(), rect); int textWidth = rect.width(); if (textWidth > maxTextWidth) { maxTextWidth = textWidth; } paintCenterText.getTextBounds("\u661F\u671F", 0, 2, rect); // 星期的字符编码(以它为标准高度) maxTextHeight = rect.height() + 2; } itemHeight = lineSpacingMultiplier * maxTextHeight; } public void smoothScroll(ACTION action) {//平滑滚动的实现 cancelFuture(); if (action == ACTION.FLING || action == ACTION.DRAG) { mOffset = (int) ((totalScrollY % itemHeight + itemHeight) % itemHeight); if ((float) mOffset > itemHeight / 2.0F) {//如果超过Item高度的一半,滚动到下一个Item去 mOffset = (int) (itemHeight - (float) mOffset); } else { mOffset = -mOffset; } } //停止的时候,位置有偏移,不是全部都能正确停止到中间位置的,这里把文字位置挪回中间去 mFuture = mExecutor.scheduleWithFixedDelay(new SmoothScrollTimerTask(this, mOffset), 0, 10, TimeUnit.MILLISECONDS); } public final void scrollBy(float velocityY) {//滚动惯性的实现 cancelFuture(); mFuture = mExecutor.scheduleWithFixedDelay(new InertiaTimerTask(this, velocityY), 0, VELOCITY_FLING, TimeUnit.MILLISECONDS); } public void cancelFuture() { if (mFuture != null && !mFuture.isCancelled()) { mFuture.cancel(true); mFuture = null; } } /** * 设置是否循环滚动 * * @param canLoop 是否循环 */ public final void setCanLoop(boolean canLoop) { isLoop = canLoop; } public final void setTypeface(Typeface font) { typeface = font; paintOuterText.setTypeface(typeface); paintCenterText.setTypeface(typeface); } public final void setTextSize(float size) { if (size > 0.0F ) { textSize = (int) (context.getResources().getDisplayMetrics().density * size); paintOuterText.setTextSize(textSize); paintCenterText.setTextSize(textSize); } } public final void setCurrentItem(int currentItem) { this.initPosition = currentItem; totalScrollY = 0;//回归顶部,不然重设setCurrentItem的话位置会偏移的,就会显示出不对位置的数据 invalidate(); } public final void setOnItemPickListener(OnItemPickListener onItemPickListener) { this.onItemPickListener = onItemPickListener; } public final void setAdapter(WheelAdapter adapter) { this.adapter = adapter; remeasure(); invalidate(); } public final WheelAdapter getAdapter() { return adapter; } public final int getCurrentPosition() { return selectedPosition; } public final String getCurrentItem() { selectedItem = (String) adapter.getItem(selectedPosition); return selectedItem; } //handler 里调用 public final void onItemPicked() { if (onItemPickListener != null) { postDelayed(new OnItemPickedRunnable(this,onItemPickListener), 200L); } } @Override protected void onDraw(Canvas canvas) { if (adapter == null) { return; } //可见的item数组 Object drawItemCount[] = new Object[itemsVisible]; //滚动的Y值高度除去每行Item的高度,得到滚动了多少个item,即change数 change = (int)(totalScrollY / itemHeight); try { //滚动中实际的预选中的item(即经过了中间位置的item) = 滑动前的位置 + 滑动相对位置 preCurrentIndex = initPosition + change % adapter.getItemsCount(); } catch (ArithmeticException e) { Log.e("WheelView","出错了!adapter.getItemsCount() == 0,联动数据不匹配"); } if (!isLoop) {//不循环的情况 if (preCurrentIndex < 0) { preCurrentIndex = 0; } if (preCurrentIndex > adapter.getItemsCount() - 1) { preCurrentIndex = adapter.getItemsCount() - 1; } } else {//循环 if (preCurrentIndex < 0) {//举个例子:如果总数是5,preCurrentIndex = -1,那么preCurrentIndex按循环来说,其实是0的上面,也就是4的位置 preCurrentIndex = adapter.getItemsCount() + preCurrentIndex; } if (preCurrentIndex > adapter.getItemsCount() - 1) {//同理上面,自己脑补一下 preCurrentIndex = preCurrentIndex - adapter.getItemsCount(); } } //跟滚动流畅度有关,总滑动距离与每个item高度取余,即并不是一格格的滚动,每个item不一定滚到对应Rect里的,这个item对应格子的偏移值 float itemHeightOffset = (totalScrollY % itemHeight); // 设置数组中每个元素的值 int counter = 0; while (counter < itemsVisible) { int index = preCurrentIndex - (itemsVisible / 2 - counter);//索引值,即当前在控件中间的item看作数据源的中间,计算出相对源数据源的index值 //判断是否循环,如果是循环数据源也使用相对循环的position获取对应的item值,如果不是循环则超出数据源范围使用""空白字符串填充,在界面上形成空白无数据的item项 if (isLoop) { index = getLoopMappingIndex(index); drawItemCount[counter] = adapter.getItem(index); } else if (index < 0) { drawItemCount[counter] = ""; } else if (index > adapter.getItemsCount() - 1) { drawItemCount[counter] = ""; } else { drawItemCount[counter] = adapter.getItem(index); } counter++; } //设置线可见时绘制两条线 if(lineConfig.isVisible()){ //绘制中间两条横线 if (dividerType == LineConfig.DividerType.WRAP){//横线长度仅包裹内容 float startX; float endX; if (TextUtils.isEmpty(label)){//隐藏Label的情况 startX = (measuredWidth - maxTextWidth)/2 - 12; }else { startX = (measuredWidth - maxTextWidth)/4 - 12; } if (startX<=0){//如果超过了WheelView的边缘 startX = 10; } endX = measuredWidth - startX; canvas.drawLine(startX, firstLineY, endX, firstLineY, paintLine); canvas.drawLine(startX, secondLineY, endX, secondLineY, paintLine); }else { canvas.drawLine(0.0F, firstLineY, measuredWidth, firstLineY, paintLine); canvas.drawLine(0.0F, secondLineY, measuredWidth, secondLineY, paintLine); } } //只显示选中项Label文字的模式,并且Label文字不为空,则进行绘制 if (!TextUtils.isEmpty(label)&& isCenterLabel) { //绘制文字,靠右并留出空隙 int drawRightContentStart = measuredWidth - getTextWidth(paintCenterText, label); canvas.drawText(label, drawRightContentStart - centerContentOffset, centerY, paintCenterText); } counter = 0; while (counter < itemsVisible) { canvas.save(); // 弧长 L = itemHeight * counter - itemHeightOffset // 求弧度 α = L / r (弧长/半径) [0,π] double radian = ((itemHeight * counter - itemHeightOffset)) / radius; // 弧度转换成角度(把半圆以Y轴为轴心向右转90度,使其处于第一象限及第四象限 // angle [-90°,90°] float angle = (float) (90D - (radian / Math.PI) * 180D);//item第一项,从90度开始,逐渐递减到 -90度 // 计算取值可能有细微偏差,保证负90°到90°以外的不绘制 if (angle >= 90F || angle <= -90F) { canvas.restore(); } else { //获取内容文字 String contentText; //如果是label每项都显示的模式,并且item内容不为空、label 也不为空 if(!isCenterLabel&&!TextUtils.isEmpty(label) &&!TextUtils.isEmpty(getContentText(drawItemCount[counter]))){ contentText = getContentText(drawItemCount[counter])+label; }else { contentText = getContentText(drawItemCount[counter]); } reMeasureTextSize(contentText); //计算开始绘制的位置 // measuredCenterContentStart(contentText); // measuredOutContentStart(contentText); drawCenterContentStart = measureContentStart(paintCenterText,contentText); drawOutContentStart = measureContentStart(paintOuterText,contentText); float translateY = (float) (radius - Math.cos(radian) * radius - (Math.sin(radian) * maxTextHeight) / 2D); //根据Math.sin(radian)来更改canvas坐标系原点,然后缩放画布,使得文字高度进行缩放,形成弧形3d视觉差 canvas.translate(0.0F, translateY); canvas.scale(1.0F, (float) Math.sin(radian)); if (translateY <= firstLineY && maxTextHeight + translateY >= firstLineY) { // 条目经过第一条线 canvas.save(); canvas.clipRect(0, 0, measuredWidth, firstLineY - translateY); canvas.scale(1.0F, (float) Math.sin(radian) * SCALE_CONTENT); canvas.drawText(contentText, drawOutContentStart, maxTextHeight, paintOuterText); canvas.restore(); canvas.save(); canvas.clipRect(0, firstLineY - translateY, measuredWidth, (int) (itemHeight)); canvas.scale(1.0F, (float) Math.sin(radian) * 1.0F); canvas.drawText(contentText, drawCenterContentStart, maxTextHeight - centerContentOffset, paintCenterText); canvas.restore(); } else if (translateY <= secondLineY && maxTextHeight + translateY >= secondLineY) { // 条目经过第二条线 canvas.save(); canvas.clipRect(0, 0, measuredWidth, secondLineY - translateY); canvas.scale(1.0F, (float) Math.sin(radian) * 1.0F); canvas.drawText(contentText, drawCenterContentStart, maxTextHeight - centerContentOffset, paintCenterText); canvas.restore(); canvas.save(); canvas.clipRect(0, secondLineY - translateY, measuredWidth, (int) (itemHeight)); canvas.scale(1.0F, (float) Math.sin(radian) * SCALE_CONTENT); canvas.drawText(contentText, drawOutContentStart, maxTextHeight, paintOuterText); canvas.restore(); } else if (translateY >= firstLineY && maxTextHeight + translateY <= secondLineY) { // 中间条目 //canvas.clipRect(0, 0, measuredWidth, maxTextHeight); //让文字居中 float Y = maxTextHeight - centerContentOffset;//因为圆弧角换算的向下取值,导致角度稍微有点偏差,加上画笔的基线会偏上,因此需要偏移量修正一下 canvas.drawText(contentText, drawCenterContentStart, Y, paintCenterText); selectedPosition= adapter.indexOf(drawItemCount[counter]); } else { // 其他条目 canvas.save(); canvas.clipRect(0, 0, measuredWidth, (int) (itemHeight)); canvas.scale(1.0F, (float) Math.sin(radian) * SCALE_CONTENT); canvas.drawText(contentText, drawOutContentStart, maxTextHeight, paintOuterText); canvas.restore(); } canvas.restore(); paintCenterText.setTextSize(textSize); } counter++; } } /** * 根据文字的长度 重新设置文字的大小 让其能完全显示 * @param contentText */ private void reMeasureTextSize(String contentText) { Rect rect = new Rect(); paintCenterText.getTextBounds(contentText, 0, contentText.length(), rect); int width = rect.width(); int size = textSize; while (width > measuredWidth) { size--; //设置2条横线中间的文字大小 paintCenterText.setTextSize(size); paintCenterText.getTextBounds(contentText, 0, contentText.length(), rect); width = rect.width(); } //设置2条横线外面的文字大小 paintOuterText.setTextSize(size); } //递归计算出对应的index private int getLoopMappingIndex(int index) { if (index < 0) { index = index + adapter.getItemsCount(); index = getLoopMappingIndex(index); } else if (index > adapter.getItemsCount() - 1) { index = index - adapter.getItemsCount(); index = getLoopMappingIndex(index); } return index; } /** * 根据传进来的对象获取getPickerViewText()方法,来获取需要显示的值 * * @param item 数据源的item * @return 对应显示的字符串 */ private String getContentText(Object item) { if (item == null) { return ""; } else if (item instanceof IPickerViewData) { return ((IPickerViewData) item).getPickerViewText(); } else if (item instanceof Integer) { //如果为整形则最少保留两位数. return String.format(Locale.getDefault(), "%02d", (int) item); } return item.toString(); } /** * 根据文本width动态画出文本的左右padding * */ private int measureContentStart(Paint paint,String text){ int baselineX = (measuredWidth - measureTextWidth(paint,text)) / 2; return baselineX - 4; } /** * 动态获取文本width * */ private int measureTextWidth(Paint paint,String text){ Rect rect = getRect(paint,text); int textWidth = rect.width(); if (textWidth > maxTextWidth) { maxTextWidth = textWidth; return maxTextWidth; } return textWidth; } private Rect getRect(Paint paint,String text){ Rect rect = new Rect(); paint.getTextBounds(text, 0, text.length(), rect); return rect; } private void measuredCenterContentStart(String content) { Rect rect = new Rect(); paintCenterText.getTextBounds(content, 0, content.length(), rect); switch (mGravity) { case Gravity.CENTER://显示内容居中 if (isOptions||label == null|| label.equals("")||!isCenterLabel) { drawCenterContentStart = (int) ((measuredWidth - rect.width()) * 0.5)-4; } else {//只显示中间label时,时间选择器内容偏左一点,留出空间绘制单位标签 drawCenterContentStart = (int) ((measuredWidth - rect.width()) * 0.25)-4; } break; case Gravity.LEFT: drawCenterContentStart = 0; break; case Gravity.RIGHT://添加偏移量 drawCenterContentStart = measuredWidth - rect.width() -(int)centerContentOffset; break; } } private void measuredOutContentStart(String content) { Rect rect = new Rect(); paintOuterText.getTextBounds(content, 0, content.length(), rect); switch (mGravity) { case Gravity.CENTER: if (isOptions||label == null|| label.equals("")||!isCenterLabel) { drawOutContentStart = (int) ((measuredWidth - rect.width()) * 0.5); } else {//只显示中间label时,时间选择器内容偏左一点,留出空间绘制单位标签 drawOutContentStart = (int) ((measuredWidth - rect.width()) * 0.25); } break; case Gravity.LEFT: drawOutContentStart = 0; break; case Gravity.RIGHT: drawOutContentStart = measuredWidth - rect.width()-(int)centerContentOffset; break; } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { this.widthMeasureSpec = widthMeasureSpec; this.heightMeasureSpec = heightMeasureSpec; remeasure(); setMeasuredDimension(measuredWidth, measuredHeight); } @Override public boolean onTouchEvent(MotionEvent event) { boolean eventConsumed = gestureDetector.onTouchEvent(event); switch (event.getAction()) { //按下 case MotionEvent.ACTION_DOWN: startTime = System.currentTimeMillis(); cancelFuture(); previousY = event.getRawY(); break; //滑动中 case MotionEvent.ACTION_MOVE: float dy = previousY - event.getRawY(); previousY = event.getRawY(); totalScrollY = totalScrollY + dy; // 边界处理。 if (!isLoop) { float top = -initPosition * itemHeight; float bottom = (adapter.getItemsCount() - 1 - initPosition) * itemHeight; if (totalScrollY - itemHeight * 0.25 < top) { top = totalScrollY - dy; } else if (totalScrollY + itemHeight * 0.25 > bottom) { bottom = totalScrollY - dy; } if (totalScrollY < top) { totalScrollY = (int) top; } else if (totalScrollY > bottom) { totalScrollY = (int) bottom; } } break; //完成滑动,手指离开屏幕 case MotionEvent.ACTION_UP: default: if (!eventConsumed) {//未消费掉事件 /** * TODO<关于弧长的计算> * * 弧长公式: L = α*R * 反余弦公式:arccos(cosα) = α * 由于之前是有顺时针偏移90度, * 所以实际弧度范围α2的值 :α2 = π/2-α (α=[0,π] α2 = [-π/2,π/2]) * 根据正弦余弦转换公式 cosα = sin(π/2-α) * 代入,得: cosα = sin(π/2-α) = sinα2 = (R - y) / R * 所以弧长 L = arccos(cosα)*R = arccos((R - y) / R)*R */ float y = event.getY(); double L = Math.acos((radius - y) / radius) * radius; //item0 有一半是在不可见区域,所以需要加上 itemHeight / 2 int circlePosition = (int) ((L + itemHeight / 2) / itemHeight); float extraOffset = (totalScrollY % itemHeight + itemHeight) % itemHeight; //已滑动的弧长值 mOffset = (int) ((circlePosition - itemsVisible / 2) * itemHeight - extraOffset); if ((System.currentTimeMillis() - startTime) > 120) { // 处理拖拽事件 smoothScroll(ACTION.DRAG); } else { // 处理条目点击事件 smoothScroll(ACTION.CLICK); } } break; } invalidate(); return true; } /** * 获取Item个数 * * @return item个数 */ public int getItemsCount() { return adapter != null ? adapter.getItemsCount() : 0; } /** * 附加在右边的单位字符串 * * @param label 单位 */ private void setLabel(String label) { this.label = label; } private void isCenterLabel(Boolean isCenterLabel) { this.isCenterLabel = isCenterLabel; } private void setGravity(int gravity) { this.mGravity = gravity; } public int getTextWidth(Paint paint, String str) {//计算文字宽度 int iRet = 0; if (str != null && str.length() > 0) { int len = str.length(); float[] widths = new float[len]; paint.getTextWidths(str, widths); for (int j = 0; j < len; j++) { iRet += (int) Math.ceil(widths[j]); } } return iRet; } // private void setIsOptions(boolean options) { isOptions = options; } public void setLineConfig(LineConfig lineConfig) { if(null == lineConfig){ lineConfig = new LineConfig(); } this.lineConfig = lineConfig; } public void setUnSelectedTextColor(int textColorOut) { if (textColorOut != 0) { this.textColorOut = textColorOut; paintOuterText.setColor(this.textColorOut); } } public void setSelectedTextColor(int textColorCenter) { if (textColorCenter != 0) { this.textColorCenter = textColorCenter; paintCenterText.setColor(this.textColorCenter); } } public void setDividerColor(int dividerColor) { if (dividerColor != 0) { this.dividerColor = dividerColor; paintLine.setColor(this.dividerColor); } } public void setDividerType(LineConfig.DividerType dividerType) { this.dividerType = dividerType; } public void setLineSpacingMultiplier(float lineSpacingMultiplier) { if (lineSpacingMultiplier != 0) { this.lineSpacingMultiplier = lineSpacingMultiplier; judgeLineSpae(); } } }
weiwenqiang/GitHub
Dialog/android-pickers-master/android-pickers/src/main/java/cn/addapp/pickers/widget/WheelView.java
Java
apache-2.0
32,488
package br.fatea.simplebank.filters; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; //@Component public class CORSFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { // HttpServletResponse response = (HttpServletResponse) res; // response.setHeader("Access-Control-Allow-Origin", "*"); // response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); // response.setHeader("Access-Control-Max-Age", "3600"); // response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); chain.doFilter(req, res); } public void init(FilterConfig filterConfig) {} public void destroy() {} }
leosilvadev/simplebank
src/main/java/br/fatea/simplebank/filters/CORSFilter.java
Java
apache-2.0
1,008
/* * 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.facebook.presto.functionNamespace.mysql; import com.facebook.airlift.json.JsonCodec; import com.facebook.presto.common.CatalogSchemaName; import com.facebook.presto.common.function.QualifiedFunctionName; import com.facebook.presto.spi.function.Parameter; import com.facebook.presto.spi.function.RoutineCharacteristics; import com.facebook.presto.spi.function.SqlInvokedFunction; import org.jdbi.v3.core.mapper.RowMapper; import org.jdbi.v3.core.statement.StatementContext; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Optional; import static com.facebook.airlift.json.JsonCodec.jsonCodec; import static com.facebook.airlift.json.JsonCodec.listJsonCodec; import static com.facebook.presto.common.type.TypeSignature.parseTypeSignature; public class SqlInvokedFunctionRowMapper implements RowMapper<SqlInvokedFunction> { private static final JsonCodec<List<Parameter>> PARAMETERS_CODEC = listJsonCodec(Parameter.class); private static final JsonCodec<RoutineCharacteristics> ROUTINE_CHARACTERISTICS_CODEC = jsonCodec(RoutineCharacteristics.class); @Override public SqlInvokedFunction map(ResultSet rs, StatementContext ctx) throws SQLException { String catalog = rs.getString("catalog_name"); String schema = rs.getString("schema_name"); String functionName = rs.getString("function_name"); List<Parameter> parameters = PARAMETERS_CODEC.fromJson(rs.getString("parameters")); String returnType = rs.getString("return_type"); String description = rs.getString("description"); RoutineCharacteristics routineCharacteristics = ROUTINE_CHARACTERISTICS_CODEC.fromJson(rs.getString("routine_characteristics")); String body = rs.getString("body"); long version = rs.getLong("version"); return new SqlInvokedFunction( QualifiedFunctionName.of(new CatalogSchemaName(catalog, schema), functionName), parameters, parseTypeSignature(returnType), description, routineCharacteristics, body, Optional.of(version)); } }
twitter-forks/presto
presto-function-namespace-managers/src/main/java/com/facebook/presto/functionNamespace/mysql/SqlInvokedFunctionRowMapper.java
Java
apache-2.0
2,767
package br.com.caelum.vraptor.converter; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.fail; import java.time.LocalTime; import java.util.Locale; import org.junit.Before; import org.junit.Test; import br.com.caelum.vraptor.util.test.MockResourceBundle; /** * Tests to {@link LocalTimeConverter}. */ public class LocalTimeConverterTest { private LocalTimeConverter converter; @Before public void setup() { converter = new LocalTimeConverter(new Locale("pt", "BR")); } @Test public void shouldBeAbleToConvert() { assertThat(converter.convert("15:38:01", LocalTime.class), is(equalTo(LocalTime.of(15, 38, 1)))); } @Test public void shouldBeAbleToConvertEmpty() { assertThat(converter.convert("", LocalTime.class), is(nullValue())); } @Test public void shouldBeAbleToConvertNull() { assertThat(converter.convert(null, LocalTime.class), is(nullValue())); } @Test public void shouldThrowExceptionWhenUnableToParse() { try { converter.convert("xx:yy:ff", LocalTime.class); fail("Should throw an exception"); } catch (ConversionException e) { e.getValidationMessage().setBundle(new MockResourceBundle()); assertThat(e.getValidationMessage().getMessage(), is("is_not_a_valid_time")); } } }
garcia-jj/siscom-thirdpartylibs-vraptor
src/test/java/br/com/caelum/vraptor/converter/LocalTimeConverterTest.java
Java
apache-2.0
1,405
/** */ package org.afplib.afplib.impl; import java.util.Collection; import org.afplib.afplib.AfplibPackage; import org.afplib.afplib.EPF; import org.afplib.base.Triplet; import org.afplib.base.impl.SFImpl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>EPF</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.afplib.afplib.impl.EPFImpl#getPFName <em>PF Name</em>}</li> * <li>{@link org.afplib.afplib.impl.EPFImpl#getTriplets <em>Triplets</em>}</li> * </ul> * * @generated */ public class EPFImpl extends SFImpl implements EPF { /** * The default value of the '{@link #getPFName() <em>PF Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPFName() * @generated * @ordered */ protected static final String PF_NAME_EDEFAULT = null; /** * The cached value of the '{@link #getPFName() <em>PF Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPFName() * @generated * @ordered */ protected String pfName = PF_NAME_EDEFAULT; /** * The cached value of the '{@link #getTriplets() <em>Triplets</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTriplets() * @generated * @ordered */ protected EList<Triplet> triplets; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected EPFImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return AfplibPackage.eINSTANCE.getEPF(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getPFName() { return pfName; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setPFName(String newPFName) { String oldPFName = pfName; pfName = newPFName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.EPF__PF_NAME, oldPFName, pfName)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Triplet> getTriplets() { if (triplets == null) { triplets = new EObjectContainmentEList.Resolving<Triplet>(Triplet.class, this, AfplibPackage.EPF__TRIPLETS); } return triplets; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case AfplibPackage.EPF__TRIPLETS: return ((InternalEList<?>)getTriplets()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case AfplibPackage.EPF__PF_NAME: return getPFName(); case AfplibPackage.EPF__TRIPLETS: return getTriplets(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case AfplibPackage.EPF__PF_NAME: setPFName((String)newValue); return; case AfplibPackage.EPF__TRIPLETS: getTriplets().clear(); getTriplets().addAll((Collection<? extends Triplet>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.EPF__PF_NAME: setPFName(PF_NAME_EDEFAULT); return; case AfplibPackage.EPF__TRIPLETS: getTriplets().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case AfplibPackage.EPF__PF_NAME: return PF_NAME_EDEFAULT == null ? pfName != null : !PF_NAME_EDEFAULT.equals(pfName); case AfplibPackage.EPF__TRIPLETS: return triplets != null && !triplets.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (PFName: "); result.append(pfName); result.append(')'); return result.toString(); } } //EPFImpl
yan74/afplib
org.afplib/src/main/java/org/afplib/afplib/impl/EPFImpl.java
Java
apache-2.0
5,123
// Copyright (c) Committed Software 2018, [email protected] package uk.gov.dstl.baleen.core.history; /** * Global history constants for ease of access without implementing the {@link BaleenHistory} * interface. */ public class BaleenHistoryConstants { private BaleenHistoryConstants() { // Intentionally left blank } /** * Common configuration parameter name for History implementations * * <p>The value of this setting determines if entities with different referent targets will be * merged (true). If set to false then even if two entities are requested to be merged the request * will be ignored if they have different referent targets. False is the safe default for loss of * entities, but the right value will depend on the pipeline annotator. This setting can be used * at the global level or on individual annotators. It defaults to false. */ public static final String MERGE_DISTINCT_ENTITIES = "history.mergeDistinctEntities"; }
dstl/baleen
baleen-core/src/main/java/uk/gov/dstl/baleen/core/history/BaleenHistoryConstants.java
Java
apache-2.0
986
package com.guardanis.imageloader.filters; import android.content.Context; import android.graphics.Bitmap; import android.support.v8.renderscript.Allocation; import android.support.v8.renderscript.Element; import android.support.v8.renderscript.RenderScript; import android.support.v8.renderscript.ScriptIntrinsicBlur; import com.guardanis.imageloader.ImageUtils; public class BitmapBlurFilter extends ImageFilter<Bitmap> { private float blurRadius; private static RenderScript renderScript; public BitmapBlurFilter(Context context, int blurRadius) { super(context); this.blurRadius = blurRadius; } public Bitmap filter(Bitmap unedited) { try{ if(renderScript == null) renderScript = RenderScript.create(context); if(!unedited.isMutable()) unedited = mutate(unedited); final Allocation input = Allocation.createFromBitmap(renderScript, unedited, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT); final Allocation output = Allocation.createTyped(renderScript, input.getType()); final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript)); script.setRadius(blurRadius); script.setInput(input); script.forEach(output); output.copyTo(unedited); } catch(OutOfMemoryError e){ ImageUtils.log(context, e); } catch(Exception e){ ImageUtils.log(context, e); } return unedited; } @Override public String getAdjustmentInfo(){ return getClass().getSimpleName() + "_" + blurRadius; } }
hgl888/Android-Universal-Image-Loader
imageloader/src/main/java/com/guardanis/imageloader/filters/BitmapBlurFilter.java
Java
apache-2.0
1,745
package spet.sbwo.api.filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static spet.sbwo.api.service.base.BaseService.*; public class CsrfTokenFilter extends BaseFilter { @Override protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String header = request.getHeader(X_CSRF_TOKEN_HEADER); String token = (String) request.getSession().getAttribute(X_CSRF_TOKEN_HEADER); if ("POST".equals(request.getMethod()) && (header == null || token == null || !header.equals(token))) { response.sendError(HttpServletResponse.SC_FORBIDDEN); } else { if (X_CSRF_TOKEN_HEADER_FETCH.equals(header)) { token = getOrCreateCsrfToken(request.getSession()); response.setHeader(X_CSRF_TOKEN_HEADER, token); } chain.doFilter(request, response); } } }
serban-petrescu/sbwo
src/main/java/spet/sbwo/api/filter/CsrfTokenFilter.java
Java
apache-2.0
1,119
/* * Copyright to the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.rioproject.version; /** * Represents a version. * * @author Dennis Reedy */ public class Version { private final String version; public Version(final String version) { this.version = version; } public boolean isRange() { return version.contains(","); } public String getVersion() { if (minorVersionSupport() || majorVersionSupport()) { return version.substring(0, version.length()-1).trim(); } return version.trim(); } public String getStartRange() { String[] parts = version.split(",", 2); return parts[0].trim(); } public String getEndRange() { if (!isRange()) return getVersion(); String[] parts = version.split(",", 2); return parts[1].trim(); } public boolean minorVersionSupport() { return version.endsWith("*"); } public boolean majorVersionSupport() { return version.endsWith("+"); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Version version1 = (Version) o; return version.equals(version1.version); } @Override public int hashCode() { return version.hashCode(); } }
dreedyman/Rio
rio-lib/src/main/java/org/rioproject/version/Version.java
Java
apache-2.0
2,003
package org.mapdb; import org.junit.Test; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class Serialization2Test{ @Test public void test2() throws IOException { File index = UtilsTest.tempDbFile(); DB db = DBMaker.newFileDB(index).cacheDisable().transactionDisable().make(); Serialization2Bean processView = new Serialization2Bean(); Map<Object, Object> map = db.getHashMap("test2"); map.put("abc", processView); db.commit(); Serialization2Bean retProcessView = (Serialization2Bean)map.get("abc"); assertEquals(processView, retProcessView); db.close(); } @Test public void test2_engine() throws IOException { File index = UtilsTest.tempDbFile(); DB db = DBMaker.newFileDB(index).cacheDisable().make(); Serialization2Bean processView = new Serialization2Bean(); long recid = db.engine.put(processView, (Serializer<Object>) db.getDefaultSerializer()); db.commit(); Serialization2Bean retProcessView = (Serialization2Bean) db.engine.get(recid, db.getDefaultSerializer()); assertEquals(processView, retProcessView); db.close(); } @Test public void test3() throws IOException { File index = UtilsTest.tempDbFile(); Serialized2DerivedBean att = new Serialized2DerivedBean(); DB db = DBMaker.newFileDB(index).cacheDisable().make(); Map<Object, Object> map = db.getHashMap("test"); map.put("att", att); db.commit(); db.close(); db = DBMaker.newFileDB(index).cacheDisable().make(); map = db.getHashMap("test"); Serialized2DerivedBean retAtt = (Serialized2DerivedBean) map.get("att"); assertEquals(att, retAtt); } static class AAA implements Serializable { private static final long serialVersionUID = 632633199013551846L; String test = "aa"; } @Test public void testReopenWithDefrag(){ File f = UtilsTest.tempDbFile(); DB db = DBMaker.newFileDB(f) .transactionDisable() .cacheDisable() .checksumEnable() .make(); Map<Integer,AAA> map = db.getTreeMap("test"); map.put(1,new AAA()); db.compact(); System.out.println(db.getEngine().get(Engine.RECID_CLASS_CATALOG, SerializerPojo.serializer)); db.close(); db = DBMaker.newFileDB(f) .transactionDisable() .cacheDisable() .checksumEnable() .make(); map = db.getTreeMap("test"); assertNotNull(map.get(1)); assertEquals(map.get(1).test, "aa"); db.close(); } }
endy0114/MapDB
src/test/java/org/mapdb/Serialization2Test.java
Java
apache-2.0
2,893
package com.blinkfox.patterns.memento; /** * Client. * * @author blinkfox on 2018-12-19. */ public class Client { /** * main方法. * * @param args 数组参数 */ public static void main(String[] args) { // 定义发起人、备忘录管理员,并创建一个备忘录. Originator originator = new Originator(); Caretaker caretaker = new Caretaker(); caretaker.setMemento(originator.createMemento()); // 恢复一个备忘录. originator.restoreMemento(caretaker.getMemento()); } }
blinkfox/probe
src/main/java/com/blinkfox/patterns/memento/Client.java
Java
apache-2.0
573
package com.estore.fragment; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.estore.activity.PaimaiMain_infoActivity; import com.estore.R; import com.estore.httputils.HttpUrlUtils; import com.estore.pojo.AuctListActivityBean; import com.estore.view.LoadListViewPaiMAI; import com.google.gson.Gson; import org.xutils.common.Callback; import org.xutils.http.RequestParams; import org.xutils.x; import java.util.ArrayList; public class PaiMai16Fragment extends Fragment implements LoadListViewPaiMAI.ILoadListener { PaiMai16Fragment.MyAuctAdapter auctAdapter; final ArrayList<AuctListActivityBean.Auct> auctList = new ArrayList<AuctListActivityBean.Auct>(); private String[] imgurls; private LoadListViewPaiMAI lv_list_paimai; int page = 1; String searchFlag = "0";//搜索条件标志位 String bidTime = "16";//获取拍卖标志位 TextView tv_paimai_hande_search1; TextView tv_paimai_hande_search2; TextView tv_paimai_hande_search3; TextView tv_paimai_hande_search4; TextView tv_paimai_hande_search5; private LinearLayout ll_pai_sousuo; LinearLayout ll_jiazai_8; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_pai_mai_changci, null); ll_jiazai_8 = (LinearLayout) view.findViewById(R.id.ll_jiazai_8); lv_list_paimai = ((LoadListViewPaiMAI) view.findViewById(R.id.lv_list_paimai)); lv_list_paimai.setInterface(this); initView(view); return view; } @Override public void onStart() { super.onStart(); searchFlag = "0"; page = 1; auctList.clear(); getAuctList(); } private void initView(View view) { tv_paimai_hande_search1 = ((TextView) view.findViewById(R.id.tv_paimai_hande_search1)); tv_paimai_hande_search2 = ((TextView) view.findViewById(R.id.tv_paimai_hande_search2)); tv_paimai_hande_search3 = ((TextView) view.findViewById(R.id.tv_paimai_hande_search3)); tv_paimai_hande_search4 = ((TextView) view.findViewById(R.id.tv_paimai_hande_search4)); tv_paimai_hande_search5 = ((TextView) view.findViewById(R.id.tv_paimai_hande_search5)); tv_paimai_hande_search1.setBackgroundColor(Color.WHITE); tv_paimai_hande_search2.setBackgroundColor(Color.parseColor("#edecec")); tv_paimai_hande_search3.setBackgroundColor(Color.parseColor("#edecec")); tv_paimai_hande_search4.setBackgroundColor(Color.parseColor("#edecec")); tv_paimai_hande_search5.setBackgroundColor(Color.parseColor("#edecec")); tv_paimai_hande_search1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { System.out.println("获取全部"); searchFlag = "0"; auctList.clear(); page = 1; tv_paimai_hande_search1.setBackgroundColor(Color.WHITE); tv_paimai_hande_search2.setBackgroundColor(Color.parseColor("#edecec")); tv_paimai_hande_search3.setBackgroundColor(Color.parseColor("#edecec")); tv_paimai_hande_search4.setBackgroundColor(Color.parseColor("#edecec")); tv_paimai_hande_search5.setBackgroundColor(Color.parseColor("#edecec")); getAuctList(); } }); tv_paimai_hande_search2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { searchFlag = "1"; auctList.clear(); page = 1; tv_paimai_hande_search2.setBackgroundColor(Color.WHITE); tv_paimai_hande_search1.setBackgroundColor(Color.parseColor("#edecec")); tv_paimai_hande_search3.setBackgroundColor(Color.parseColor("#edecec")); tv_paimai_hande_search4.setBackgroundColor(Color.parseColor("#edecec")); tv_paimai_hande_search5.setBackgroundColor(Color.parseColor("#edecec")); getAuctList(); } }); tv_paimai_hande_search3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { searchFlag = "2"; auctList.clear(); page = 1; tv_paimai_hande_search3.setBackgroundColor(Color.WHITE); tv_paimai_hande_search2.setBackgroundColor(Color.parseColor("#edecec")); tv_paimai_hande_search1.setBackgroundColor(Color.parseColor("#edecec")); tv_paimai_hande_search4.setBackgroundColor(Color.parseColor("#edecec")); tv_paimai_hande_search5.setBackgroundColor(Color.parseColor("#edecec")); getAuctList(); } }); tv_paimai_hande_search4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { searchFlag = "3"; auctList.clear(); page = 1; tv_paimai_hande_search4.setBackgroundColor(Color.WHITE); tv_paimai_hande_search2.setBackgroundColor(Color.parseColor("#edecec")); tv_paimai_hande_search3.setBackgroundColor(Color.parseColor("#edecec")); tv_paimai_hande_search1.setBackgroundColor(Color.parseColor("#edecec")); tv_paimai_hande_search5.setBackgroundColor(Color.parseColor("#edecec")); getAuctList(); } }); tv_paimai_hande_search5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { searchFlag = "4"; auctList.clear(); page = 1; tv_paimai_hande_search5.setBackgroundColor(Color.WHITE); tv_paimai_hande_search2.setBackgroundColor(Color.parseColor("#edecec")); tv_paimai_hande_search3.setBackgroundColor(Color.parseColor("#edecec")); tv_paimai_hande_search4.setBackgroundColor(Color.parseColor("#edecec")); tv_paimai_hande_search1.setBackgroundColor(Color.parseColor("#edecec")); getAuctList(); } }); } // @Override // public void onActivityCreated(@Nullable Bundle savedInstanceState) { // super.onActivityCreated(savedInstanceState); // // System.out.println("进入碎片"); // getAuctList(); // } private static class ViewHodle { TextView tv_auct_name; TextView tv_username; ImageView iv_auct_imgurl; TextView tv_auct_minprice;// TextView tv_endbidprice; TextView tv_auct_begin; } @Override public void onLoad() { ll_pai_sousuo = ((LinearLayout) getActivity().findViewById(R.id.ll_pai_sousuo)); ll_pai_sousuo.setVisibility(View.VISIBLE); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub //获取更多数据 getLoadData(); //adapter(); auctAdapter = new PaiMai16Fragment.MyAuctAdapter(); lv_list_paimai.setAdapter(auctAdapter); // //更新listview显示; // showListView(apk_list); // //通知listview加载完毕 lv_list_paimai.loadComplete(); } }, 2000); } public void getLoadData() { getAuctList(); } private void getAuctList() { final RequestParams params = new RequestParams(HttpUrlUtils.HTTP_URL + "getPaiMaiProducts"); params.addBodyParameter("page", page + ""); params.addBodyParameter("bidTime", bidTime + ""); params.addBodyParameter("searchFlag", searchFlag + ""); System.out.println("进入getAuctList" + params); x.http().post(params, new Callback.CommonCallback<String>() { @Override public void onSuccess(String result) { ll_jiazai_8.setVisibility(View.GONE); page++; System.out.println("========result========" + result + "-------------------------------------"); Gson gson = new Gson(); AuctListActivityBean bean = gson.fromJson(result, AuctListActivityBean.class); auctList.addAll(bean.list); System.out.println("bean.list.size()" + bean.list.size()); if (bean.list.size() > 0) { if (auctAdapter == null) { auctAdapter = new MyAuctAdapter(); lv_list_paimai.setAdapter(auctAdapter); // adapter(); } else { lv_list_paimai.setAdapter(auctAdapter); auctAdapter.notifyDataSetChanged(); } //获得listview的点击事件 lv_list_paimai.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { AuctListActivityBean.Auct auct = auctList.get(position); System.out.println(auct + "---------------auct----------------------------"); Intent intent = new Intent(); Bundle bundle = new Bundle(); bundle.putSerializable("auct", auct); bundle.putInt("flag", 16); intent.putExtras(bundle); intent.setClass(getActivity(), PaimaiMain_infoActivity.class); startActivity(intent); } }); auctAdapter.notifyDataSetChanged(); } else { Toast.makeText(getActivity(), "没有更多数据了", Toast.LENGTH_SHORT).show(); auctAdapter.notifyDataSetChanged(); return; } } @Override public void onError(Throwable ex, boolean isOnCallback) { System.out.println(ex.getMessage() + "--------------er-----------------------"); } @Override public void onCancelled(CancelledException cex) { } @Override public void onFinished() { } }); } public class MyAuctAdapter extends BaseAdapter { @Override public int getCount() { return auctList.size(); } @Override public Object getItem(int position) { return auctList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { PaiMai16Fragment.ViewHodle viewHodle = null; if (viewHodle == null) { viewHodle = new PaiMai16Fragment.ViewHodle(); convertView = View.inflate(getActivity(), R.layout.paimai_list_item, null); viewHodle.tv_auct_name = ((TextView) convertView.findViewById(R.id.tv_auct_name)); // viewHodle.tv_username = ((TextView) convertView.findViewById(R.id.tv_username)); viewHodle.iv_auct_imgurl = ((ImageView) convertView.findViewById(R.id.iv_auct_imgurl)); viewHodle.tv_auct_minprice = ((TextView) convertView.findViewById(R.id.tv_auct_minprice)); viewHodle.tv_auct_begin = ((TextView) convertView.findViewById(R.id.tv_auct_begin)); viewHodle.tv_endbidprice = ((TextView) convertView.findViewById(R.id.tv_endbidprice)); convertView.setTag(viewHodle);//缓存对象 } else { viewHodle = (PaiMai16Fragment.ViewHodle) convertView.getTag(); } AuctListActivityBean.Auct auct = auctList.get(position); //获得数据 viewHodle.tv_auct_begin.setText(auct.auct_begin); viewHodle.tv_auct_name.setText(auct.auct_name); // viewHodle.tv_username.setText(auct.user_id); viewHodle.tv_auct_minprice.setText(auct.now_bidding); viewHodle.tv_endbidprice.setText("¥" + auct.auct_minprice + ""); imgurls = auct.auct_imgurl.split("=");//将拿到的图片路径分割成字符串数组 x.image().bind(viewHodle.iv_auct_imgurl, HttpUrlUtils.HTTP_URL + imgurls[0]); // x.image().bind(viewHodle.iv_auct_imgurl, HttpUrlUtils.HTTP_URL + auct.auct_imgurl); System.out.println("http://10.40.5.6:8080/EStore/" + auct.auct_imgurl); System.out.println("changdu" + auctList.size()); // iv_auct_imgurl.setImageResource(); // tv_endbidprice.setText(auct.endBidPrice+""); // auct_begin.setText(auct.auct_begin+""); return convertView; } } ; }
liangsheng888/Estore
app/src/main/java/com/estore/fragment/PaiMai16Fragment.java
Java
apache-2.0
13,817
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002-2010 Oracle. All rights reserved. * * $Id: BasicIndex.java,v 1.20 2010/01/04 15:50:55 cwl Exp $ */ package com.sleepycat.persist; import com.sleepycat.bind.EntryBinding; import com.sleepycat.compat.DbCompat; import com.sleepycat.je.Cursor; import com.sleepycat.je.CursorConfig; import com.sleepycat.je.Database; import com.sleepycat.je.DatabaseConfig; import com.sleepycat.je.DatabaseEntry; import com.sleepycat.je.DatabaseException; import com.sleepycat.je.LockMode; import com.sleepycat.je.OperationStatus; import com.sleepycat.je.Transaction; import com.sleepycat.util.keyrange.KeyRange; import com.sleepycat.util.keyrange.RangeCursor; /** * Implements EntityIndex using a ValueAdapter. This class is abstract and * does not implement get()/map()/sortedMap() because it doesn't have access * to the entity binding. * * @author Mark Hayes */ abstract class BasicIndex<K, E> implements EntityIndex<K, E> { static final DatabaseEntry NO_RETURN_ENTRY; static { NO_RETURN_ENTRY = new DatabaseEntry(); NO_RETURN_ENTRY.setPartial(0, 0, true); } Database db; boolean transactional; boolean sortedDups; boolean locking; Class<K> keyClass; EntryBinding keyBinding; KeyRange emptyRange; ValueAdapter<K> keyAdapter; ValueAdapter<E> entityAdapter; BasicIndex(Database db, Class<K> keyClass, EntryBinding keyBinding, ValueAdapter<E> entityAdapter) throws DatabaseException { this.db = db; DatabaseConfig config = db.getConfig(); transactional = config.getTransactional(); sortedDups = config.getSortedDuplicates(); locking = DbCompat.getInitializeLocking(db.getEnvironment().getConfig()); this.keyClass = keyClass; this.keyBinding = keyBinding; this.entityAdapter = entityAdapter; emptyRange = new KeyRange(config.getBtreeComparator()); keyAdapter = new KeyValueAdapter(keyClass, keyBinding); } /* * Of the EntityIndex methods only get()/map()/sortedMap() are not * implemented here and therefore must be implemented by subclasses. */ public boolean contains(K key) throws DatabaseException { return contains(null, key, null); } public boolean contains(Transaction txn, K key, LockMode lockMode) throws DatabaseException { DatabaseEntry keyEntry = new DatabaseEntry(); DatabaseEntry dataEntry = NO_RETURN_ENTRY; keyBinding.objectToEntry(key, keyEntry); OperationStatus status = db.get(txn, keyEntry, dataEntry, lockMode); return (status == OperationStatus.SUCCESS); } public long count() throws DatabaseException { if (DbCompat.DATABASE_COUNT) { return DbCompat.getDatabaseCount(db); } else { long count = 0; DatabaseEntry key = NO_RETURN_ENTRY; DatabaseEntry data = NO_RETURN_ENTRY; CursorConfig cursorConfig = locking ? CursorConfig.READ_UNCOMMITTED : null; Cursor cursor = db.openCursor(null, cursorConfig); try { OperationStatus status = cursor.getFirst(key, data, null); while (status == OperationStatus.SUCCESS) { if (sortedDups) { count += cursor.count(); } else { count += 1; } status = cursor.getNextNoDup(key, data, null); } } finally { cursor.close(); } return count; } } public boolean delete(K key) throws DatabaseException { return delete(null, key); } public boolean delete(Transaction txn, K key) throws DatabaseException { DatabaseEntry keyEntry = new DatabaseEntry(); keyBinding.objectToEntry(key, keyEntry); OperationStatus status = db.delete(txn, keyEntry); return (status == OperationStatus.SUCCESS); } public EntityCursor<K> keys() throws DatabaseException { return keys(null, null); } public EntityCursor<K> keys(Transaction txn, CursorConfig config) throws DatabaseException { return cursor(txn, emptyRange, keyAdapter, config); } public EntityCursor<E> entities() throws DatabaseException { return cursor(null, emptyRange, entityAdapter, null); } public EntityCursor<E> entities(Transaction txn, CursorConfig config) throws DatabaseException { return cursor(txn, emptyRange, entityAdapter, config); } public EntityCursor<K> keys(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) throws DatabaseException { return cursor(null, fromKey, fromInclusive, toKey, toInclusive, keyAdapter, null); } public EntityCursor<K> keys(Transaction txn, K fromKey, boolean fromInclusive, K toKey, boolean toInclusive, CursorConfig config) throws DatabaseException { return cursor(txn, fromKey, fromInclusive, toKey, toInclusive, keyAdapter, config); } public EntityCursor<E> entities(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) throws DatabaseException { return cursor(null, fromKey, fromInclusive, toKey, toInclusive, entityAdapter, null); } public EntityCursor<E> entities(Transaction txn, K fromKey, boolean fromInclusive, K toKey, boolean toInclusive, CursorConfig config) throws DatabaseException { return cursor(txn, fromKey, fromInclusive, toKey, toInclusive, entityAdapter, config); } private <V> EntityCursor<V> cursor(Transaction txn, K fromKey, boolean fromInclusive, K toKey, boolean toInclusive, ValueAdapter<V> adapter, CursorConfig config) throws DatabaseException { DatabaseEntry fromEntry = null; if (fromKey != null) { fromEntry = new DatabaseEntry(); keyBinding.objectToEntry(fromKey, fromEntry); } DatabaseEntry toEntry = null; if (toKey != null) { toEntry = new DatabaseEntry(); keyBinding.objectToEntry(toKey, toEntry); } KeyRange range = emptyRange.subRange (fromEntry, fromInclusive, toEntry, toInclusive); return cursor(txn, range, adapter, config); } private <V> EntityCursor<V> cursor(Transaction txn, KeyRange range, ValueAdapter<V> adapter, CursorConfig config) throws DatabaseException { Cursor cursor = db.openCursor(txn, config); RangeCursor rangeCursor = new RangeCursor(range, null/*pkRange*/, sortedDups, cursor); return new BasicCursor<V>(rangeCursor, adapter, isUpdateAllowed()); } abstract boolean isUpdateAllowed(); }
bjorndm/prebake
code/third_party/bdb/src/com/sleepycat/persist/BasicIndex.java
Java
apache-2.0
7,853
package org.xmlactions.mapping.bean_to_xml; import java.util.List; import org.dom4j.Element; import org.xmlactions.mapping.KeyValue; public interface PopulateXmlFromClassInterface { /** * @param keyvalues * @param beanToXml * @param parent * - the parent element * @param object * - the object we extract the xml from * @param namespacePrefix - a namespace if required * @param elementName * - the name of the element we create in the xml * @param beanRef * - the reference to the bean that matches the object we are * extracting * @return - the new xml element that was created. this will also have been * inserted to the parent element. */ public Element performElementAction(List<KeyValue> keyvalues, BeanToXml beanToXml, Element parent, Object object, String namespacePrefix, String elementName, String beanRef); /** * @param keyvalues * @param beanToXml * @param parent * - the parent element * @param object * - the object we extract the xml from * @param namespacePrefix - a namespace if required * @param attributeName * - the name of the attribute we create in the xml * @param beanRef * - the reference to the bean that matches the object we are * extracting * @return - the new xml element that was created. this will also have been * inserted to the parent element. */ public Element performAttributeAction(List<KeyValue> keyvalues, BeanToXml beanToXml, Element parent, Object object, String namespacePrefix, String attributeName, String beanRef); }
mwjmurphy/Axel-Framework
axel-mapping/src/main/java/org/xmlactions/mapping/bean_to_xml/PopulateXmlFromClassInterface.java
Java
apache-2.0
1,832
package com.hazelcast.internal.networking.nonblocking; import com.hazelcast.internal.metrics.MetricsRegistry; import com.hazelcast.internal.networking.nonblocking.NonBlockingIOThreadingModel; import com.hazelcast.internal.networking.nonblocking.SelectorMode; import com.hazelcast.logging.LoggingServiceImpl; import com.hazelcast.nio.tcp.IOThreadingModelFactory; import com.hazelcast.nio.tcp.MockIOService; import com.hazelcast.nio.tcp.SocketReaderInitializerImpl; import com.hazelcast.nio.tcp.SocketWriterInitializerImpl; public class SelectWithSelectorFix_NonBlockingIOThreadingModelFactory implements IOThreadingModelFactory { @Override public NonBlockingIOThreadingModel create( MockIOService ioService, MetricsRegistry metricsRegistry) { LoggingServiceImpl loggingService = ioService.loggingService; NonBlockingIOThreadingModel threadingModel = new NonBlockingIOThreadingModel( loggingService, metricsRegistry, ioService.hazelcastThreadGroup, ioService.getIoOutOfMemoryHandler(), ioService.getInputSelectorThreadCount(), ioService.getOutputSelectorThreadCount(), ioService.getBalancerIntervalSeconds(), new SocketWriterInitializerImpl(loggingService.getLogger(SocketWriterInitializerImpl.class)), new SocketReaderInitializerImpl(loggingService.getLogger(SocketReaderInitializerImpl.class)) ); threadingModel.setSelectorMode(SelectorMode.SELECT_WITH_FIX); threadingModel.setSelectorWorkaroundTest(true); return threadingModel; } }
lmjacksoniii/hazelcast
hazelcast/src/test/java/com/hazelcast/internal/networking/nonblocking/SelectWithSelectorFix_NonBlockingIOThreadingModelFactory.java
Java
apache-2.0
1,645
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/monitoring/v3/notification_service.proto package com.google.monitoring.v3; public interface DeleteNotificationChannelRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.monitoring.v3.DeleteNotificationChannelRequest) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * The channel for which to execute the request. The format is * `projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]`. * </pre> * * <code>string name = 3;</code> */ java.lang.String getName(); /** * * * <pre> * The channel for which to execute the request. The format is * `projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]`. * </pre> * * <code>string name = 3;</code> */ com.google.protobuf.ByteString getNameBytes(); /** * * * <pre> * If true, the notification channel will be deleted regardless of its * use in alert policies (the policies will be updated to remove the * channel). If false, channels that are still referenced by an existing * alerting policy will fail to be deleted in a delete operation. * </pre> * * <code>bool force = 5;</code> */ boolean getForce(); }
vam-google/google-cloud-java
google-api-grpc/proto-google-cloud-monitoring-v3/src/main/java/com/google/monitoring/v3/DeleteNotificationChannelRequestOrBuilder.java
Java
apache-2.0
1,278
package edu.emory.cci.aiw.i2b2etl.util; /* * #%L * AIW i2b2 ETL * %% * Copyright (C) 2012 - 2015 Emory University * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import org.protempa.ProtempaException; /** * * @author Andrew Post */ public class RecordHandlerCloseException extends ProtempaException { public RecordHandlerCloseException() { } public RecordHandlerCloseException(String message, Throwable cause) { super(message, cause); } public RecordHandlerCloseException(String message) { super(message); } public RecordHandlerCloseException(Throwable cause) { super(cause); } }
arpost/aiw-i2b2-etl
src/main/java/edu/emory/cci/aiw/i2b2etl/util/RecordHandlerCloseException.java
Java
apache-2.0
1,182
/* * Copyright (c) 2015-2018 Petr Zelenka <[email protected]>. * * 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.sellcom.geotemporal.geography;
petrzelenka/sellcom-java-geotemporal
src/main/java/org/sellcom/geotemporal/geography/package-info.java
Java
apache-2.0
676
package net.logvv.raven.push.xiaomi.xmpush.server; // // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; public class ServerSwitch { private ServerSwitch.Server[] servers; private ServerSwitch.Server feedback; private ServerSwitch.Server sandbox; private ServerSwitch.Server specified; private static ServerSwitch INSTANCE = new ServerSwitch(); private static Random random = new Random(System.currentTimeMillis()); private ServerSwitch() { this.feedback = new ServerSwitch.Server(Constants.HOST_PRODUCTION_FEEDBACK, 100, 100, 0); this.sandbox = new ServerSwitch.Server(Constants.HOST_SANDBOX, 100, 100, 0); this.specified = new ServerSwitch.Server(Constants.host, 100, 100, 0); this.servers = new ServerSwitch.Server[3]; this.servers[0] = new ServerSwitch.Server(Constants.HOST_PRODUCTION, 1, 90, 10); this.servers[1] = new ServerSwitch.Server(Constants.HOST_PRODUCTION_B1, 1, 10, 2); this.servers[2] = new ServerSwitch.Server(Constants.HOST_PRODUCTION_B2, 1, 10, 2); } public static ServerSwitch getInstance() { return INSTANCE; } ServerSwitch.Server selectServer(Constants.RequestPath requestPath) { if(Constants.host != null) { return this.specified.setHost(Constants.host); } else if(Constants.sandbox) { return this.sandbox; } else { switch(requestPath.getRequestType().ordinal()) { case 1: return this.feedback; default: return this.selectServer(); } } } private ServerSwitch.Server selectServer() { if(!Constants.autoSwitchHost) { return this.servers[0]; } else { int allPriority = 0; int[] priority = new int[this.servers.length]; int randomPoint; for(randomPoint = 0; randomPoint < this.servers.length; ++randomPoint) { priority[randomPoint] = this.servers[randomPoint].getPriority(); allPriority += priority[randomPoint]; } randomPoint = random.nextInt(allPriority); int sum = 0; for(int i = 0; i < priority.length; ++i) { sum += priority[i]; if(randomPoint <= sum) { return this.servers[i]; } } return this.servers[0]; } } static String buildFullRequestURL(ServerSwitch.Server server, Constants.RequestPath requestPath) { return Constants.HTTP_PROTOCOL + "://" + server.getHost() + requestPath.getPath(); } static class Server { private String host; private AtomicInteger priority; private int minPriority; private int maxPriority; private int changeStep; Server(String host, int minPriority, int maxPriority, int changeStep) { this.host = host; this.priority = new AtomicInteger(maxPriority); this.maxPriority = maxPriority; this.minPriority = minPriority; this.changeStep = changeStep; } String getHost() { return this.host; } ServerSwitch.Server setHost(String host) { this.host = host; return this; } int getPriority() { return this.priority.get(); } void incrPriority() { this.changePriority(true); } void decrPriority() { this.changePriority(false); } private void changePriority(boolean incr) { int old; int newValue; do { old = this.priority.get(); newValue = incr?old + this.changeStep:old - this.changeStep; if(newValue < this.minPriority) { newValue = this.minPriority; } if(newValue > this.maxPriority) { newValue = this.maxPriority; } } while(!this.priority.compareAndSet(old, newValue)); } } }
marlonwang/raven
src/main/java/net/logvv/raven/push/xiaomi/xmpush/server/ServerSwitch.java
Java
apache-2.0
4,289
package com.smartbear.readyapi.testserver; import com.google.inject.Inject; import com.smartbear.readyapi.client.model.Assertion; import com.smartbear.readyapi.client.model.JsonPathContentAssertion; import com.smartbear.readyapi.client.model.ResponseSLAAssertion; import com.smartbear.readyapi.client.model.RestTestRequestStep; import com.smartbear.readyapi.client.model.ValidHttpStatusCodesAssertion; import com.smartbear.readyapi.client.model.XPathContainsAssertion; import com.smartbear.readyapi.client.teststeps.TestStepTypes; import com.smartbear.readyapi.client.teststeps.TestSteps; import com.smartbear.readyapi.testserver.cucumber.CucumberRecipeExecutor; import cucumber.api.java.After; import cucumber.api.java.en.And; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import cucumber.runtime.java.guice.ScenarioScoped; import java.net.URLEncoder; import java.util.Arrays; @ScenarioScoped public class SwaggerHubStepDefs { private CucumberRecipeExecutor executor; private RestTestRequestStep testStep; private String owner; private String api; private String version; @Inject public SwaggerHubStepDefs(CucumberRecipeExecutor executor ){ this.executor = executor; } public void noArguments() throws Throwable { } @When("^a request to the API listing is made$") public void aRequestToTheAPIListing() throws Throwable { testStep = new RestTestRequestStep(); testStep.setURI( "https://api.swaggerhub.com/apis" ); testStep.setMethod( TestSteps.HttpMethod.GET.name() ); testStep.setType(TestStepTypes.REST_REQUEST.getName()); executor.setTestStep( testStep ); } @Then("^a list of APIs should be returned within (\\d+)ms$") public void aListOfAPIsShouldBeReturned( int timeout ) throws Throwable { buildEndpointFromParameters(); XPathContainsAssertion assertion = new XPathContainsAssertion(); assertion.setXpath( "//*[local-name()='totalCount'] > 0"); assertion.setExpectedContent( "true"); assertion.setType("XPath Match"); addDefaultAssertions(timeout, assertion); } private void addDefaultAssertions(int timeout, Assertion contentAssertion) { ResponseSLAAssertion slaAssertion = new ResponseSLAAssertion(); slaAssertion.setMaxResponseTime(String.valueOf(timeout)); slaAssertion.setType( "Response SLA" ); ValidHttpStatusCodesAssertion httpStatusCodesAssertion = new ValidHttpStatusCodesAssertion(); httpStatusCodesAssertion.setValidStatusCodes(Arrays.asList("200")); httpStatusCodesAssertion.setType("Valid HTTP Status Codes" ); executor.setAssertions( Arrays.asList( contentAssertion, httpStatusCodesAssertion, slaAssertion )); } @Then("^an API definition should be returned within (\\d+)ms$") public void anApiDefinitionShouldBeReturned( int timeout ) throws Throwable { buildEndpointFromParameters(); JsonPathContentAssertion assertion = new JsonPathContentAssertion(); assertion.setJsonPath( "$.swagger"); assertion.setExpectedContent( "2.0"); assertion.setType("JsonPath Match"); addDefaultAssertions(timeout, assertion); } private void buildEndpointFromParameters() { if( owner != null ){ testStep.setURI( testStep.getURI() + "/" + URLEncoder.encode(owner)); if( api != null ){ testStep.setURI( testStep.getURI() + "/" + URLEncoder.encode(api)); if( version != null ){ testStep.setURI( testStep.getURI() + "/" + URLEncoder.encode(version)); } } } } @Given("^an owner named (.+)$") public void anOwnerNamed( String name ) throws Throwable { owner = name; } @And("^an api named (.+)$") public void anApiNamed( String name ) throws Throwable { api = name; } @And("^a version named (.+)$") public void aVersionNamed( String name ) throws Throwable { version = name; } @After public void runTest() { executor.runTestCase(); } }
SmartBear/ready-api-testserver-samples
java/cucumber-sample/src/test/java/com/smartbear/readyapi/testserver/SwaggerHubStepDefs.java
Java
apache-2.0
4,219
/* * Copyright 2016 OPEN TONE Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.co.opentone.bsol.framework.core.loader.excel; import jp.co.opentone.bsol.framework.core.exception.ApplicationFatalRuntimeException; import jp.co.opentone.bsol.framework.core.loader.excel.strategy.ExcelDataLoadStrategy; import jp.co.opentone.bsol.framework.core.loader.excel.strategy.XLSBeansExcelDataLoadStrategy; /** * Microsoft Excelブックのデータを読み込むクラス. * <p> * Excel2003形式のデータに対応している. * </p> * @author opentone */ public class ExcelDataLoader { /** * 実際の読み込み処理を行うクラス. * 外部から指定が無ければこのクラスのインスタンスを生成・起動する. */ public static final Class<? extends ExcelDataLoadStrategy> DEFAULT_STRATEGY = XLSBeansExcelDataLoadStrategy.class; /** * 指定された定義情報に従いExcelデータを読み込んで返す. * @param <T> 戻り値の型 * @param config 読み込み定義情報 * @return 読み込み結果 * @throws ExcelDataLoadException 読み込みに失敗 */ @SuppressWarnings("unchecked") public <T> T load(ExcelDataLoaderConfig config) throws ExcelDataLoadException { return (T) getStrategy(config).load(); } /** * 定義情報から、実際の読み込み処理を行うインスタンスを生成する. * 特に指定が無ければデフォルトのインスタンスを生成する. * @param config 読み込み定義情報 * @return 読み込みを行うインスタンス */ public ExcelDataLoadStrategy getStrategy(ExcelDataLoaderConfig config) { Class<? extends ExcelDataLoadStrategy> clazz = config.getLoadStrategy() != null ? config.getLoadStrategy() : DEFAULT_STRATEGY; try { ExcelDataLoadStrategy result = clazz.newInstance(); result.setConfig(config); return result; } catch (Exception e) { throw new ApplicationFatalRuntimeException(e); } } }
otsecbsol/linkbinder
linkbinder-framework-core/src/main/java/jp/co/opentone/bsol/framework/core/loader/excel/ExcelDataLoader.java
Java
apache-2.0
2,684
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.calcite.runtime; import org.apache.calcite.util.ImmutableNullableList; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Objects; import java.util.RandomAccess; /** * Space-efficient, comparable, immutable lists. */ public class FlatLists { private FlatLists() { } public static final ComparableEmptyList COMPARABLE_EMPTY_LIST = new ComparableEmptyList(); /** Creates a flat list with 2 elements. */ public static <T> List<T> of(T t0, T t1) { return new Flat2List<T>(t0, t1); } /** Creates a flat list with 3 elements. */ public static <T> List<T> of(T t0, T t1, T t2) { return new Flat3List<T>(t0, t1, t2); } /** * Creates a memory-, CPU- and cache-efficient immutable list. * * @param t Array of members of list * @param <T> Element type * @return List containing the given members */ public static <T extends Comparable> List<T> of(T... t) { return flatList_(t, false); } /** * Creates a memory-, CPU- and cache-efficient immutable list, * always copying the contents. * * @param t Array of members of list * @param <T> Element type * @return List containing the given members */ @Deprecated // to be removed before 2.0 public static <T> List<T> copy(T... t) { return flatListNotComparable(t); } /** * Creates a memory-, CPU- and cache-efficient comparable immutable list, * always copying the contents. * * <p>The elements are comparable, and so is the returned list. * Elements may be null. * * @param t Array of members of list * @param <T> Element type * @return List containing the given members */ public static <T extends Comparable> List<T> copyOf(T... t) { return flatList_(t, true); } /** * Creates a memory-, CPU- and cache-efficient immutable list, * always copying the contents. * * <p>The elements need not be comparable, * and the returned list may not implement {@link Comparable}. * Elements may be null. * * @param t Array of members of list * @param <T> Element type * @return List containing the given members */ public static <T> List<T> copyOf(T... t) { return flatListNotComparable(t); } /** * Creates a memory-, CPU- and cache-efficient comparable immutable list, * optionally copying the list. * * @param copy Whether to always copy the list * @param t Array of members of list * @return List containing the given members */ private static <T extends Comparable> List<T> flatList_(T[] t, boolean copy) { switch (t.length) { case 0: //noinspection unchecked return COMPARABLE_EMPTY_LIST; case 1: return Collections.singletonList(t[0]); case 2: return new Flat2List<T>(t[0], t[1]); case 3: return new Flat3List<T>(t[0], t[1], t[2]); default: // REVIEW: AbstractList contains a modCount field; we could // write our own implementation and reduce creation overhead a // bit. if (copy) { return new ComparableListImpl<>(Arrays.asList(t.clone())); } else { return new ComparableListImpl<>(Arrays.asList(t)); } } } /** * Creates a memory-, CPU- and cache-efficient immutable list, * always copying the list. * * @param t Array of members of list * @return List containing the given members */ private static <T> List<T> flatListNotComparable(T[] t) { switch (t.length) { case 0: //noinspection unchecked return COMPARABLE_EMPTY_LIST; case 1: return Collections.singletonList(t[0]); case 2: return new Flat2List<>(t[0], t[1]); case 3: return new Flat3List<>(t[0], t[1], t[2]); default: return ImmutableNullableList.copyOf(t); } } /** * Creates a memory-, CPU- and cache-efficient immutable list from an * existing list. The list is always copied. * * @param t Array of members of list * @param <T> Element type * @return List containing the given members */ public static <T> List<T> of(List<T> t) { switch (t.size()) { case 0: //noinspection unchecked return COMPARABLE_EMPTY_LIST; case 1: return Collections.singletonList(t.get(0)); case 2: return new Flat2List<>(t.get(0), t.get(1)); case 3: return new Flat3List<>(t.get(0), t.get(1), t.get(2)); default: // REVIEW: AbstractList contains a modCount field; we could // write our own implementation and reduce creation overhead a // bit. //noinspection unchecked return new ComparableListImpl(Arrays.asList(t.toArray())); } } /** Base class for flat lists. */ public abstract static class AbstractFlatList<T> implements List<T>, RandomAccess { protected final List<T> asArrayList() { //noinspection unchecked return Arrays.asList((T[]) toArray()); } public Iterator<T> iterator() { return asArrayList().iterator(); } public ListIterator<T> listIterator() { return asArrayList().listIterator(); } public boolean isEmpty() { return false; } public boolean add(T t) { throw new UnsupportedOperationException(); } public boolean addAll(Collection<? extends T> c) { throw new UnsupportedOperationException(); } public boolean addAll(int index, Collection<? extends T> c) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public T set(int index, T element) { throw new UnsupportedOperationException(); } public void add(int index, T element) { throw new UnsupportedOperationException(); } public T remove(int index) { throw new UnsupportedOperationException(); } public ListIterator<T> listIterator(int index) { return asArrayList().listIterator(index); } public List<T> subList(int fromIndex, int toIndex) { return asArrayList().subList(fromIndex, toIndex); } public boolean contains(Object o) { return indexOf(o) >= 0; } public boolean containsAll(Collection<?> c) { for (Object o : c) { if (!contains(o)) { return false; } } return true; } public boolean remove(Object o) { throw new UnsupportedOperationException(); } } /** * List that stores its two elements in the two members of the class. * Unlike {@link java.util.ArrayList} or * {@link java.util.Arrays#asList(Object[])} there is * no array, only one piece of memory allocated, therefore is very compact * and cache and CPU efficient. * * <p>The list is read-only and cannot be modified or re-sized. * The elements may be null. * * <p>The list is created via {@link FlatLists#of}. * * @param <T> Element type */ protected static class Flat2List<T> extends AbstractFlatList<T> implements ComparableList<T> { private final T t0; private final T t1; Flat2List(T t0, T t1) { this.t0 = t0; this.t1 = t1; } public String toString() { return "[" + t0 + ", " + t1 + "]"; } public T get(int index) { switch (index) { case 0: return t0; case 1: return t1; default: throw new IndexOutOfBoundsException("index " + index); } } public int size() { return 2; } public Iterator<T> iterator() { return Arrays.asList(t0, t1).iterator(); } public boolean equals(Object o) { if (this == o) { return true; } if (o instanceof Flat2List) { Flat2List that = (Flat2List) o; return Objects.equals(this.t0, that.t0) && Objects.equals(this.t1, that.t1); } return Arrays.asList(t0, t1).equals(o); } public int hashCode() { int h = 1; h = h * 31 + Utilities.hash(t0); h = h * 31 + Utilities.hash(t1); return h; } public int indexOf(Object o) { if (o == null) { if (t0 == null) { return 0; } if (t1 == null) { return 1; } } else { if (t0.equals(o)) { return 0; } if (t1.equals(o)) { return 1; } } return -1; } public int lastIndexOf(Object o) { if (o == null) { if (t1 == null) { return 1; } if (t0 == null) { return 0; } } else { if (t1.equals(o)) { return 1; } if (t0.equals(o)) { return 0; } } return -1; } @SuppressWarnings({"unchecked" }) public <T2> T2[] toArray(T2[] a) { a[0] = (T2) t0; a[1] = (T2) t1; return a; } public Object[] toArray() { return new Object[] {t0, t1}; } public int compareTo(List o) { return ComparableListImpl.compare((List) this, o); } } /** * List that stores its three elements in the three members of the class. * Unlike {@link java.util.ArrayList} or * {@link java.util.Arrays#asList(Object[])} there is * no array, only one piece of memory allocated, therefore is very compact * and cache and CPU efficient. * * <p>The list is read-only, cannot be modified or re-sized. * The elements may be null. * * <p>The list is created via {@link FlatLists#of(java.util.List)}. * * @param <T> Element type */ protected static class Flat3List<T> extends AbstractFlatList<T> implements ComparableList<T> { private final T t0; private final T t1; private final T t2; Flat3List(T t0, T t1, T t2) { this.t0 = t0; this.t1 = t1; this.t2 = t2; } public String toString() { return "[" + t0 + ", " + t1 + ", " + t2 + "]"; } public T get(int index) { switch (index) { case 0: return t0; case 1: return t1; case 2: return t2; default: throw new IndexOutOfBoundsException("index " + index); } } public int size() { return 3; } public Iterator<T> iterator() { return Arrays.asList(t0, t1, t2).iterator(); } public boolean equals(Object o) { if (this == o) { return true; } if (o instanceof Flat3List) { Flat3List that = (Flat3List) o; return Objects.equals(this.t0, that.t0) && Objects.equals(this.t1, that.t1) && Objects.equals(this.t2, that.t2); } return o.equals(this); } public int hashCode() { int h = 1; h = h * 31 + Utilities.hash(t0); h = h * 31 + Utilities.hash(t1); h = h * 31 + Utilities.hash(t2); return h; } public int indexOf(Object o) { if (o == null) { if (t0 == null) { return 0; } if (t1 == null) { return 1; } if (t2 == null) { return 2; } } else { if (t0.equals(o)) { return 0; } if (t1.equals(o)) { return 1; } if (t2.equals(o)) { return 2; } } return -1; } public int lastIndexOf(Object o) { if (o == null) { if (t2 == null) { return 2; } if (t1 == null) { return 1; } if (t0 == null) { return 0; } } else { if (t2.equals(o)) { return 2; } if (t1.equals(o)) { return 1; } if (t0.equals(o)) { return 0; } } return -1; } @SuppressWarnings({"unchecked" }) public <T2> T2[] toArray(T2[] a) { a[0] = (T2) t0; a[1] = (T2) t1; a[2] = (T2) t2; return a; } public Object[] toArray() { return new Object[] {t0, t1, t2}; } public int compareTo(List o) { return ComparableListImpl.compare((List) this, o); } } /** Empty list that implements the {@link Comparable} interface. */ private static class ComparableEmptyList<T> extends AbstractList<T> implements ComparableList<T> { private ComparableEmptyList() { } public T get(int index) { throw new IndexOutOfBoundsException(); } public int hashCode() { return 1; // same as Collections.emptyList() } public boolean equals(Object o) { return o == this || o instanceof List && ((List) o).isEmpty(); } public int size() { return 0; } public int compareTo(List o) { return ComparableListImpl.compare((List) this, o); } } /** List that is also comparable. * * <p>You can create an instance whose type * parameter {@code T} does not extend {@link Comparable}, but you will get a * {@link ClassCastException} at runtime when you call * {@link #compareTo(Object)} if the elements of the list do not implement * {@code Comparable}. */ public interface ComparableList<T> extends List<T>, Comparable<List> { } /** Wrapper around a list that makes it implement the {@link Comparable} * interface using lexical ordering. The elements must be comparable. */ static class ComparableListImpl<T extends Comparable<T>> extends AbstractList<T> implements ComparableList<T> { private final List<T> list; protected ComparableListImpl(List<T> list) { this.list = list; } public T get(int index) { return list.get(index); } public int size() { return list.size(); } public int compareTo(List o) { return compare(list, o); } static <T extends Comparable<T>> int compare(List<T> list0, List<T> list1) { final int size0 = list0.size(); final int size1 = list1.size(); if (size1 == size0) { return compare(list0, list1, size0); } final int c = compare(list0, list1, Math.min(size0, size1)); if (c != 0) { return c; } return size0 - size1; } static <T extends Comparable<T>> int compare(List<T> list0, List<T> list1, int size) { for (int i = 0; i < size; i++) { Comparable o0 = list0.get(i); Comparable o1 = list1.get(i); int c = compare(o0, o1); if (c != 0) { return c; } } return 0; } static <T extends Comparable<T>> int compare(T a, T b) { if (a == b) { return 0; } if (a == null) { return -1; } if (b == null) { return 1; } return a.compareTo(b); } } } // End FlatLists.java
joshelser/incubator-calcite
core/src/main/java/org/apache/calcite/runtime/FlatLists.java
Java
apache-2.0
15,891
package com.nesei.minhash.service.impl; import com.nesei.minhash.service.CalculateService; import org.springframework.stereotype.Service; import java.util.HashMap; /** * @Author wzy * @Date 2016/11/18 20:30 */ @Service("CalculateService") public class CalculateServiceImpl implements CalculateService { public float calcXlsOfMinhash(String hashA, String hashB) { float xslMinwise = 0.0f; String[] hashArrayA = hashA.split("\\|"); String[] hashArrayB = hashB.split("\\|"); int count = 0; int size = Math.min(hashArrayA.length, hashArrayB.length); for (int i = 0; i < size; i++) { if (hashArrayA[i].equals(hashArrayB[i])) { count++; } } xslMinwise = (float) count / size; return xslMinwise; } public float calcXlsOfOnePerHash(String hashA, String hashB, boolean isEmptyPartitionEqual) { float xslMinwise = 0.0f; String[] hashArrayA = hashA.split("\\|"); String[] hashArrayB = hashB.split("\\|"); int count = 0; int size = Math.min(hashArrayA.length, hashArrayB.length); int lastSize = size; for (int i = 0; i < size; i++) { // if (hashArrayA[i].equals("*")) {//认为空区相等 // //认为空区相等 // if (isEmptyPartitionEqual) { // count++; // } // } else {//认为空区不相等 // if (hashArrayA[i].equals(hashArrayB[i])) { // count++; // } // } if ( hashArrayA[i].equals("*") && hashArrayB[i].equals("*")) { //均为空区 lastSize --; continue; } if ( hashArrayA[i].equals(hashArrayB[i])) { //其中之一为空区 count ++; } } xslMinwise = (float) count / lastSize; return xslMinwise; } public float calcXslOfShingle(String shgA, String shgB) { int samenum = 0; float xsl = 0.0f; String[] arrStrA = shgA.split("\\|"); String[] arrStrB = shgB.split("\\|"); int strASize = arrStrA.length; int strBSize = arrStrB.length; HashMap<String, String> ht1 = new HashMap<String, String>(); HashMap<String, String> ht2 = new HashMap<String, String>(); for (int i = 0; i < strASize; i++) { String ashg = arrStrA[i]; if (!ht1.containsKey(ashg)) { ht1.put(ashg, ashg); } } for (int i = 0; i < strBSize; i++) { String bshg = arrStrB[i]; if (!ht2.containsKey(bshg)) { ht2.put(bshg, bshg); } } for (String bshg : ht2.keySet()) { if (ht1.containsKey(bshg)) { samenum++; } } xsl = (float) samenum / (float) (ht1.size() + ht2.size() - samenum); return xsl; } } //~ Formatted by Jindent --- http://www.jindent.com
wang-zhen-yu/minhash
src/main/java/com/nesei/minhash/service/impl/CalculateServiceImpl.java
Java
apache-2.0
3,059
package sample.sdr.auth.config; import org.springframework.context.annotation.Configuration; import org.springframework.data.rest.core.config.RepositoryRestConfiguration; import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration; /** * To change any default config, we need to subclass * RepositoryRestMvcConfiguration * */ @Configuration public class CustomRepositoryRestMvcConfiguration extends RepositoryRestMvcConfiguration { @Override protected void configureRepositoryRestConfiguration( RepositoryRestConfiguration config) { config.setDefaultPageSize(1000); } }
charybr/spring-data-rest-acl
bookstore/src/main/java/sample/sdr/auth/config/CustomRepositoryRestMvcConfiguration.java
Java
apache-2.0
610
package org.imirsel.nema.model; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import javax.persistence.*; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.Set; import org.apache.commons.lang.RandomStringUtils; /** * This class represents the basic "user" object in AppFuse that allows for authentication * and user management. It implements Acegi Security's UserDetails interface. * * @author <a href="mailto:[email protected]">Matt Raible</a> * Updated by Dan Kibler ([email protected]) * Extended to implement Acegi UserDetails interface * by David Carter [email protected] */ @Entity @Table(name="app_user") public class User extends BaseObject implements Serializable, UserDetails { private static final long serialVersionUID = 3832626162173359411L; private Long id; private String username; private String password;// required private Integer version; private Set<Role> roles = new HashSet<Role>(); private boolean enabled; private boolean accountExpired; private boolean accountLocked; private boolean credentialsExpired; private Set<PreferenceValue> preferences = new HashSet<PreferenceValue>(); private Profile profile; /** * Default constructor - creates a new instance with no values set. * Generated a 20-30 random string as the password. * (Real authentication is done through OpenID). */ public User() { Random random=new Random(); password=RandomStringUtils.random(random.nextInt(10)+20); } /** * Create a new instance and set the username. * @param username login name for user. */ public User(final String username) { this.username = username; } @Id @GeneratedValue(strategy=GenerationType.AUTO) public Long getId() { return id; } @Column(nullable=false,length=200,unique=true) public String getUsername() { return username; } @Transient public String getFirstName() { return this.profile.getFirstname(); } @Transient public String getLastName() { return this.profile.getLastname(); } @Transient public String getEmail() { return this.profile.getEmail(); } /* @Column(name="phone_number") public String getPhoneNumber() { return phoneNumber; } public String getWebsite() { return website; } */ /** * Returns the full name. * @return firstName + ' ' + lastName */ @Transient public String getFullName() { return this.profile.getFirstname() + ' ' + this.profile.getLastname(); } /* @Embedded public Address getAddress() { return address; } */ @ManyToMany(fetch = FetchType.EAGER) @JoinTable( name="user_role", joinColumns = { @JoinColumn( name="user_id") }, inverseJoinColumns = @JoinColumn( name="role_id") ) public Set<Role> getRoles() { return roles; } @OneToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL) @JoinTable( name="user_prefs", joinColumns = { @JoinColumn( name="user_id") } ) public Set<PreferenceValue> getPreferences(){ return preferences; } /** * We are using OpenID to manage authentication. * Local password is not necessary. * This password is generated when user is created and used for later authentication, * for example in repository. * @return */ public String getPassword() { return password; } public void addPreference(PreferenceValue pvalue) { preferences.add(pvalue); } public void addPreference(String key, String value) { PreferenceValue pvalue = new PreferenceValue(key,value); preferences.add(pvalue); } public String getPreference(String key){ for(PreferenceValue pv: preferences){ if(pv.getKey().equals(key)){ return pv.getValue(); } } return null; } public boolean updatePreference(String key, String value) { boolean updated=Boolean.FALSE; for(PreferenceValue pv: preferences){ if(pv.getKey().equals(key)){ pv.setValue(value); updated= Boolean.TRUE; return updated; } } if(!updated){ preferences.add(new PreferenceValue(key,value)); } return updated; } public boolean removePreference(String key){ Iterator<PreferenceValue> it = preferences.iterator(); boolean success= Boolean.FALSE; while(it.hasNext()){ PreferenceValue pval=it.next(); if(pval.getKey().equals(key)){ it.remove(); success = Boolean.TRUE; } } return success; } @Transient public List<LabelValue> getPreferenceValueList(){ List<LabelValue> list= new ArrayList<LabelValue>(); if (this.roles != null) { for (PreferenceValue p : preferences) { // convert the user's preference to LabelValue Objects list.add(new LabelValue(p.getKey(), p.getValue())); } } return list; } /** * Convert user roles to LabelValue objects for convenience. * @return a list of LabelValue objects with role information */ @Transient public List<LabelValue> getRoleList() { List<LabelValue> userRoles = new ArrayList<LabelValue>(); if (this.roles != null) { for (Role role : roles) { // convert the user's roles to LabelValue Objects userRoles.add(new LabelValue(role.getName(), role.getName())); } } return userRoles; } /** * Adds a role for the user * @param role the fully instantiated role */ public void addRole(Role role) { getRoles().add(role); } /** * @see org.springframework.security.userdetails.UserDetails#getAuthorities() * @return Collection<GrantedAuthority> */ @Transient public Collection<GrantedAuthority> getAuthorities() { Collection<GrantedAuthority> grantedAuthorityCollection = new ArrayList<GrantedAuthority>(); for(Role role:roles){ grantedAuthorityCollection.add(role);} return grantedAuthorityCollection; } @Version public Integer getVersion() { return version; } @Column(name="account_enabled") public boolean isEnabled() { return enabled; } @Column(name="account_expired",nullable=false) public boolean isAccountExpired() { return accountExpired; } /** * @see org.springframework.security.userdetails.UserDetails#isAccountNonExpired() */ @Transient public boolean isAccountNonExpired() { return !isAccountExpired(); } @Column(name="account_locked",nullable=false) public boolean isAccountLocked() { return accountLocked; } /** * @see org.springframework.security.userdetails.UserDetails#isAccountNonLocked() */ @Transient public boolean isAccountNonLocked() { return !isAccountLocked(); } @Column(name="credentials_expired",nullable=false) public boolean isCredentialsExpired() { return credentialsExpired; } @OneToOne(cascade={CascadeType.MERGE,CascadeType.PERSIST}) @JoinColumn(unique=true,name="profile_id") public Profile getProfile() { return profile; } /** * @see org.springframework.security.userdetails.UserDetails#isCredentialsNonExpired() */ @Transient public boolean isCredentialsNonExpired() { return !credentialsExpired; } public void setId(Long id) { this.id = id; } public void setUsername(String username) { this.username = username; } public void setRoles(Set<Role> roles) { this.roles = roles; } public void setPreferences(Set<PreferenceValue> pvalues){ this.preferences=pvalues; } public void setVersion(Integer version) { this.version = version; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public void setAccountExpired(boolean accountExpired) { this.accountExpired = accountExpired; } public void setAccountLocked(boolean accountLocked) { this.accountLocked = accountLocked; } public void setCredentialsExpired(boolean credentialsExpired) { this.credentialsExpired = credentialsExpired; } public void setProfile(Profile profile) { this.profile = profile; } /** * This method is only for Hibernate to populate the object from database, * password is set once the user is created and should not be changed or set * ever since as the authentication is through OpenId. * @param password */ public void setPassword(String password){ this.password=password; } /** * {@inheritDoc} */ public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof User)) { return false; } final User user = (User) o; return !(username != null ? !username.equals(user.getUsername()) : user.getUsername() != null); } /** * {@inheritDoc} */ public int hashCode() { return (username != null ? username.hashCode() : 0); } /** * {@inheritDoc} */ public String toString() { ToStringBuilder sb = new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE) .append("username", this.username) .append("enabled", this.enabled) .append("accountExpired", this.accountExpired) .append("credentialsExpired", this.credentialsExpired) .append("accountLocked", this.accountLocked); Collection<GrantedAuthority> auths = this.getAuthorities(); if (auths != null) { sb.append("Granted Authorities: "); int i=0; for (GrantedAuthority auth:auths) { if (i > 0) { sb.append(", "); } sb.append(auth.toString()); i++; } } else { sb.append("No Granted Authorities"); } return sb.toString(); } }
kumaramit01/DIY
core/src/main/java/org/imirsel/nema/model/User.java
Java
apache-2.0
10,811
/* * Sonar ESQL Plugin * Copyright (C) 2013-2022 Thomas Pohl and EXXETA AG * http://www.exxeta.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.exxeta.iss.sonar.esql.api.tree.function; import com.exxeta.iss.sonar.esql.api.tree.expression.ExpressionTree; import com.exxeta.iss.sonar.esql.api.tree.lexical.SyntaxToken; public interface TheFunctionTree extends ListFunctionTree { SyntaxToken theKeyword(); SyntaxToken openingParenthesis(); ExpressionTree expression(); SyntaxToken closingParenthesis(); }
EXXETA/sonar-esql-plugin
esql-frontend/src/main/java/com/exxeta/iss/sonar/esql/api/tree/function/TheFunctionTree.java
Java
apache-2.0
1,049
/* * Trident - A Multithreaded Server Alternative * Copyright 2017 The TridentSDK Team * * 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 net.tridentsdk.server.player; import lombok.AccessLevel; import lombok.NoArgsConstructor; import net.tridentsdk.base.Position; import net.tridentsdk.entity.Entity; import net.tridentsdk.entity.living.Player; import net.tridentsdk.server.entity.TridentEntity; import net.tridentsdk.server.packet.PacketOut; import net.tridentsdk.server.world.TridentChunk; import net.tridentsdk.server.world.TridentWorld; import javax.annotation.concurrent.Immutable; import java.util.Set; /** * Utility class that contains shortcuts for selecting * specific recipients of a particular packet. */ @Immutable @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class RecipientSelector { /** * Sends the given packet to those who can see the given * entity, as well as the given entity too if the flag * is set to {@code true}. * * @param chunk the chunk in which holders will be * selected to receive the given packet * @param exclude a non-null player if they should be * excluded * @param packetOut the packets to send to the selected * targets */ public static void whoCanSee(TridentChunk chunk, Entity exclude, PacketOut... packetOut) { if (chunk == null) { throw new IllegalStateException("Player cannot inhabit an unloaded chunk"); } Set<TridentPlayer> targets = chunk.getHolders(); if (exclude == null || !(exclude instanceof Player)) { for (TridentPlayer p : targets) { for (PacketOut out : packetOut) { p.net().sendPacket(out); } } } else { for (TridentPlayer p : targets) { if (p.equals(exclude)) { continue; } for (PacketOut out : packetOut) { p.net().sendPacket(out); } } } } /** * Sends the given packet to those who can see the given * entity. * * @param canSee the entity that can be seen * @param exclude whether or not to exclude the player * @param packetOut the packets to send to selected * recipients */ public static void whoCanSee(TridentEntity canSee, boolean exclude, PacketOut... packetOut) { Position pos = canSee.getPosition(); whoCanSee(canSee.getWorld().getChunkAt(pos.getChunkX(), pos.getChunkZ(), true), exclude ? canSee : null, packetOut); } /** * Sends the given packet to all players who are * occupants of the given world. * * @param world the world in which the players are the * target of the packet to be sent * @param packetOut the packets to send to the selected * players */ public static void inWorld(TridentWorld world, PacketOut... packetOut) { for (TridentPlayer player : world.getOccupants()) { for (PacketOut out : packetOut) { player.net().sendPacket(out); } } } }
TridentSDK/Trident
src/main/java/net/tridentsdk/server/player/RecipientSelector.java
Java
apache-2.0
3,695
package com.itheima.mobilesafe.utils; import android.content.Context; public class DensityUtil { /** * 根据手机的分辨率从 dip 的单位 转成为 px(像素) */ public static int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** * 根据手机的分辨率从 px(像素) 的单位 转成为 dp */ public static int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } }
qq644531343/MobileSafe
src/com/itheima/mobilesafe/utils/DensityUtil.java
Java
apache-2.0
611
package org.docksidestage.hangar.dbflute.bsbhv; import java.util.List; import org.dbflute.*; import org.dbflute.bhv.readable.*; import org.dbflute.bhv.writable.*; import org.dbflute.bhv.writable.coins.DateUpdateAdjuster; import org.dbflute.bhv.referrer.*; import org.dbflute.cbean.*; import org.dbflute.cbean.chelper.HpSLSFunction; import org.dbflute.cbean.result.*; import org.dbflute.exception.*; import org.dbflute.optional.OptionalEntity; import org.dbflute.outsidesql.executor.*; import org.docksidestage.hangar.dbflute.allcommon.CDef; import org.docksidestage.hangar.dbflute.exbhv.*; import org.docksidestage.hangar.dbflute.bsbhv.loader.*; import org.docksidestage.hangar.dbflute.exentity.*; import org.docksidestage.hangar.dbflute.bsentity.dbmeta.*; import org.docksidestage.hangar.dbflute.cbean.*; /** * The behavior of (地域)REGION as TABLE. <br> * <pre> * [primary key] * REGION_ID * * [column] * REGION_ID, REGION_NAME * * [sequence] * * * [identity] * * * [version-no] * * * [foreign table] * * * [referrer table] * MEMBER_ADDRESS * * [foreign property] * * * [referrer property] * memberAddressList * </pre> * @author DBFlute(AutoGenerator) */ public abstract class BsRegionBhv extends org.docksidestage.hangar.dbflute.nogen.ExtendedAbstractBehaviorWritable<Region, RegionCB> { // =================================================================================== // Definition // ========== /*df:beginQueryPath*/ /*df:endQueryPath*/ // =================================================================================== // DB Meta // ======= /** {@inheritDoc} */ public RegionDbm asDBMeta() { return RegionDbm.getInstance(); } /** {@inheritDoc} */ public String asTableDbName() { return "REGION"; } // =================================================================================== // New Instance // ============ /** {@inheritDoc} */ public RegionCB newConditionBean() { return new RegionCB(); } // =================================================================================== // Count Select // ============ /** * Select the count of uniquely-selected records by the condition-bean. {IgnorePagingCondition, IgnoreSpecifyColumn}<br> * SpecifyColumn is ignored but you can use it only to remove text type column for union's distinct. * <pre> * <span style="color: #70226C">int</span> count = <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">selectCount</span>(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().set... * }); * </pre> * @param cbLambda The callback for condition-bean of Region. (NotNull) * @return The count for the condition. (NotMinus) */ public int selectCount(CBCall<RegionCB> cbLambda) { return facadeSelectCount(createCB(cbLambda)); } // =================================================================================== // Entity Select // ============= /** * Select the entity by the condition-bean. <br> * It returns not-null optional entity, so you should ... <br> * <span style="color: #AD4747; font-size: 120%">If the data is always present as your business rule, alwaysPresent().</span> <br> * <span style="color: #AD4747; font-size: 120%">If it might be no data, isPresent() and orElse(), ...</span> * <pre> * <span style="color: #3F7E5E">// if the data always exists as your business rule</span> * <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">selectEntity</span>(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().set... * }).<span style="color: #CC4747">alwaysPresent</span>(<span style="color: #553000">region</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #3F7E5E">// called if present, or exception</span> * ... = <span style="color: #553000">region</span>.get... * }); * * <span style="color: #3F7E5E">// if it might be no data, ...</span> * <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">selectEntity</span>(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().set... * }).<span style="color: #CC4747">ifPresent</span>(<span style="color: #553000">region</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #3F7E5E">// called if present</span> * ... = <span style="color: #553000">region</span>.get... * }).<span style="color: #994747">orElse</span>(() <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #3F7E5E">// called if not present</span> * }); * </pre> * @param cbLambda The callback for condition-bean of Region. (NotNull) * @return The optional entity selected by the condition. (NotNull: if no data, empty entity) * @throws EntityAlreadyDeletedException When get(), required() of return value is called and the value is null, which means entity has already been deleted (not found). * @throws EntityDuplicatedException When the entity has been duplicated. * @throws SelectEntityConditionNotFoundException When the condition for selecting an entity is not found. */ public OptionalEntity<Region> selectEntity(CBCall<RegionCB> cbLambda) { return facadeSelectEntity(createCB(cbLambda)); } protected OptionalEntity<Region> facadeSelectEntity(RegionCB cb) { return doSelectOptionalEntity(cb, typeOfSelectedEntity()); } protected <ENTITY extends Region> OptionalEntity<ENTITY> doSelectOptionalEntity(RegionCB cb, Class<? extends ENTITY> tp) { return createOptionalEntity(doSelectEntity(cb, tp), cb); } protected Entity doReadEntity(ConditionBean cb) { return facadeSelectEntity(downcast(cb)).orElse(null); } /** * Select the entity by the condition-bean with deleted check. <br> * <span style="color: #AD4747; font-size: 120%">If the data is always present as your business rule, this method is good.</span> * <pre> * Region <span style="color: #553000">region</span> = <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">selectEntityWithDeletedCheck</span>(cb <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> cb.acceptPK(1)); * ... = <span style="color: #553000">region</span>.get...(); <span style="color: #3F7E5E">// the entity always be not null</span> * </pre> * @param cbLambda The callback for condition-bean of Region. (NotNull) * @return The entity selected by the condition. (NotNull: if no data, throws exception) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. * @throws SelectEntityConditionNotFoundException When the condition for selecting an entity is not found. */ public Region selectEntityWithDeletedCheck(CBCall<RegionCB> cbLambda) { return facadeSelectEntityWithDeletedCheck(createCB(cbLambda)); } /** * Select the entity by the primary-key value. * @param regionId (地域ID): PK, NotNull, INTEGER(10), classification=Region. (NotNull) * @return The optional entity selected by the PK. (NotNull: if no data, empty entity) * @throws EntityAlreadyDeletedException When get(), required() of return value is called and the value is null, which means entity has already been deleted (not found). * @throws EntityDuplicatedException When the entity has been duplicated. * @throws SelectEntityConditionNotFoundException When the condition for selecting an entity is not found. */ public OptionalEntity<Region> selectByPK(CDef.Region regionId) { return facadeSelectByPK(regionId); } protected OptionalEntity<Region> facadeSelectByPK(CDef.Region regionId) { return doSelectOptionalByPK(regionId, typeOfSelectedEntity()); } protected <ENTITY extends Region> ENTITY doSelectByPK(CDef.Region regionId, Class<? extends ENTITY> tp) { return doSelectEntity(xprepareCBAsPK(regionId), tp); } protected <ENTITY extends Region> OptionalEntity<ENTITY> doSelectOptionalByPK(CDef.Region regionId, Class<? extends ENTITY> tp) { return createOptionalEntity(doSelectByPK(regionId, tp), regionId); } protected RegionCB xprepareCBAsPK(CDef.Region regionId) { assertObjectNotNull("regionId", regionId); return newConditionBean().acceptPK(regionId); } // =================================================================================== // List Select // =========== /** * Select the list as result bean. * <pre> * ListResultBean&lt;Region&gt; <span style="color: #553000">regionList</span> = <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">selectList</span>(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().set...; * <span style="color: #553000">cb</span>.query().addOrderBy...; * }); * <span style="color: #70226C">for</span> (Region <span style="color: #553000">region</span> : <span style="color: #553000">regionList</span>) { * ... = <span style="color: #553000">region</span>.get...; * } * </pre> * @param cbLambda The callback for condition-bean of Region. (NotNull) * @return The result bean of selected list. (NotNull: if no data, returns empty list) * @throws DangerousResultSizeException When the result size is over the specified safety size. */ public ListResultBean<Region> selectList(CBCall<RegionCB> cbLambda) { return facadeSelectList(createCB(cbLambda)); } @Override protected boolean isEntityDerivedMappable() { return true; } // =================================================================================== // Page Select // =========== /** * Select the page as result bean. <br> * (both count-select and paging-select are executed) * <pre> * PagingResultBean&lt;Region&gt; <span style="color: #553000">page</span> = <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">selectPage</span>(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().set... * <span style="color: #553000">cb</span>.query().addOrderBy... * <span style="color: #553000">cb</span>.<span style="color: #CC4747">paging</span>(20, 3); <span style="color: #3F7E5E">// 20 records per a page and current page number is 3</span> * }); * <span style="color: #70226C">int</span> allRecordCount = <span style="color: #553000">page</span>.getAllRecordCount(); * <span style="color: #70226C">int</span> allPageCount = <span style="color: #553000">page</span>.getAllPageCount(); * <span style="color: #70226C">boolean</span> isExistPrePage = <span style="color: #553000">page</span>.isExistPrePage(); * <span style="color: #70226C">boolean</span> isExistNextPage = <span style="color: #553000">page</span>.isExistNextPage(); * ... * <span style="color: #70226C">for</span> (Region region : <span style="color: #553000">page</span>) { * ... = region.get...; * } * </pre> * @param cbLambda The callback for condition-bean of Region. (NotNull) * @return The result bean of selected page. (NotNull: if no data, returns bean as empty list) * @throws DangerousResultSizeException When the result size is over the specified safety size. */ public PagingResultBean<Region> selectPage(CBCall<RegionCB> cbLambda) { return facadeSelectPage(createCB(cbLambda)); } // =================================================================================== // Cursor Select // ============= /** * Select the cursor by the condition-bean. * <pre> * <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">selectCursor</span>(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().set... * }, <span style="color: #553000">member</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * ... = <span style="color: #553000">member</span>.getMemberName(); * }); * </pre> * @param cbLambda The callback for condition-bean of Region. (NotNull) * @param entityLambda The handler of entity row of Region. (NotNull) */ public void selectCursor(CBCall<RegionCB> cbLambda, EntityRowHandler<Region> entityLambda) { facadeSelectCursor(createCB(cbLambda), entityLambda); } // =================================================================================== // Scalar Select // ============= /** * Select the scalar value derived by a function from uniquely-selected records. <br> * You should call a function method after this method called like as follows: * <pre> * <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">selectScalar</span>(Date.class).max(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.specify().<span style="color: #CC4747">column...</span>; <span style="color: #3F7E5E">// required for the function</span> * <span style="color: #553000">cb</span>.query().set... * }); * </pre> * @param <RESULT> The type of result. * @param resultType The type of result. (NotNull) * @return The scalar function object to specify function for scalar value. (NotNull) */ public <RESULT> HpSLSFunction<RegionCB, RESULT> selectScalar(Class<RESULT> resultType) { return facadeScalarSelect(resultType); } // =================================================================================== // Sequence // ======== @Override protected Number doReadNextVal() { String msg = "This table is NOT related to sequence: " + asTableDbName(); throw new UnsupportedOperationException(msg); } // =================================================================================== // Load Referrer // ============= /** * Load referrer for the list by the referrer loader. * <pre> * List&lt;Member&gt; <span style="color: #553000">memberList</span> = <span style="color: #0000C0">memberBhv</span>.selectList(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().set... * }); * memberBhv.<span style="color: #CC4747">load</span>(<span style="color: #553000">memberList</span>, <span style="color: #553000">memberLoader</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">memberLoader</span>.<span style="color: #CC4747">loadPurchase</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">purchaseCB</span>.setupSelect... * <span style="color: #553000">purchaseCB</span>.query().set... * <span style="color: #553000">purchaseCB</span>.query().addOrderBy... * }); <span style="color: #3F7E5E">// you can also load nested referrer from here</span> * <span style="color: #3F7E5E">//}).withNestedReferrer(purchaseLoader -&gt; {</span> * <span style="color: #3F7E5E">// purchaseLoader.loadPurchasePayment(...);</span> * <span style="color: #3F7E5E">//});</span> * * <span style="color: #3F7E5E">// you can also pull out foreign table and load its referrer</span> * <span style="color: #3F7E5E">// (setupSelect of the foreign table should be called)</span> * <span style="color: #3F7E5E">//memberLoader.pulloutMemberStatus().loadMemberLogin(...)</span> * }); * <span style="color: #70226C">for</span> (Member member : <span style="color: #553000">memberList</span>) { * List&lt;Purchase&gt; purchaseList = member.<span style="color: #CC4747">getPurchaseList()</span>; * <span style="color: #70226C">for</span> (Purchase purchase : purchaseList) { * ... * } * } * </pre> * About internal policy, the value of primary key (and others too) is treated as case-insensitive. <br> * The condition-bean, which the set-upper provides, has order by FK before callback. * @param regionList The entity list of region. (NotNull) * @param loaderLambda The callback to handle the referrer loader for actually loading referrer. (NotNull) */ public void load(List<Region> regionList, ReferrerLoaderHandler<LoaderOfRegion> loaderLambda) { xassLRArg(regionList, loaderLambda); loaderLambda.handle(new LoaderOfRegion().ready(regionList, _behaviorSelector)); } /** * Load referrer for the entity by the referrer loader. * <pre> * Member <span style="color: #553000">member</span> = <span style="color: #0000C0">memberBhv</span>.selectEntityWithDeletedCheck(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> <span style="color: #553000">cb</span>.acceptPK(1)); * <span style="color: #0000C0">memberBhv</span>.<span style="color: #CC4747">load</span>(<span style="color: #553000">member</span>, <span style="color: #553000">memberLoader</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">memberLoader</span>.<span style="color: #CC4747">loadPurchase</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">purchaseCB</span>.setupSelect... * <span style="color: #553000">purchaseCB</span>.query().set... * <span style="color: #553000">purchaseCB</span>.query().addOrderBy... * }); <span style="color: #3F7E5E">// you can also load nested referrer from here</span> * <span style="color: #3F7E5E">//}).withNestedReferrer(purchaseLoader -&gt; {</span> * <span style="color: #3F7E5E">// purchaseLoader.loadPurchasePayment(...);</span> * <span style="color: #3F7E5E">//});</span> * * <span style="color: #3F7E5E">// you can also pull out foreign table and load its referrer</span> * <span style="color: #3F7E5E">// (setupSelect of the foreign table should be called)</span> * <span style="color: #3F7E5E">//memberLoader.pulloutMemberStatus().loadMemberLogin(...)</span> * }); * List&lt;Purchase&gt; purchaseList = <span style="color: #553000">member</span>.<span style="color: #CC4747">getPurchaseList()</span>; * <span style="color: #70226C">for</span> (Purchase purchase : purchaseList) { * ... * } * </pre> * About internal policy, the value of primary key (and others too) is treated as case-insensitive. <br> * The condition-bean, which the set-upper provides, has order by FK before callback. * @param region The entity of region. (NotNull) * @param loaderLambda The callback to handle the referrer loader for actually loading referrer. (NotNull) */ public void load(Region region, ReferrerLoaderHandler<LoaderOfRegion> loaderLambda) { xassLRArg(region, loaderLambda); loaderLambda.handle(new LoaderOfRegion().ready(xnewLRAryLs(region), _behaviorSelector)); } /** * Load referrer of memberAddressList by the set-upper of referrer. <br> * (会員住所情報)MEMBER_ADDRESS by REGION_ID, named 'memberAddressList'. * <pre> * <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">loadMemberAddress</span>(<span style="color: #553000">regionList</span>, <span style="color: #553000">addressCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">addressCB</span>.setupSelect... * <span style="color: #553000">addressCB</span>.query().set... * <span style="color: #553000">addressCB</span>.query().addOrderBy... * }); <span style="color: #3F7E5E">// you can load nested referrer from here</span> * <span style="color: #3F7E5E">//}).withNestedReferrer(referrerList -&gt; {</span> * <span style="color: #3F7E5E">// ...</span> * <span style="color: #3F7E5E">//});</span> * <span style="color: #70226C">for</span> (Region region : <span style="color: #553000">regionList</span>) { * ... = region.<span style="color: #CC4747">getMemberAddressList()</span>; * } * </pre> * About internal policy, the value of primary key (and others too) is treated as case-insensitive. <br> * The condition-bean, which the set-upper provides, has settings before callback as follows: * <pre> * cb.query().setRegionId_InScope(pkList); * cb.query().addOrderBy_RegionId_Asc(); * </pre> * @param regionList The entity list of region. (NotNull) * @param refCBLambda The callback to set up referrer condition-bean for loading referrer. (NotNull) * @return The callback interface which you can load nested referrer by calling withNestedReferrer(). (NotNull) */ public NestedReferrerListGateway<MemberAddress> loadMemberAddress(List<Region> regionList, ReferrerConditionSetupper<MemberAddressCB> refCBLambda) { xassLRArg(regionList, refCBLambda); return doLoadMemberAddress(regionList, new LoadReferrerOption<MemberAddressCB, MemberAddress>().xinit(refCBLambda)); } /** * Load referrer of memberAddressList by the set-upper of referrer. <br> * (会員住所情報)MEMBER_ADDRESS by REGION_ID, named 'memberAddressList'. * <pre> * <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">loadMemberAddress</span>(<span style="color: #553000">region</span>, <span style="color: #553000">addressCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">addressCB</span>.setupSelect... * <span style="color: #553000">addressCB</span>.query().set... * <span style="color: #553000">addressCB</span>.query().addOrderBy... * }); <span style="color: #3F7E5E">// you can load nested referrer from here</span> * <span style="color: #3F7E5E">//}).withNestedReferrer(referrerList -&gt; {</span> * <span style="color: #3F7E5E">// ...</span> * <span style="color: #3F7E5E">//});</span> * ... = <span style="color: #553000">region</span>.<span style="color: #CC4747">getMemberAddressList()</span>; * </pre> * About internal policy, the value of primary key (and others too) is treated as case-insensitive. <br> * The condition-bean, which the set-upper provides, has settings before callback as follows: * <pre> * cb.query().setRegionId_InScope(pkList); * cb.query().addOrderBy_RegionId_Asc(); * </pre> * @param region The entity of region. (NotNull) * @param refCBLambda The callback to set up referrer condition-bean for loading referrer. (NotNull) * @return The callback interface which you can load nested referrer by calling withNestedReferrer(). (NotNull) */ public NestedReferrerListGateway<MemberAddress> loadMemberAddress(Region region, ReferrerConditionSetupper<MemberAddressCB> refCBLambda) { xassLRArg(region, refCBLambda); return doLoadMemberAddress(xnewLRLs(region), new LoadReferrerOption<MemberAddressCB, MemberAddress>().xinit(refCBLambda)); } protected NestedReferrerListGateway<MemberAddress> doLoadMemberAddress(List<Region> regionList, LoadReferrerOption<MemberAddressCB, MemberAddress> option) { return helpLoadReferrerInternally(regionList, option, "memberAddressList"); } // =================================================================================== // Pull out Relation // ================= // =================================================================================== // Extract Column // ============== /** * Extract the value list of (single) primary key regionId. * @param regionList The list of region. (NotNull, EmptyAllowed) * @return The list of the column value. (NotNull, EmptyAllowed, NotNullElement) */ public List<Integer> extractRegionIdList(List<Region> regionList) { return helpExtractListInternally(regionList, "regionId"); } // =================================================================================== // Entity Update // ============= /** * Insert the entity modified-only. (DefaultConstraintsEnabled) * <pre> * Region region = <span style="color: #70226C">new</span> Region(); * <span style="color: #3F7E5E">// if auto-increment, you don't need to set the PK value</span> * region.setFoo...(value); * region.setBar...(value); * <span style="color: #3F7E5E">// you don't need to set values of common columns</span> * <span style="color: #3F7E5E">//region.setRegisterUser(value);</span> * <span style="color: #3F7E5E">//region.set...;</span> * <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">insert</span>(region); * ... = region.getPK...(); <span style="color: #3F7E5E">// if auto-increment, you can get the value after</span> * </pre> * <p>While, when the entity is created by select, all columns are registered.</p> * @param region The entity of insert. (NotNull, PrimaryKeyNullAllowed: when auto-increment) * @throws EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void insert(Region region) { doInsert(region, null); } /** * Update the entity modified-only. (ZeroUpdateException, NonExclusiveControl) <br> * By PK as default, and also you can update by unique keys using entity's uniqueOf(). * <pre> * Region region = <span style="color: #70226C">new</span> Region(); * region.setPK...(value); <span style="color: #3F7E5E">// required</span> * region.setFoo...(value); <span style="color: #3F7E5E">// you should set only modified columns</span> * <span style="color: #3F7E5E">// you don't need to set values of common columns</span> * <span style="color: #3F7E5E">//region.setRegisterUser(value);</span> * <span style="color: #3F7E5E">//region.set...;</span> * <span style="color: #3F7E5E">// if exclusive control, the value of concurrency column is required</span> * region.<span style="color: #CC4747">setVersionNo</span>(value); * <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">update</span>(region); * </pre> * @param region The entity of update. (NotNull, PrimaryKeyNotNull) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. * @throws EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void update(Region region) { doUpdate(region, null); } /** * Insert or update the entity modified-only. (DefaultConstraintsEnabled, NonExclusiveControl) <br> * if (the entity has no PK) { insert() } else { update(), but no data, insert() } <br> * <p><span style="color: #994747; font-size: 120%">Also you can update by unique keys using entity's uniqueOf().</span></p> * @param region The entity of insert or update. (NotNull, ...depends on insert or update) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. * @throws EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void insertOrUpdate(Region region) { doInsertOrUpdate(region, null, null); } /** * Delete the entity. (ZeroUpdateException, NonExclusiveControl) <br> * By PK as default, and also you can delete by unique keys using entity's uniqueOf(). * <pre> * Region region = <span style="color: #70226C">new</span> Region(); * region.setPK...(value); <span style="color: #3F7E5E">// required</span> * <span style="color: #3F7E5E">// if exclusive control, the value of concurrency column is required</span> * region.<span style="color: #CC4747">setVersionNo</span>(value); * <span style="color: #70226C">try</span> { * <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">delete</span>(region); * } <span style="color: #70226C">catch</span> (EntityAlreadyUpdatedException e) { <span style="color: #3F7E5E">// if concurrent update</span> * ... * } * </pre> * @param region The entity of delete. (NotNull, PrimaryKeyNotNull) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. */ public void delete(Region region) { doDelete(region, null); } // =================================================================================== // Batch Update // ============ /** * Batch-insert the entity list modified-only of same-set columns. (DefaultConstraintsEnabled) <br> * This method uses executeBatch() of java.sql.PreparedStatement. <br> * <p><span style="color: #CC4747; font-size: 120%">The columns of least common multiple are registered like this:</span></p> * <pre> * <span style="color: #70226C">for</span> (... : ...) { * Region region = <span style="color: #70226C">new</span> Region(); * region.setFooName("foo"); * <span style="color: #70226C">if</span> (...) { * region.setFooPrice(123); * } * <span style="color: #3F7E5E">// FOO_NAME and FOO_PRICE (and record meta columns) are registered</span> * <span style="color: #3F7E5E">// FOO_PRICE not-called in any entities are registered as null without default value</span> * <span style="color: #3F7E5E">// columns not-called in all entities are registered as null or default value</span> * regionList.add(region); * } * <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">batchInsert</span>(regionList); * </pre> * <p>While, when the entities are created by select, all columns are registered.</p> * <p>And if the table has an identity, entities after the process don't have incremented values. * (When you use the (normal) insert(), you can get the incremented value from your entity)</p> * @param regionList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNullAllowed: when auto-increment) * @return The array of inserted count. (NotNull, EmptyAllowed) */ public int[] batchInsert(List<Region> regionList) { return doBatchInsert(regionList, null); } /** * Batch-update the entity list modified-only of same-set columns. (NonExclusiveControl) <br> * This method uses executeBatch() of java.sql.PreparedStatement. <br> * <span style="color: #CC4747; font-size: 120%">You should specify same-set columns to all entities like this:</span> * <pre> * for (... : ...) { * Region region = <span style="color: #70226C">new</span> Region(); * region.setFooName("foo"); * <span style="color: #70226C">if</span> (...) { * region.setFooPrice(123); * } <span style="color: #70226C">else</span> { * region.setFooPrice(null); <span style="color: #3F7E5E">// updated as null</span> * <span style="color: #3F7E5E">//region.setFooDate(...); // *not allowed, fragmented</span> * } * <span style="color: #3F7E5E">// FOO_NAME and FOO_PRICE (and record meta columns) are updated</span> * <span style="color: #3F7E5E">// (others are not updated: their values are kept)</span> * regionList.add(region); * } * <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">batchUpdate</span>(regionList); * </pre> * @param regionList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNotNull) * @return The array of updated count. (NotNull, EmptyAllowed) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) */ public int[] batchUpdate(List<Region> regionList) { return doBatchUpdate(regionList, null); } /** * Batch-delete the entity list. (NonExclusiveControl) <br> * This method uses executeBatch() of java.sql.PreparedStatement. * @param regionList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNotNull) * @return The array of deleted count. (NotNull, EmptyAllowed) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) */ public int[] batchDelete(List<Region> regionList) { return doBatchDelete(regionList, null); } // =================================================================================== // Query Update // ============ /** * Insert the several entities by query (modified-only for fixed value). * <pre> * <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">queryInsert</span>(new QueryInsertSetupper&lt;Region, RegionCB&gt;() { * public ConditionBean setup(Region entity, RegionCB intoCB) { * FooCB cb = FooCB(); * cb.setupSelect_Bar(); * * <span style="color: #3F7E5E">// mapping</span> * intoCB.specify().columnMyName().mappedFrom(cb.specify().columnFooName()); * intoCB.specify().columnMyCount().mappedFrom(cb.specify().columnFooCount()); * intoCB.specify().columnMyDate().mappedFrom(cb.specify().specifyBar().columnBarDate()); * entity.setMyFixedValue("foo"); <span style="color: #3F7E5E">// fixed value</span> * <span style="color: #3F7E5E">// you don't need to set values of common columns</span> * <span style="color: #3F7E5E">//entity.setRegisterUser(value);</span> * <span style="color: #3F7E5E">//entity.set...;</span> * <span style="color: #3F7E5E">// you don't need to set a value of concurrency column</span> * <span style="color: #3F7E5E">//entity.setVersionNo(value);</span> * * return cb; * } * }); * </pre> * @param manyArgLambda The callback to set up query-insert. (NotNull) * @return The inserted count. */ public int queryInsert(QueryInsertSetupper<Region, RegionCB> manyArgLambda) { return doQueryInsert(manyArgLambda, null); } /** * Update the several entities by query non-strictly modified-only. (NonExclusiveControl) * <pre> * Region region = <span style="color: #70226C">new</span> Region(); * <span style="color: #3F7E5E">// you don't need to set PK value</span> * <span style="color: #3F7E5E">//region.setPK...(value);</span> * region.setFoo...(value); <span style="color: #3F7E5E">// you should set only modified columns</span> * <span style="color: #3F7E5E">// you don't need to set values of common columns</span> * <span style="color: #3F7E5E">//region.setRegisterUser(value);</span> * <span style="color: #3F7E5E">//region.set...;</span> * <span style="color: #3F7E5E">// you don't need to set a value of concurrency column</span> * <span style="color: #3F7E5E">// (auto-increment for version number is valid though non-exclusive control)</span> * <span style="color: #3F7E5E">//region.setVersionNo(value);</span> * <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">queryUpdate</span>(region, <span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().setFoo... * }); * </pre> * @param region The entity that contains update values. (NotNull, PrimaryKeyNullAllowed) * @param cbLambda The callback for condition-bean of Region. (NotNull) * @return The updated count. * @throws NonQueryUpdateNotAllowedException When the query has no condition. */ public int queryUpdate(Region region, CBCall<RegionCB> cbLambda) { return doQueryUpdate(region, createCB(cbLambda), null); } /** * Delete the several entities by query. (NonExclusiveControl) * <pre> * <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">queryDelete</span>(region, <span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().setFoo... * }); * </pre> * @param cbLambda The callback for condition-bean of Region. (NotNull) * @return The deleted count. * @throws NonQueryDeleteNotAllowedException When the query has no condition. */ public int queryDelete(CBCall<RegionCB> cbLambda) { return doQueryDelete(createCB(cbLambda), null); } // =================================================================================== // Varying Update // ============== // ----------------------------------------------------- // Entity Update // ------------- /** * Insert the entity with varying requests. <br> * For example, disableCommonColumnAutoSetup(), disablePrimaryKeyIdentity(). <br> * Other specifications are same as insert(entity). * <pre> * Region region = <span style="color: #70226C">new</span> Region(); * <span style="color: #3F7E5E">// if auto-increment, you don't need to set the PK value</span> * region.setFoo...(value); * region.setBar...(value); * <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">varyingInsert</span>(region, <span style="color: #553000">op</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #3F7E5E">// you can insert by your values for common columns</span> * <span style="color: #553000">op</span>.disableCommonColumnAutoSetup(); * }); * ... = region.getPK...(); <span style="color: #3F7E5E">// if auto-increment, you can get the value after</span> * </pre> * @param region The entity of insert. (NotNull, PrimaryKeyNullAllowed: when auto-increment) * @param opLambda The callback for option of insert for varying requests. (NotNull) * @throws EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void varyingInsert(Region region, WritableOptionCall<RegionCB, InsertOption<RegionCB>> opLambda) { doInsert(region, createInsertOption(opLambda)); } /** * Update the entity with varying requests modified-only. (ZeroUpdateException, NonExclusiveControl) <br> * For example, self(selfCalculationSpecification), specify(updateColumnSpecification), disableCommonColumnAutoSetup(). <br> * Other specifications are same as update(entity). * <pre> * Region region = <span style="color: #70226C">new</span> Region(); * region.setPK...(value); <span style="color: #3F7E5E">// required</span> * region.setOther...(value); <span style="color: #3F7E5E">// you should set only modified columns</span> * <span style="color: #3F7E5E">// if exclusive control, the value of concurrency column is required</span> * region.<span style="color: #CC4747">setVersionNo</span>(value); * <span style="color: #3F7E5E">// you can update by self calculation values</span> * <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">varyingUpdate</span>(region, <span style="color: #553000">op</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">op</span>.self(<span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.specify().<span style="color: #CC4747">columnXxxCount()</span>; * }).plus(1); <span style="color: #3F7E5E">// XXX_COUNT = XXX_COUNT + 1</span> * }); * </pre> * @param region The entity of update. (NotNull, PrimaryKeyNotNull) * @param opLambda The callback for option of update for varying requests. (NotNull) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. * @throws EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void varyingUpdate(Region region, WritableOptionCall<RegionCB, UpdateOption<RegionCB>> opLambda) { doUpdate(region, createUpdateOption(opLambda)); } /** * Insert or update the entity with varying requests. (ExclusiveControl: when update) <br> * Other specifications are same as insertOrUpdate(entity). * @param region The entity of insert or update. (NotNull) * @param insertOpLambda The callback for option of insert for varying requests. (NotNull) * @param updateOpLambda The callback for option of update for varying requests. (NotNull) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. * @throws EntityAlreadyExistsException When the entity already exists. (unique constraint violation) */ public void varyingInsertOrUpdate(Region region, WritableOptionCall<RegionCB, InsertOption<RegionCB>> insertOpLambda, WritableOptionCall<RegionCB, UpdateOption<RegionCB>> updateOpLambda) { doInsertOrUpdate(region, createInsertOption(insertOpLambda), createUpdateOption(updateOpLambda)); } /** * Delete the entity with varying requests. (ZeroUpdateException, NonExclusiveControl) <br> * Now a valid option does not exist. <br> * Other specifications are same as delete(entity). * @param region The entity of delete. (NotNull, PrimaryKeyNotNull, ConcurrencyColumnNotNull) * @param opLambda The callback for option of delete for varying requests. (NotNull) * @throws EntityAlreadyDeletedException When the entity has already been deleted. (not found) * @throws EntityDuplicatedException When the entity has been duplicated. */ public void varyingDelete(Region region, WritableOptionCall<RegionCB, DeleteOption<RegionCB>> opLambda) { doDelete(region, createDeleteOption(opLambda)); } // ----------------------------------------------------- // Batch Update // ------------ /** * Batch-insert the list with varying requests. <br> * For example, disableCommonColumnAutoSetup() * , disablePrimaryKeyIdentity(), limitBatchInsertLogging(). <br> * Other specifications are same as batchInsert(entityList). * @param regionList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNotNull) * @param opLambda The callback for option of insert for varying requests. (NotNull) * @return The array of updated count. (NotNull, EmptyAllowed) */ public int[] varyingBatchInsert(List<Region> regionList, WritableOptionCall<RegionCB, InsertOption<RegionCB>> opLambda) { return doBatchInsert(regionList, createInsertOption(opLambda)); } /** * Batch-update the list with varying requests. <br> * For example, self(selfCalculationSpecification), specify(updateColumnSpecification) * , disableCommonColumnAutoSetup(), limitBatchUpdateLogging(). <br> * Other specifications are same as batchUpdate(entityList). * @param regionList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNotNull) * @param opLambda The callback for option of update for varying requests. (NotNull) * @return The array of updated count. (NotNull, EmptyAllowed) */ public int[] varyingBatchUpdate(List<Region> regionList, WritableOptionCall<RegionCB, UpdateOption<RegionCB>> opLambda) { return doBatchUpdate(regionList, createUpdateOption(opLambda)); } /** * Batch-delete the list with varying requests. <br> * For example, limitBatchDeleteLogging(). <br> * Other specifications are same as batchDelete(entityList). * @param regionList The list of the entity. (NotNull, EmptyAllowed, PrimaryKeyNotNull) * @param opLambda The callback for option of delete for varying requests. (NotNull) * @return The array of deleted count. (NotNull, EmptyAllowed) */ public int[] varyingBatchDelete(List<Region> regionList, WritableOptionCall<RegionCB, DeleteOption<RegionCB>> opLambda) { return doBatchDelete(regionList, createDeleteOption(opLambda)); } // ----------------------------------------------------- // Query Update // ------------ /** * Insert the several entities by query with varying requests (modified-only for fixed value). <br> * For example, disableCommonColumnAutoSetup(), disablePrimaryKeyIdentity(). <br> * Other specifications are same as queryInsert(entity, setupper). * @param manyArgLambda The set-upper of query-insert. (NotNull) * @param opLambda The callback for option of insert for varying requests. (NotNull) * @return The inserted count. */ public int varyingQueryInsert(QueryInsertSetupper<Region, RegionCB> manyArgLambda, WritableOptionCall<RegionCB, InsertOption<RegionCB>> opLambda) { return doQueryInsert(manyArgLambda, createInsertOption(opLambda)); } /** * Update the several entities by query with varying requests non-strictly modified-only. {NonExclusiveControl} <br> * For example, self(selfCalculationSpecification), specify(updateColumnSpecification) * , disableCommonColumnAutoSetup(), allowNonQueryUpdate(). <br> * Other specifications are same as queryUpdate(entity, cb). * <pre> * <span style="color: #3F7E5E">// ex) you can update by self calculation values</span> * Region region = <span style="color: #70226C">new</span> Region(); * <span style="color: #3F7E5E">// you don't need to set PK value</span> * <span style="color: #3F7E5E">//region.setPK...(value);</span> * region.setOther...(value); <span style="color: #3F7E5E">// you should set only modified columns</span> * <span style="color: #3F7E5E">// you don't need to set a value of concurrency column</span> * <span style="color: #3F7E5E">// (auto-increment for version number is valid though non-exclusive control)</span> * <span style="color: #3F7E5E">//region.setVersionNo(value);</span> * <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">varyingQueryUpdate</span>(region, <span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().setFoo... * }, <span style="color: #553000">op</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">op</span>.self(<span style="color: #553000">colCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">colCB</span>.specify().<span style="color: #CC4747">columnFooCount()</span>; * }).plus(1); <span style="color: #3F7E5E">// FOO_COUNT = FOO_COUNT + 1</span> * }); * </pre> * @param region The entity that contains update values. (NotNull) {PrimaryKeyNotRequired} * @param cbLambda The callback for condition-bean of Region. (NotNull) * @param opLambda The callback for option of update for varying requests. (NotNull) * @return The updated count. * @throws NonQueryUpdateNotAllowedException When the query has no condition (if not allowed). */ public int varyingQueryUpdate(Region region, CBCall<RegionCB> cbLambda, WritableOptionCall<RegionCB, UpdateOption<RegionCB>> opLambda) { return doQueryUpdate(region, createCB(cbLambda), createUpdateOption(opLambda)); } /** * Delete the several entities by query with varying requests non-strictly. <br> * For example, allowNonQueryDelete(). <br> * Other specifications are same as queryDelete(cb). * <pre> * <span style="color: #0000C0">regionBhv</span>.<span style="color: #CC4747">queryDelete</span>(region, <span style="color: #553000">cb</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">cb</span>.query().setFoo... * }, <span style="color: #553000">op</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">op</span>... * }); * </pre> * @param cbLambda The callback for condition-bean of Region. (NotNull) * @param opLambda The callback for option of delete for varying requests. (NotNull) * @return The deleted count. * @throws NonQueryDeleteNotAllowedException When the query has no condition (if not allowed). */ public int varyingQueryDelete(CBCall<RegionCB> cbLambda, WritableOptionCall<RegionCB, DeleteOption<RegionCB>> opLambda) { return doQueryDelete(createCB(cbLambda), createDeleteOption(opLambda)); } // =================================================================================== // OutsideSql // ========== /** * Prepare the all facade executor of outside-SQL to execute it. * <pre> * <span style="color: #3F7E5E">// main style</span> * regionBhv.outideSql().selectEntity(pmb); <span style="color: #3F7E5E">// optional</span> * regionBhv.outideSql().selectList(pmb); <span style="color: #3F7E5E">// ListResultBean</span> * regionBhv.outideSql().selectPage(pmb); <span style="color: #3F7E5E">// PagingResultBean</span> * regionBhv.outideSql().selectPagedListOnly(pmb); <span style="color: #3F7E5E">// ListResultBean</span> * regionBhv.outideSql().selectCursor(pmb, handler); <span style="color: #3F7E5E">// (by handler)</span> * regionBhv.outideSql().execute(pmb); <span style="color: #3F7E5E">// int (updated count)</span> * regionBhv.outideSql().call(pmb); <span style="color: #3F7E5E">// void (pmb has OUT parameters)</span> * * <span style="color: #3F7E5E">// traditional style</span> * regionBhv.outideSql().traditionalStyle().selectEntity(path, pmb, entityType); * regionBhv.outideSql().traditionalStyle().selectList(path, pmb, entityType); * regionBhv.outideSql().traditionalStyle().selectPage(path, pmb, entityType); * regionBhv.outideSql().traditionalStyle().selectPagedListOnly(path, pmb, entityType); * regionBhv.outideSql().traditionalStyle().selectCursor(path, pmb, handler); * regionBhv.outideSql().traditionalStyle().execute(path, pmb); * * <span style="color: #3F7E5E">// options</span> * regionBhv.outideSql().removeBlockComment().selectList() * regionBhv.outideSql().removeLineComment().selectList() * regionBhv.outideSql().formatSql().selectList() * </pre> * <p>The invoker of behavior command should be not null when you call this method.</p> * @return The new-created all facade executor of outside-SQL. (NotNull) */ public OutsideSqlAllFacadeExecutor<RegionBhv> outsideSql() { return doOutsideSql(); } // =================================================================================== // Framework Filter Override // ========================= @Override protected void frameworkFilterEntityOfInsert(Entity entity, org.dbflute.optional.OptionalThing<InsertOption<? extends ConditionBean>> option) { super.frameworkFilterEntityOfInsert(entity, option); new DateUpdateAdjuster().truncatePrecisionOfEntityProperty(entity); } @Override protected void frameworkFilterEntityOfUpdate(Entity entity, org.dbflute.optional.OptionalThing<UpdateOption<? extends ConditionBean>> option) { super.frameworkFilterEntityOfUpdate(entity, option); new DateUpdateAdjuster().truncatePrecisionOfEntityProperty(entity); } // =================================================================================== // Type Helper // =========== protected Class<? extends Region> typeOfSelectedEntity() { return Region.class; } protected Class<Region> typeOfHandlingEntity() { return Region.class; } protected Class<RegionCB> typeOfHandlingConditionBean() { return RegionCB.class; } }
dbflute-test/dbflute-test-active-hangar
src/main/java/org/docksidestage/hangar/dbflute/bsbhv/BsRegionBhv.java
Java
apache-2.0
57,830
package com.palmelf.eoffice.dao.admin; import com.palmelf.core.dao.BaseDao; import com.palmelf.eoffice.model.admin.BookType; public abstract interface BookTypeDao extends BaseDao<BookType> { }
jacarrichan/eoffice
src/main/java/com/palmelf/eoffice/dao/admin/BookTypeDao.java
Java
apache-2.0
195
package io.github.metteo.ws; import javax.xml.bind.annotation.adapters.XmlAdapter; public class Element1To2Adapter extends XmlAdapter<Element_1_0, Element_2_0> { @Override public Element_2_0 unmarshal(Element_1_0 v) throws Exception { if (v == null) { return null; } Element_2_0 result = new Element_2_0(); result.value1 = v.value1; result.value2 = v.value2; return result; } @Override public Element_1_0 marshal(Element_2_0 v) throws Exception { if (v == null) { return null; } Element_1_0 result = new Element_1_0(); result.value1 = v.value1; result.value2 = v.value2; return result; } }
metteo/ws-template
client/src/main/java/io/github/metteo/ws/Element1To2Adapter.java
Java
apache-2.0
633
package ru.job4j.calculator; /** *Class Calculator *author kgnedash *@since 3.11.2017 *@version 1 */ public class Calculator { private double result; public void add(double first, double second) { this.result = first + second; } public void substract(double first, double second) { this.result = first - second; } public void div(double first, double second) { this.result = first / second; } public void multiple(double first, double second) { this.result = first * second; } public double getResult() { return this.result; } }
kgnedash/kgnedash
chapter_001/src/main/java/ru/job4j/calculator/Calculator.java
Java
apache-2.0
562
package ru.job4j.JMM; /** * Created by Andrey on 02.09.2017. */ public class MultithreadingProblem implements Runnable { private static Integer counter = 0; public static Integer getCounter() { return counter; } @Override public void run() { for (int i = 0; i < 100; i++) { counter++; } } }
AVBaranov/abaranov
chapter_007/src/main/java/ru/job4j/JMM/MultithreadingProblem.java
Java
apache-2.0
357
package framework.netty; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; public class HelloClientHandler extends SimpleChannelInboundHandler<String> { @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { System.out.println("接收到服务器的消息-->" + msg); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); System.out.println("链接到服务器"); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); System.out.println("断开链接"); } }
ssywbj/JavaBase
src/framework/netty/HelloClientHandler.java
Java
apache-2.0
719
/* * Copyright 2015-2020 OpenCB * * 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.opencb.opencga.catalog.managers; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.config.Configurator; import org.junit.rules.ExternalResource; import org.opencb.commons.datastore.core.DataStoreServerAddress; import org.opencb.commons.datastore.mongodb.MongoDataStore; import org.opencb.commons.datastore.mongodb.MongoDataStoreManager; import org.opencb.opencga.catalog.exceptions.CatalogException; import org.opencb.opencga.core.common.TimeUtils; import org.opencb.opencga.core.common.UriUtils; import org.opencb.opencga.core.config.Configuration; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.LinkedList; import java.util.List; import static org.opencb.opencga.core.common.JacksonUtils.getDefaultObjectMapper; /** * Created on 05/05/16 * * @author Jacobo Coll &lt;[email protected]&gt; */ public class CatalogManagerExternalResource extends ExternalResource { private static CatalogManager catalogManager; private Configuration configuration; private Path opencgaHome; public CatalogManagerExternalResource() { Configurator.setLevel("org.mongodb.driver.cluster", Level.WARN); Configurator.setLevel("org.mongodb.driver.connection", Level.WARN); } @Override public void before() throws Exception { int c = 0; do { opencgaHome = Paths.get("target/test-data").resolve("junit_opencga_home_" + TimeUtils.getTimeMillis() + (c > 0 ? "_" + c : "")); c++; } while (opencgaHome.toFile().exists()); Files.createDirectories(opencgaHome); configuration = Configuration.load(getClass().getResource("/configuration-test.yml").openStream()); configuration.setWorkspace(opencgaHome.resolve("sessions").toAbsolutePath().toString()); configuration.setJobDir(opencgaHome.resolve("jobs").toAbsolutePath().toString()); clearCatalog(configuration); if (!opencgaHome.toFile().exists()) { deleteFolderTree(opencgaHome.toFile()); Files.createDirectory(opencgaHome); } catalogManager = new CatalogManager(configuration); catalogManager.installCatalogDB("dummy", "admin", "[email protected]", "", true); catalogManager.close(); // FIXME!! Should not need to create again the catalogManager // Have to create again the CatalogManager, as it has a random "secretKey" inside catalogManager = new CatalogManager(configuration); } @Override public void after() { super.after(); try { if (catalogManager != null) { catalogManager.close(); } } catch (CatalogException e) { throw new RuntimeException(e); } } public Configuration getConfiguration() { return configuration; } public CatalogManager getCatalogManager() { return catalogManager; } public Path getOpencgaHome() { return opencgaHome; } public ObjectMapper generateNewObjectMapper() { ObjectMapper jsonObjectMapper = getDefaultObjectMapper(); // jsonObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // jsonObjectMapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true); return jsonObjectMapper; } public static void clearCatalog(Configuration configuration) throws IOException, CatalogException, URISyntaxException { List<DataStoreServerAddress> dataStoreServerAddresses = new LinkedList<>(); for (String hostPort : configuration.getCatalog().getDatabase().getHosts()) { if (hostPort.contains(":")) { String[] split = hostPort.split(":"); Integer port = Integer.valueOf(split[1]); dataStoreServerAddresses.add(new DataStoreServerAddress(split[0], port)); } else { dataStoreServerAddresses.add(new DataStoreServerAddress(hostPort, 27017)); } } MongoDataStoreManager mongoManager = new MongoDataStoreManager(dataStoreServerAddresses); // if (catalogManager == null) { // catalogManager = new CatalogManager(configuration); // } // MongoDataStore db = mongoManager.get(catalogConfiguration.getDatabase().getDatabase()); MongoDataStore db = mongoManager.get(configuration.getDatabasePrefix() + "_catalog"); db.getDb().drop(); // mongoManager.close(catalogConfiguration.getDatabase().getDatabase()); mongoManager.close(configuration.getDatabasePrefix() + "_catalog"); Path rootdir = Paths.get(UriUtils.createDirectoryUri(configuration.getWorkspace())); deleteFolderTree(rootdir.toFile()); Path jobdir = Paths.get(UriUtils.createDirectoryUri(configuration.getJobDir())); deleteFolderTree(jobdir.toFile()); } public static void deleteFolderTree(java.io.File folder) { java.io.File[] files = folder.listFiles(); if (files != null) { for (java.io.File f : files) { if (f.isDirectory()) { deleteFolderTree(f); } else { f.delete(); } } } folder.delete(); } }
opencb/opencga
opencga-catalog/src/test/java/org/opencb/opencga/catalog/managers/CatalogManagerExternalResource.java
Java
apache-2.0
6,028
/* * Copyright 2012-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sample.simple; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.context.ApplicationContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link SampleSimpleApplication}. * * @author Dave Syer */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(SampleSimpleApplication.class) public class SpringTestSampleSimpleApplicationTests { @Autowired ApplicationContext ctx; @Test public void testContextLoads() throws Exception { assertThat(this.ctx).isNotNull(); assertThat(this.ctx.containsBean("helloWorldService")).isTrue(); assertThat(this.ctx.containsBean("sampleSimpleApplication")).isTrue(); } }
joansmith/spring-boot
spring-boot-samples/spring-boot-sample-simple/src/test/java/sample/simple/SpringTestSampleSimpleApplicationTests.java
Java
apache-2.0
1,536
/* Copyright 2009 Semantic Discovery, Inc. (www.semanticdiscovery.com) This file is part of the Semantic Discovery Toolkit. The Semantic Discovery Toolkit is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The Semantic Discovery Toolkit 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with The Semantic Discovery Toolkit. If not, see <http://www.gnu.org/licenses/>. */ package org.sd.atn.extract; import org.sd.xml.DomContext; import org.sd.xml.DomNode; import org.sd.xml.DomUtil; /** * Container class for xml-based extracted node text. * <p> * @author Spence Koehler */ public class XmlTextExtraction extends XmlExtraction { private int startIndex; /** * Starting index of extraction text within domContext's text (inclusive). */ public int getStartIndex() { return startIndex; } protected void setStartIndex(int startIndex) { this.startIndex = startIndex; } private int endIndex; /** * Ending index of extraction text within domContext's text (exclusive). */ public int getEndIndex() { return endIndex; } protected void setEndIndex(int endIndex) { this.endIndex = endIndex; } /** * Construct with an domContext and the extraction's start index (inclusive) * and end index (exclusive) within the domContext's text. * * Note that the domContext used for an extraction will be that which is * closest to the indicated text (deepest in its DOM tree) while still * encompassing the extraction text. */ public XmlTextExtraction(String type, DomContext domContext, int startIndex, int endIndex) { super(type); // adjust domContext as tightly as possible around the extracted text. final int[] adjustedStartIndex = new int[] {startIndex}; final int[] adjustedEndIndex = new int[] {endIndex}; final DomNode adjustedXmlNode = DomUtil.getDeepestNode(domContext.getDomNode(), startIndex, endIndex, adjustedStartIndex, adjustedEndIndex); // set instance data final String fullNodeText = DomUtil.getTrimmedNodeText(adjustedXmlNode); setText(fullNodeText.substring(adjustedStartIndex[0], adjustedEndIndex[0])); setNode(adjustedXmlNode); this.startIndex = adjustedStartIndex[0]; this.endIndex = adjustedEndIndex[0]; } protected String asString() { StringBuilder result = new StringBuilder(); result. append(super.asString()). append(" (["). append(startIndex). append(","). append(endIndex). append("] "). append(")"); return result.toString(); } }
KoehlerSB747/sd-tools
src/main/java/org/sd/atn/extract/XmlTextExtraction.java
Java
apache-2.0
3,035
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ambari.server.checks; import java.util.HashMap; import java.util.Map; import org.apache.ambari.server.configuration.Configuration; import org.apache.ambari.server.controller.PrereqCheckRequest; import org.apache.ambari.server.orm.entities.RepositoryVersionEntity; import org.apache.ambari.server.state.Cluster; import org.apache.ambari.server.state.Clusters; import org.apache.ambari.server.state.Config; import org.apache.ambari.server.state.DesiredConfig; import org.apache.ambari.server.state.Service; import org.apache.ambari.server.state.repository.ClusterVersionSummary; import org.apache.ambari.server.state.repository.VersionDefinitionXml; import org.apache.ambari.server.state.stack.PrereqCheckStatus; import org.apache.ambari.server.state.stack.PrerequisiteCheck; import org.apache.ambari.server.state.stack.UpgradePack.PrerequisiteCheckConfig; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import com.google.inject.Provider; /** * Unit tests for ServicesMapReduceDistributedCacheCheck * */ @RunWith(MockitoJUnitRunner.class) public class ServicesMapReduceDistributedCacheCheckTest { private final Clusters clusters = Mockito.mock(Clusters.class); private final ServicesMapReduceDistributedCacheCheck servicesMapReduceDistributedCacheCheck = new ServicesMapReduceDistributedCacheCheck(); @Mock private ClusterVersionSummary m_clusterVersionSummary; @Mock private VersionDefinitionXml m_vdfXml; @Mock private RepositoryVersionEntity m_repositoryVersion; final Map<String, Service> m_services = new HashMap<>(); @Before public void setup() throws Exception { servicesMapReduceDistributedCacheCheck.clustersProvider = new Provider<Clusters>() { @Override public Clusters get() { return clusters; } }; Configuration config = Mockito.mock(Configuration.class); servicesMapReduceDistributedCacheCheck.config = config; m_services.clear(); Mockito.when(m_repositoryVersion.getRepositoryXml()).thenReturn(m_vdfXml); Mockito.when(m_vdfXml.getClusterSummary(Mockito.any(Cluster.class))).thenReturn(m_clusterVersionSummary); Mockito.when(m_clusterVersionSummary.getAvailableServiceNames()).thenReturn(m_services.keySet()); } @Test public void testIsApplicable() throws Exception { final Cluster cluster = Mockito.mock(Cluster.class); final Service service = Mockito.mock(Service.class); m_services.put("YARN", service); Mockito.when(cluster.getServices()).thenReturn(m_services); Mockito.when(clusters.getCluster("cluster")).thenReturn(cluster); Mockito.when(cluster.getClusterId()).thenReturn(1L); PrereqCheckRequest request = new PrereqCheckRequest("cluster"); request.setTargetRepositoryVersion(m_repositoryVersion); Assert.assertTrue(servicesMapReduceDistributedCacheCheck.isApplicable(request)); request = new PrereqCheckRequest("cluster"); request.setTargetRepositoryVersion(m_repositoryVersion); request.addResult(CheckDescription.SERVICES_NAMENODE_HA, PrereqCheckStatus.FAIL); Assert.assertFalse(servicesMapReduceDistributedCacheCheck.isApplicable(request)); request.addResult(CheckDescription.SERVICES_NAMENODE_HA, PrereqCheckStatus.PASS); Assert.assertTrue(servicesMapReduceDistributedCacheCheck.isApplicable(request)); m_services.remove("YARN"); Assert.assertFalse(servicesMapReduceDistributedCacheCheck.isApplicable(request)); } @Test public void testPerform() throws Exception { final Cluster cluster = Mockito.mock(Cluster.class); Mockito.when(cluster.getClusterId()).thenReturn(1L); Mockito.when(clusters.getCluster("cluster")).thenReturn(cluster); final DesiredConfig desiredConfig = Mockito.mock(DesiredConfig.class); Mockito.when(desiredConfig.getTag()).thenReturn("tag"); Map<String, DesiredConfig> configMap = new HashMap<>(); configMap.put("mapred-site", desiredConfig); configMap.put("core-site", desiredConfig); Mockito.when(cluster.getDesiredConfigs()).thenReturn(configMap); final Config config = Mockito.mock(Config.class); Mockito.when(cluster.getConfig(Mockito.anyString(), Mockito.anyString())).thenReturn(config); final Map<String, String> properties = new HashMap<>(); Mockito.when(config.getProperties()).thenReturn(properties); PrerequisiteCheck check = new PrerequisiteCheck(null, null); servicesMapReduceDistributedCacheCheck.perform(check, new PrereqCheckRequest("cluster")); Assert.assertEquals(PrereqCheckStatus.FAIL, check.getStatus()); properties.put("fs.defaultFS", "anything"); properties.put("mapreduce.application.framework.path", "hdfs://some/path"); properties.put("mapreduce.application.classpath", "anything"); check = new PrerequisiteCheck(null, null); servicesMapReduceDistributedCacheCheck.perform(check, new PrereqCheckRequest("cluster")); Assert.assertEquals(PrereqCheckStatus.PASS, check.getStatus()); properties.put("fs.defaultFS", "anything"); properties.put("mapreduce.application.framework.path", "dfs://some/path"); properties.put("mapreduce.application.classpath", "anything"); check = new PrerequisiteCheck(null, null); servicesMapReduceDistributedCacheCheck.perform(check, new PrereqCheckRequest("cluster")); Assert.assertEquals(PrereqCheckStatus.PASS, check.getStatus()); properties.put("fs.defaultFS", "hdfs://ha"); properties.put("mapreduce.application.framework.path", "/some/path"); properties.put("mapreduce.application.classpath", "anything"); check = new PrerequisiteCheck(null, null); servicesMapReduceDistributedCacheCheck.perform(check, new PrereqCheckRequest("cluster")); Assert.assertEquals(PrereqCheckStatus.PASS, check.getStatus()); properties.put("fs.defaultFS", "dfs://ha"); properties.put("mapreduce.application.framework.path", "/some/path"); properties.put("mapreduce.application.classpath", "anything"); check = new PrerequisiteCheck(null, null); servicesMapReduceDistributedCacheCheck.perform(check, new PrereqCheckRequest("cluster")); Assert.assertEquals(PrereqCheckStatus.PASS, check.getStatus()); // Fail due to no dfs properties.put("fs.defaultFS", "anything"); properties.put("mapreduce.application.framework.path", "/some/path"); properties.put("mapreduce.application.classpath", "anything"); check = new PrerequisiteCheck(null, null); servicesMapReduceDistributedCacheCheck.perform(check, new PrereqCheckRequest("cluster")); Assert.assertEquals(PrereqCheckStatus.FAIL, check.getStatus()); } @Test public void testPerformWithCheckConfig() throws Exception { final Cluster cluster = Mockito.mock(Cluster.class); Mockito.when(cluster.getClusterId()).thenReturn(1L); Mockito.when(clusters.getCluster("cluster")).thenReturn(cluster); final DesiredConfig desiredConfig = Mockito.mock(DesiredConfig.class); Mockito.when(desiredConfig.getTag()).thenReturn("tag"); Map<String, DesiredConfig> configMap = new HashMap<>(); configMap.put("mapred-site", desiredConfig); configMap.put("core-site", desiredConfig); Mockito.when(cluster.getDesiredConfigs()).thenReturn(configMap); final Config config = Mockito.mock(Config.class); Mockito.when(cluster.getConfig(Mockito.anyString(), Mockito.anyString())).thenReturn(config); final Map<String, String> properties = new HashMap<>(); Mockito.when(config.getProperties()).thenReturn(properties); Map<String, String> checkProperties = new HashMap<>(); checkProperties.put("dfs-protocols-regex","^([^:]*dfs|wasb|ecs):.*"); PrerequisiteCheckConfig prerequisiteCheckConfig = Mockito.mock(PrerequisiteCheckConfig.class); Mockito.when(prerequisiteCheckConfig.getCheckProperties( servicesMapReduceDistributedCacheCheck.getClass().getName())).thenReturn(checkProperties); PrereqCheckRequest request = new PrereqCheckRequest("cluster"); request.setPrerequisiteCheckConfig(prerequisiteCheckConfig); PrerequisiteCheck check = new PrerequisiteCheck(null, null); servicesMapReduceDistributedCacheCheck.perform(check, request); Assert.assertEquals(PrereqCheckStatus.FAIL, check.getStatus()); properties.put("fs.defaultFS", "anything"); properties.put("mapreduce.application.framework.path", "hdfs://some/path"); properties.put("mapreduce.application.classpath", "anything"); request = new PrereqCheckRequest("cluster"); request.setPrerequisiteCheckConfig(prerequisiteCheckConfig); check = new PrerequisiteCheck(null, null); servicesMapReduceDistributedCacheCheck.perform(check, request); Assert.assertEquals(PrereqCheckStatus.PASS, check.getStatus()); properties.put("fs.defaultFS", "anything"); properties.put("mapreduce.application.framework.path", "dfs://some/path"); properties.put("mapreduce.application.classpath", "anything"); request = new PrereqCheckRequest("cluster"); request.setPrerequisiteCheckConfig(prerequisiteCheckConfig); check = new PrerequisiteCheck(null, null); servicesMapReduceDistributedCacheCheck.perform(check, request); Assert.assertEquals(PrereqCheckStatus.PASS, check.getStatus()); properties.put("fs.defaultFS", "anything"); properties.put("mapreduce.application.framework.path", "wasb://some/path"); properties.put("mapreduce.application.classpath", "anything"); request = new PrereqCheckRequest("cluster"); request.setPrerequisiteCheckConfig(prerequisiteCheckConfig); check = new PrerequisiteCheck(null, null); servicesMapReduceDistributedCacheCheck.perform(check, request); Assert.assertEquals(PrereqCheckStatus.PASS, check.getStatus()); properties.put("fs.defaultFS", "anything"); properties.put("mapreduce.application.framework.path", "ecs://some/path"); properties.put("mapreduce.application.classpath", "anything"); request = new PrereqCheckRequest("cluster"); request.setPrerequisiteCheckConfig(prerequisiteCheckConfig); check = new PrerequisiteCheck(null, null); servicesMapReduceDistributedCacheCheck.perform(check, request); Assert.assertEquals(PrereqCheckStatus.PASS, check.getStatus()); properties.put("fs.defaultFS", "hdfs://ha"); properties.put("mapreduce.application.framework.path", "/some/path"); properties.put("mapreduce.application.classpath", "anything"); request = new PrereqCheckRequest("cluster"); request.setPrerequisiteCheckConfig(prerequisiteCheckConfig); check = new PrerequisiteCheck(null, null); servicesMapReduceDistributedCacheCheck.perform(check, request); Assert.assertEquals(PrereqCheckStatus.PASS, check.getStatus()); properties.put("fs.defaultFS", "dfs://ha"); properties.put("mapreduce.application.framework.path", "/some/path"); properties.put("mapreduce.application.classpath", "anything"); request = new PrereqCheckRequest("cluster"); request.setPrerequisiteCheckConfig(prerequisiteCheckConfig); check = new PrerequisiteCheck(null, null); servicesMapReduceDistributedCacheCheck.perform(check, request); Assert.assertEquals(PrereqCheckStatus.PASS, check.getStatus()); properties.put("fs.defaultFS", "wasb://ha"); properties.put("mapreduce.application.framework.path", "/some/path"); properties.put("mapreduce.application.classpath", "anything"); request = new PrereqCheckRequest("cluster"); request.setPrerequisiteCheckConfig(prerequisiteCheckConfig); check = new PrerequisiteCheck(null, null); servicesMapReduceDistributedCacheCheck.perform(check, request); Assert.assertEquals(PrereqCheckStatus.PASS, check.getStatus()); properties.put("fs.defaultFS", "ecs://ha"); properties.put("mapreduce.application.framework.path", "/some/path"); properties.put("mapreduce.application.classpath", "anything"); request = new PrereqCheckRequest("cluster"); request.setPrerequisiteCheckConfig(prerequisiteCheckConfig); check = new PrerequisiteCheck(null, null); servicesMapReduceDistributedCacheCheck.perform(check, request); Assert.assertEquals(PrereqCheckStatus.PASS, check.getStatus()); // Fail due to no dfs properties.put("fs.defaultFS", "anything"); properties.put("mapreduce.application.framework.path", "/some/path"); properties.put("mapreduce.application.classpath", "anything"); request = new PrereqCheckRequest("cluster"); request.setPrerequisiteCheckConfig(prerequisiteCheckConfig); check = new PrerequisiteCheck(null, null); servicesMapReduceDistributedCacheCheck.perform(check, request); Assert.assertEquals(PrereqCheckStatus.FAIL, check.getStatus()); } }
radicalbit/ambari
ambari-server/src/test/java/org/apache/ambari/server/checks/ServicesMapReduceDistributedCacheCheckTest.java
Java
apache-2.0
13,607
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.codedeploy.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.codedeploy.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * ECSServiceMappingLimitExceededException JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ECSServiceMappingLimitExceededExceptionUnmarshaller extends EnhancedJsonErrorUnmarshaller { private ECSServiceMappingLimitExceededExceptionUnmarshaller() { super(com.amazonaws.services.codedeploy.model.ECSServiceMappingLimitExceededException.class, "ECSServiceMappingLimitExceededException"); } @Override public com.amazonaws.services.codedeploy.model.ECSServiceMappingLimitExceededException unmarshallFromContext(JsonUnmarshallerContext context) throws Exception { com.amazonaws.services.codedeploy.model.ECSServiceMappingLimitExceededException eCSServiceMappingLimitExceededException = new com.amazonaws.services.codedeploy.model.ECSServiceMappingLimitExceededException( null); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return eCSServiceMappingLimitExceededException; } private static ECSServiceMappingLimitExceededExceptionUnmarshaller instance; public static ECSServiceMappingLimitExceededExceptionUnmarshaller getInstance() { if (instance == null) instance = new ECSServiceMappingLimitExceededExceptionUnmarshaller(); return instance; } }
aws/aws-sdk-java
aws-java-sdk-codedeploy/src/main/java/com/amazonaws/services/codedeploy/model/transform/ECSServiceMappingLimitExceededExceptionUnmarshaller.java
Java
apache-2.0
3,096
package com.littlesparkle.growler.library.activity; import android.os.Bundle; public abstract class BaseSplashActivity extends HandlerActivity { public static final int ONE_SECOND = 1000; private static final int MAX_COUNTER = 2; private int mRemainingSeconds = 0; private Runnable mUpdateRunnable = new Runnable() { public void run() { if (mRemainingSeconds == 0) { onSplashEnd(); } else { mRemainingSeconds = mRemainingSeconds - 1; mHandler.postDelayed(this, ONE_SECOND); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initUI(); } protected abstract void onSplashEnd(); protected int getMaxCounter() { return MAX_COUNTER; } private void initUI() { mRemainingSeconds = getMaxCounter(); mHandler.postDelayed(mUpdateRunnable, ONE_SECOND); } }
little-sparkle/growler_engine_android
library/src/main/java/com/littlesparkle/growler/library/activity/BaseSplashActivity.java
Java
apache-2.0
1,002
package com.sequenceiq.freeipa.client; public class InvalidFreeIpaStateException extends RuntimeException { public InvalidFreeIpaStateException(String message, Throwable cause) { super(message, cause); } }
hortonworks/cloudbreak
freeipa-client/src/main/java/com/sequenceiq/freeipa/client/InvalidFreeIpaStateException.java
Java
apache-2.0
223
// Copyright (C) 2013 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.pgm.init; import static com.google.inject.Scopes.SINGLETON; import static com.google.inject.Stage.PRODUCTION; import com.google.common.base.MoreObjects; import com.google.common.base.Strings; import com.google.common.flogger.FluentLogger; import com.google.gerrit.common.Die; import com.google.gerrit.common.IoUtil; import com.google.gerrit.exceptions.StorageException; import com.google.gerrit.metrics.DisabledMetricMaker; import com.google.gerrit.metrics.MetricMaker; import com.google.gerrit.pgm.init.api.ConsoleUI; import com.google.gerrit.pgm.init.api.InitFlags; import com.google.gerrit.pgm.init.api.InstallAllPlugins; import com.google.gerrit.pgm.init.api.InstallPlugins; import com.google.gerrit.pgm.init.api.LibraryDownload; import com.google.gerrit.pgm.init.index.IndexManagerOnInit; import com.google.gerrit.pgm.init.index.elasticsearch.ElasticIndexModuleOnInit; import com.google.gerrit.pgm.init.index.lucene.LuceneIndexModuleOnInit; import com.google.gerrit.pgm.util.SiteProgram; import com.google.gerrit.server.config.GerritServerConfigModule; import com.google.gerrit.server.config.SitePath; import com.google.gerrit.server.config.SitePaths; import com.google.gerrit.server.git.GitRepositoryManager; import com.google.gerrit.server.index.IndexModule; import com.google.gerrit.server.plugins.JarScanner; import com.google.gerrit.server.schema.NoteDbSchemaUpdater; import com.google.gerrit.server.schema.UpdateUI; import com.google.gerrit.server.securestore.SecureStore; import com.google.gerrit.server.securestore.SecureStoreClassName; import com.google.gerrit.server.securestore.SecureStoreProvider; import com.google.inject.AbstractModule; import com.google.inject.CreationException; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.TypeLiteral; import com.google.inject.spi.Message; import com.google.inject.util.Providers; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; /** Initialize a new Gerrit installation. */ public class BaseInit extends SiteProgram { private static final FluentLogger logger = FluentLogger.forEnclosingClass(); private final boolean standalone; protected final PluginsDistribution pluginsDistribution; private final List<String> pluginsToInstall; private Injector sysInjector; protected BaseInit(PluginsDistribution pluginsDistribution, List<String> pluginsToInstall) { this.standalone = true; this.pluginsDistribution = pluginsDistribution; this.pluginsToInstall = pluginsToInstall; } public BaseInit( Path sitePath, boolean standalone, PluginsDistribution pluginsDistribution, List<String> pluginsToInstall) { super(sitePath); this.standalone = standalone; this.pluginsDistribution = pluginsDistribution; this.pluginsToInstall = pluginsToInstall; } @Override public int run() throws Exception { final SiteInit init = createSiteInit(); if (beforeInit(init)) { return 0; } init.flags.autoStart = getAutoStart() && init.site.isNew; init.flags.dev = isDev() && init.site.isNew; init.flags.skipPlugins = skipPlugins(); init.flags.deleteCaches = getDeleteCaches(); init.flags.isNew = init.site.isNew; final SiteRun run; try { init.initializer.run(); init.flags.deleteOnFailure = false; Injector sysInjector = createSysInjector(init); IndexManagerOnInit indexManager = sysInjector.getInstance(IndexManagerOnInit.class); try { indexManager.start(); run = createSiteRun(init); try { run.upgradeSchema(); } catch (StorageException e) { String msg = "Couldn't upgrade schema. Expected if slave and read-only database"; System.err.println(msg); logger.atSevere().withCause(e).log(msg); } init.initializer.postRun(sysInjector); } finally { indexManager.stop(); } } catch (Exception | Error failure) { if (init.flags.deleteOnFailure) { recursiveDelete(getSitePath()); } throw failure; } System.err.println("Initialized " + getSitePath().toRealPath().normalize()); afterInit(run); return 0; } protected boolean skipPlugins() { return false; } protected String getSecureStoreLib() { return null; } protected boolean skipAllDownloads() { return false; } protected List<String> getSkippedDownloads() { return Collections.emptyList(); } /** * Invoked before site init is called. * * @param init initializer instance. * @throws Exception */ protected boolean beforeInit(SiteInit init) throws Exception { return false; } /** * Invoked after site init is called. * * @param run completed run instance. * @throws Exception */ protected void afterInit(SiteRun run) throws Exception {} protected List<String> getInstallPlugins() { try { if (pluginsToInstall != null && pluginsToInstall.isEmpty()) { return Collections.emptyList(); } List<String> names = pluginsDistribution.listPluginNames(); if (pluginsToInstall != null) { names.removeIf(n -> !pluginsToInstall.contains(n)); } return names; } catch (FileNotFoundException e) { logger.atWarning().log( "Couldn't find distribution archive location. No plugin will be installed"); return null; } } protected boolean installAllPlugins() { return false; } protected boolean getAutoStart() { return false; } public static class SiteInit { public final SitePaths site; final InitFlags flags; final ConsoleUI ui; final SitePathInitializer initializer; @Inject SiteInit( final SitePaths site, final InitFlags flags, final ConsoleUI ui, final SitePathInitializer initializer) { this.site = site; this.flags = flags; this.ui = ui; this.initializer = initializer; } } private SiteInit createSiteInit() { final ConsoleUI ui = getConsoleUI(); final Path sitePath = getSitePath(); final List<Module> m = new ArrayList<>(); final SecureStoreInitData secureStoreInitData = discoverSecureStoreClass(); final String currentSecureStoreClassName = getConfiguredSecureStoreClass(); if (secureStoreInitData != null && currentSecureStoreClassName != null && !currentSecureStoreClassName.equals(secureStoreInitData.className)) { String err = String.format( "Different secure store was previously configured: %s. " + "Use SwitchSecureStore program to switch between implementations.", currentSecureStoreClassName); throw die(err); } m.add(new GerritServerConfigModule()); m.add(new InitModule(standalone)); m.add( new AbstractModule() { @Override protected void configure() { bind(ConsoleUI.class).toInstance(ui); bind(Path.class).annotatedWith(SitePath.class).toInstance(sitePath); List<String> plugins = MoreObjects.firstNonNull(getInstallPlugins(), new ArrayList<>()); bind(new TypeLiteral<List<String>>() {}) .annotatedWith(InstallPlugins.class) .toInstance(plugins); bind(new TypeLiteral<Boolean>() {}) .annotatedWith(InstallAllPlugins.class) .toInstance(installAllPlugins()); bind(PluginsDistribution.class).toInstance(pluginsDistribution); String secureStoreClassName; if (secureStoreInitData != null) { secureStoreClassName = secureStoreInitData.className; } else { secureStoreClassName = currentSecureStoreClassName; } if (secureStoreClassName != null) { ui.message("Using secure store: %s\n", secureStoreClassName); } bind(SecureStoreInitData.class).toProvider(Providers.of(secureStoreInitData)); bind(String.class) .annotatedWith(SecureStoreClassName.class) .toProvider(Providers.of(secureStoreClassName)); bind(SecureStore.class).toProvider(SecureStoreProvider.class).in(SINGLETON); bind(new TypeLiteral<List<String>>() {}) .annotatedWith(LibraryDownload.class) .toInstance(getSkippedDownloads()); bind(Boolean.class).annotatedWith(LibraryDownload.class).toInstance(skipAllDownloads()); bind(MetricMaker.class).to(DisabledMetricMaker.class); } }); try { return Guice.createInjector(PRODUCTION, m).getInstance(SiteInit.class); } catch (CreationException ce) { final Message first = ce.getErrorMessages().iterator().next(); Throwable why = first.getCause(); if (why instanceof Die) { throw (Die) why; } final StringBuilder buf = new StringBuilder(ce.getMessage()); while (why != null) { buf.append("\n"); buf.append(why.getMessage()); why = why.getCause(); if (why != null) { buf.append("\n caused by "); } } throw die(buf.toString(), new RuntimeException("InitInjector failed", ce)); } } protected ConsoleUI getConsoleUI() { return ConsoleUI.getInstance(false); } private SecureStoreInitData discoverSecureStoreClass() { String secureStore = getSecureStoreLib(); if (Strings.isNullOrEmpty(secureStore)) { return null; } Path secureStoreLib = Paths.get(secureStore); if (!Files.exists(secureStoreLib)) { throw new InvalidSecureStoreException(String.format("File %s doesn't exist", secureStore)); } try (JarScanner scanner = new JarScanner(secureStoreLib)) { List<String> secureStores = scanner.findSubClassesOf(SecureStore.class); if (secureStores.isEmpty()) { throw new InvalidSecureStoreException( String.format( "Cannot find class implementing %s interface in %s", SecureStore.class.getName(), secureStore)); } if (secureStores.size() > 1) { throw new InvalidSecureStoreException( String.format( "%s has more that one implementation of %s interface", secureStore, SecureStore.class.getName())); } IoUtil.loadJARs(secureStoreLib); return new SecureStoreInitData(secureStoreLib, secureStores.get(0)); } catch (IOException e) { throw new InvalidSecureStoreException(String.format("%s is not a valid jar", secureStore), e); } } public static class SiteRun { public final ConsoleUI ui; public final SitePaths site; public final InitFlags flags; final NoteDbSchemaUpdater noteDbSchemaUpdater; final GitRepositoryManager repositoryManager; @Inject SiteRun( ConsoleUI ui, SitePaths site, InitFlags flags, NoteDbSchemaUpdater noteDbSchemaUpdater, GitRepositoryManager repositoryManager) { this.ui = ui; this.site = site; this.flags = flags; this.noteDbSchemaUpdater = noteDbSchemaUpdater; this.repositoryManager = repositoryManager; } void upgradeSchema() { noteDbSchemaUpdater.update(new UpdateUIImpl(ui)); } private static class UpdateUIImpl implements UpdateUI { private final ConsoleUI consoleUi; UpdateUIImpl(ConsoleUI consoleUi) { this.consoleUi = consoleUi; } @Override public void message(String message) { System.err.println(message); System.err.flush(); } @Override public boolean yesno(boolean defaultValue, String message) { return consoleUi.yesno(defaultValue, message); } @Override public void waitForUser() { consoleUi.waitForUser(); } @Override public String readString(String defaultValue, Set<String> allowedValues, String message) { return consoleUi.readString(defaultValue, allowedValues, message); } @Override public boolean isBatch() { return consoleUi.isBatch(); } } } private SiteRun createSiteRun(SiteInit init) { return createSysInjector(init).getInstance(SiteRun.class); } private Injector createSysInjector(SiteInit init) { if (sysInjector == null) { final List<Module> modules = new ArrayList<>(); modules.add( new AbstractModule() { @Override protected void configure() { bind(ConsoleUI.class).toInstance(init.ui); bind(InitFlags.class).toInstance(init.flags); } }); Injector dbInjector = createDbInjector(); switch (IndexModule.getIndexType(dbInjector)) { case LUCENE: modules.add(new LuceneIndexModuleOnInit()); break; case ELASTICSEARCH: modules.add(new ElasticIndexModuleOnInit()); break; default: throw new IllegalStateException("unsupported index.type"); } sysInjector = dbInjector.createChildInjector(modules); } return sysInjector; } private static void recursiveDelete(Path path) { final String msg = "warn: Cannot remove "; try { Files.walkFileTree( path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path f, BasicFileAttributes attrs) throws IOException { try { Files.delete(f); } catch (IOException e) { System.err.println(msg + f); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException err) { try { // Previously warned if err was not null; if dir is not empty as a // result, will cause an error that will be logged below. Files.delete(dir); } catch (IOException e) { System.err.println(msg + dir); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path f, IOException e) { System.err.println(msg + f); return FileVisitResult.CONTINUE; } }); } catch (IOException e) { System.err.println(msg + path); } } protected boolean isDev() { return false; } protected boolean getDeleteCaches() { return false; } }
qtproject/qtqa-gerrit
java/com/google/gerrit/pgm/init/BaseInit.java
Java
apache-2.0
15,658
package cgeo.geocaching.filter; import cgeo.geocaching.CgeoApplication; import android.os.Parcel; import android.support.annotation.StringRes; abstract class AbstractRangeFilter extends AbstractFilter { protected final float rangeMin; protected final float rangeMax; protected AbstractRangeFilter(@StringRes final int resourceId, final int range) { super(CgeoApplication.getInstance().getResources().getString(resourceId) + ' ' + (range == 5 ? '5' : range + " + " + String.format("%.1f", range + 0.5))); rangeMin = range; rangeMax = rangeMin + 1f; } protected AbstractRangeFilter(final Parcel in) { super(in); rangeMin = in.readFloat(); rangeMax = in.readFloat(); } @Override public void writeToParcel(final Parcel dest, final int flags) { super.writeToParcel(dest, flags); dest.writeFloat(rangeMin); dest.writeFloat(rangeMax); } }
SammysHP/cgeo
main/src/cgeo/geocaching/filter/AbstractRangeFilter.java
Java
apache-2.0
946
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.giraph.worker; import org.apache.giraph.conf.ImmutableClassesGiraphConfiguration; import org.apache.giraph.graph.GraphState; import org.apache.giraph.graph.VertexEdgeCount; import org.apache.giraph.utils.CallableFactory; import org.apache.giraph.zk.ZooKeeperExt; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.mapreduce.Mapper; /** * Factory for {@link VertexInputSplitsCallable}s. * * @param <I> Vertex id * @param <V> Vertex value * @param <E> Edge value * @param <M> Message data */ public class VertexInputSplitsCallableFactory<I extends WritableComparable, V extends Writable, E extends Writable, M extends Writable> implements CallableFactory<VertexEdgeCount> { /** Mapper context. */ private final Mapper<?, ?, ?, ?>.Context context; /** Graph state. */ private final GraphState<I, V, E, M> graphState; /** Configuration. */ private final ImmutableClassesGiraphConfiguration<I, V, E, M> configuration; /** {@link BspServiceWorker} we're running on. */ private final IBspServiceWorker<I, V, E, M> bspServiceWorker; /** Handler for input splits */ private final InputSplitsHandler splitsHandler; /** {@link ZooKeeperExt} for this worker. */ private final ZooKeeperExt zooKeeperExt; /** * Constructor. * * @param context Mapper context * @param graphState Graph state * @param configuration Configuration * @param bspServiceWorker Calling {@link BspServiceWorker} * @param splitsHandler Handler for input splits * @param zooKeeperExt {@link ZooKeeperExt} for this worker */ public VertexInputSplitsCallableFactory( Mapper<?, ?, ?, ?>.Context context, GraphState<I, V, E, M> graphState, ImmutableClassesGiraphConfiguration<I, V, E, M> configuration, IBspServiceWorker<I, V, E, M> bspServiceWorker, InputSplitsHandler splitsHandler, ZooKeeperExt zooKeeperExt) { this.context = context; this.graphState = graphState; this.configuration = configuration; this.bspServiceWorker = bspServiceWorker; this.zooKeeperExt = zooKeeperExt; this.splitsHandler = splitsHandler; } @Override public InputSplitsCallable<I, V, E, M> newCallable(int threadId) { return new VertexInputSplitsCallable<I, V, E, M>( context, graphState, configuration, bspServiceWorker, splitsHandler, zooKeeperExt); } }
simon0227/dgraph
giraph-core/src/main/java/org/apache/giraph/worker/VertexInputSplitsCallableFactory.java
Java
apache-2.0
3,267
package org.xbib.catalog.entities.pica.natliz.bib; import org.xbib.catalog.entities.CatalogEntity; import java.util.Map; /** * */ public class RecordFormat extends CatalogEntity { public RecordFormat(Map<String, Object> params) { super(params); } }
xbib/catalog-entities
src/main/java/org/xbib/catalog/entities/pica/natliz/bib/RecordFormat.java
Java
apache-2.0
271
package com.vmware.vim25; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for RegisterVMRequestType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="RegisterVMRequestType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="_this" type="{urn:vim25}ManagedObjectReference"/> * &lt;element name="path" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="asTemplate" type="{http://www.w3.org/2001/XMLSchema}boolean"/> * &lt;element name="pool" type="{urn:vim25}ManagedObjectReference" minOccurs="0"/> * &lt;element name="host" type="{urn:vim25}ManagedObjectReference" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "RegisterVMRequestType", propOrder = { "_this", "path", "name", "asTemplate", "pool", "host" }) public class RegisterVMRequestType { @XmlElement(required = true) protected ManagedObjectReference _this; @XmlElement(required = true) protected String path; protected String name; protected boolean asTemplate; protected ManagedObjectReference pool; protected ManagedObjectReference host; /** * Gets the value of the this property. * * @return * possible object is * {@link ManagedObjectReference } * */ public ManagedObjectReference getThis() { return _this; } /** * Sets the value of the this property. * * @param value * allowed object is * {@link ManagedObjectReference } * */ public void setThis(ManagedObjectReference value) { this._this = value; } /** * Gets the value of the path property. * * @return * possible object is * {@link String } * */ public String getPath() { return path; } /** * Sets the value of the path property. * * @param value * allowed object is * {@link String } * */ public void setPath(String value) { this.path = value; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the asTemplate property. * */ public boolean isAsTemplate() { return asTemplate; } /** * Sets the value of the asTemplate property. * */ public void setAsTemplate(boolean value) { this.asTemplate = value; } /** * Gets the value of the pool property. * * @return * possible object is * {@link ManagedObjectReference } * */ public ManagedObjectReference getPool() { return pool; } /** * Sets the value of the pool property. * * @param value * allowed object is * {@link ManagedObjectReference } * */ public void setPool(ManagedObjectReference value) { this.pool = value; } /** * Gets the value of the host property. * * @return * possible object is * {@link ManagedObjectReference } * */ public ManagedObjectReference getHost() { return host; } /** * Sets the value of the host property. * * @param value * allowed object is * {@link ManagedObjectReference } * */ public void setHost(ManagedObjectReference value) { this.host = value; } }
jdgwartney/vsphere-ws
java/JAXWS/samples/com/vmware/vim25/RegisterVMRequestType.java
Java
apache-2.0
4,604
/* * Copyright 2013 David Curtis * * 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.logicmill.util.concurrent; import org.logicmill.util.concurrent.ConcurrentLargeHashMapProbe.SegmentProbe; /** Thrown by {@link ConcurrentLargeHashMapAuditor#verifyMapIntegrity(boolean, int)} * to indicate the detection of an entry whose hash code does not match the * bucket in which it was found. * @author David Curtis * */ public class WrongBucketException extends SegmentIntegrityException { private static final long serialVersionUID = 2425500101047242622L; final int bucketIndex; final int offset; final int bucketIndexFromEntry; /** Creates a new WrongBucketException with the specified details. * @param segmentProbe proxy for segment in which exception occurred; uses * reflection to access private segment internals * @param bucketIndex index of the bucket in which the offending entry * was detected * @param offset offset (from the bucket index) of the offending entry * @param bucketIndexFromEntry the bucket index derived from the * entry's hash code */ public WrongBucketException(SegmentProbe segmentProbe, int bucketIndex, int offset, int bucketIndexFromEntry) { super(String.format("entry at buckets[%d + %d]: index from entry hash code (%d) doesn't match bucket", bucketIndex, offset, bucketIndexFromEntry), segmentProbe); this.bucketIndex = bucketIndex; this.offset = offset; this.bucketIndexFromEntry = bucketIndexFromEntry; } /** * @return index of the bucket in which the offending entry was detected */ public int getBucketIndex() { return bucketIndex; } /** * @return offset (from bucket index) of the offending entry */ public int getOffset() { return offset; } /** * @return the bucket index derived from the entry's hash code */ public int getBucketIndexFromEntry() { return bucketIndexFromEntry; } }
edgeofmagic/large-hashmap
large-hashmap/src/test/java/org/logicmill/util/concurrent/WrongBucketException.java
Java
apache-2.0
2,401
// Copyright 2005 The Apache Software Foundation // // 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.apache.tapestry.annotations; import org.apache.hivemind.Location; import org.apache.tapestry.enhance.EnhancementOperation; import org.apache.tapestry.enhance.InjectComponentWorker; import org.apache.tapestry.spec.IComponentSpecification; /** * Tests for {@link org.apache.tapestry.annotations.InjectComponentAnnotationWorker}. * * @author Howard M. Lewis Ship * @since 4.0 */ public class TestInjectComponentAnnotationWorker extends BaseAnnotationTestCase { public void testDefault() { InjectComponentAnnotationWorker worker = new InjectComponentAnnotationWorker(); assertNotNull(worker._delegate); } public void testDelegation() { Location l = newLocation(); EnhancementOperation op = newOp(); IComponentSpecification spec = newSpec(); InjectComponentWorker delegate = (InjectComponentWorker) newMock(InjectComponentWorker.class); delegate.injectComponent(op, "fred", "fredField", l); replayControls(); InjectComponentAnnotationWorker worker = new InjectComponentAnnotationWorker(delegate); worker.performEnhancement(op, spec, findMethod(AnnotatedPage.class, "getFredField"), l); verifyControls(); } }
apache/tapestry4
annotations/src/test/org/apache/tapestry/annotations/TestInjectComponentAnnotationWorker.java
Java
apache-2.0
1,852
package com.huawei.ism.openapi.snapshot; import java.util.List; import java.util.Map; import com.huawei.ism.openapi.common.batchquery.ApiIterator; import com.huawei.ism.openapi.common.commu.rest.RestManager; import com.huawei.ism.openapi.common.commu.rest.RestRequestHandler; import com.huawei.ism.openapi.common.exception.ApiException; import com.huawei.ism.openapi.common.keydeifines.TLV.SNAPSHOT; import com.huawei.ism.openapi.common.utils.OpenApiUtils; /** * 快照的迭代器 * @author w00208247 * @version [版本号V001R010C10] */ public class SnapshotIterator extends ApiIterator<SnapshotMO, SnapshotQuery> { private static final String[] preciseFilter = {SNAPSHOT.PARENTID, SNAPSHOT.HEALTHSTATUS, SNAPSHOT.RUNNINGSTATUS}; private static final String[] fuzzyFilter = {SNAPSHOT.NAME, SNAPSHOT.ID}; /** * 快照迭代器的构造函数 * @param restRequestHandler rest请求 * @param deviceID 网元id * @param queryCondition 查询条件 */ public SnapshotIterator(RestRequestHandler restRequestHandler, String deviceID, SnapshotQuery queryCondition) { super(restRequestHandler, deviceID, queryCondition, false); } /** * 获取对应MO的数量 * @return long * @throws ApiException API异常 */ protected long getConcretCount() throws ApiException { String relativePath = OpenApiUtils.getOpenApiUtilsInstance().composeRelativeUri(getDeviceId(), "SNAPSHOT", "count"); Map<String, String> headParamMap = composeRequestHeader(false); RestManager<SnapshotMO> restManager = new RestManager<SnapshotMO>(SnapshotMO.class, getRestRequestHandler(), relativePath, headParamMap, null); SnapshotMO resPonsemo = restManager.getGetRequestMO(); return resPonsemo.getCount(); } /** * 获取具体MO批量查询的结果 * @return List<SnapshotMO> * @throws ApiException API自定义异常 */ protected List<SnapshotMO> getConcretBatchNext(boolean isAssociate) throws ApiException { String relativePath = OpenApiUtils.getOpenApiUtilsInstance().composeRelativeUri(getDeviceId(), "SNAPSHOT"); Map<String, String> headParamMap = composeRequestHeader(true); RestManager<SnapshotMO> restManager = new RestManager<SnapshotMO>(SnapshotMO.class, getRestRequestHandler(), relativePath, headParamMap, null); List<SnapshotMO> resPonsemoList = restManager.getGetRequestMOList(); return resPonsemoList; } /** * 获取Snapshot 属性Map * @param modelMo Snapshot 数据对象 * @return Snapshot 属性Map */ @Override protected Map<Object, Object> getConcretMoMap(SnapshotMO modelMo) { return (null != modelMo) ? (modelMo.getMO().getProperties()) : null; } /** * 获取SNAPSHOT批量查询条件数组 * @return SNAPSHOT批量查询条件数组 */ @Override protected String[] getConcretFilterHeaders() { return preciseFilter; } @Override protected String[] getFuzzyFilterHeaders() { return fuzzyFilter; } }
eSDK/esdk_storage_native_java
source/OpenApi/src/main/java/com/huawei/ism/openapi/snapshot/SnapshotIterator.java
Java
apache-2.0
3,172
/** * Copyright 2013 Petros Pissias. * * 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.jlcf.core; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.jlcf.core.dynrec.ConnectorTimingBasedReconfigurationManager; /** * This interecepts and forwards the calls to the component proxy handler. * This is the 2nd level wrapper, on top of the component POJO and the component Proxy Handler. * There is one connector created per formal component interface. * * The main purpose of a connector is to selectively block calls directed at the * component during dynamic reconfiguration. * * @author Petros Pissias * */ public class ConnectorHandler implements InvocationHandler, IConnectorManager { //the component proxy instance. //called by the component framework and user threads so needs to be volatile. private volatile Object componentProxy; //the proxy handler of the component private volatile IComponentProxy componentProxyHandler; //the connector reconfiguration manager //TODO change actual implementation based on a configuration file. private final ConnectorTimingBasedReconfigurationManager connectorReconfigurationManager; private final Logger logger = Logger.getLogger(getClass()); //name of this connector, primarily for logging private final String name; public ConnectorHandler(Object componentProxyInstance, IComponentProxy compProxyHandler, String name) { componentProxy = componentProxyInstance; this.name = name; this.componentProxyHandler = compProxyHandler; connectorReconfigurationManager = new ConnectorTimingBasedReconfigurationManager(); connectorReconfigurationManager.setComponentProxy(componentProxyHandler); } /* (non-Javadoc) * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[]) */ @Override public Object invoke(Object proxy, Method m, Object[] arguments) throws Throwable { //logger.debug(name+" invoking connector reconf manager start method"); connectorReconfigurationManager.startCall(m, arguments); //logger.debug(name+" invoking target component proxy"); Object ret; //the return try { ret = m.invoke(componentProxy, arguments); }catch (InvocationTargetException ex) { if (ex.getCause() == null) { throw (ex); } else { throw (ex.getCause()); //throw the actual exception of the target interface } } //logger.debug(name+" invoking connector reconf manager finish method"); connectorReconfigurationManager.finishCall(m, arguments); return ret; } @Override //called by the framework at startup and after a reconfiguration to set the component proxy target. public void setTarget(Object target, IComponentProxy componentProxyHandler) { //logger.debug(name+" setting target"); this.componentProxy = target; this.componentProxyHandler = componentProxyHandler; connectorReconfigurationManager.setComponentProxy(componentProxyHandler); } @Override //called by the framework reconfiguration manager to declare the start of a reconfiguration. public void setReconfiguring(boolean reconfiguring, long millis) { connectorReconfigurationManager.setReconfiguring(reconfiguring, millis); } }
ppissias/JLCF
src/org/jlcf/core/ConnectorHandler.java
Java
apache-2.0
3,868
package pgcon3; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Permutation { static boolean bElapsed = false; void solve(BufferedReader br) throws Exception { List<Integer> list = new ArrayList<>(); for (int i=1; i<=3; i++) { list.add(i); } Collections.sort(list); List<Integer> tmpList = new ArrayList<>(); search(list, tmpList); } void search(List<Integer> list, List<Integer> tmpList) { if (list.size() == tmpList.size()) { pln(tmpList.toString()); return; } for (int i=0; i<list.size(); i++) { int v = list.get(i); if (tmpList.contains(v)) continue; tmpList.add(v); search(list, tmpList); tmpList.remove(tmpList.size()-1); } } void p(char c) { System.out.print(c); } void pln(char c) { System.out.println(c); } void p(long l) { System.out.print(l); } void pln(long l) { System.out.println(l); } void p(String s) { System.out.print(s); } void pln(String s) { System.out.println(s); } //Integer.MAX_VALUE=2147483647>10^9 //Long.MAX_VALUE=9223372036854775807L>10^18 public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); new Permutation().solve(br); long end = System.currentTimeMillis(); if (bElapsed) { System.out.println((end-start) + "ms"); } } }
hiuchida/exam
java/pgcon3/Permutation.java
Java
apache-2.0
1,481
/** * © Copyright IBM Corporation 2016. * © Copyright HCL Technologies Ltd. 2017. * LICENSE: Apache License, Version 2.0 https://www.apache.org/licenses/LICENSE-2.0 */ package com.hcl.appscan.sdk.presence; import java.util.Map; public interface IPresenceProvider { /** * Gets the available presences. * @return A Map of presences, keyed by the presence id. */ public Map<String, String> getPresences(); /** * Gets the name of the presence with the given id. * @param id The id of the presence. * @return The presence name. */ public String getName(String id); /** * Deletes the presence with the given id. * @param id The id of the presence to delete. * @return true if the delete was successful. */ public boolean delete(String id); /** * Retrieves details about the presence with the given id. * @param id The id of the presence. * @return A Map containing details of the presence. */ public Map<String, String> getDetails(String id); /** * Generate a new key for the given presence. * @param id The id of the presence to generate the new key for. * @return The new key. */ public String getNewKey(String id); }
AppSecDev/appscan-sdk
src/main/java/com/hcl/appscan/sdk/presence/IPresenceProvider.java
Java
apache-2.0
1,182
/* * Copyright 2022 Apollo Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.ctrip.framework.apollo.openapi.client.service; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.apache.http.client.methods.HttpGet; import org.apache.http.entity.StringEntity; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; public class AppOpenApiServiceTest extends AbstractOpenApiServiceTest { private AppOpenApiService appOpenApiService; private String someAppId; @Override @Before public void setUp() throws Exception { super.setUp(); someAppId = "someAppId"; StringEntity responseEntity = new StringEntity("[]"); when(someHttpResponse.getEntity()).thenReturn(responseEntity); appOpenApiService = new AppOpenApiService(httpClient, someBaseUrl, gson); } @Test public void testGetEnvClusterInfo() throws Exception { final ArgumentCaptor<HttpGet> request = ArgumentCaptor.forClass(HttpGet.class); appOpenApiService.getEnvClusterInfo(someAppId); verify(httpClient, times(1)).execute(request.capture()); HttpGet get = request.getValue(); assertEquals(String .format("%s/apps/%s/envclusters", someBaseUrl, someAppId), get.getURI().toString()); } @Test(expected = RuntimeException.class) public void testGetEnvClusterInfoWithError() throws Exception { when(statusLine.getStatusCode()).thenReturn(500); appOpenApiService.getEnvClusterInfo(someAppId); } }
nobodyiam/apollo
apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/AppOpenApiServiceTest.java
Java
apache-2.0
2,120
package de.hub.emffrag.testmodels.frag.testmodel.util.builder; /** * <!-- begin-user-doc --> * A builder for the model object '<em><b>de.hub.emffrag.testmodels.frag.testmodel.TestContainmentIndex</b></em>'. * <!-- end-user-doc --> * * @generated */ public class TestContainmentIndexBuilder implements de.hub.emffrag.testmodels.frag.testmodel.util.builder.ITestmodelBuilder<de.hub.emffrag.testmodels.frag.testmodel.TestContainmentIndex> { // features and builders private java.lang.String m_prefix; // helper attributes private boolean m_featurePrefixSet = false; /** * Builder is not instantiated with a constructor. * @see #newTestContainmentIndexBuilder() */ private TestContainmentIndexBuilder() { } /** * This method creates a new instance of the TestContainmentIndexBuilder. * @return new instance of the TestContainmentIndexBuilder */ public static TestContainmentIndexBuilder newTestContainmentIndexBuilder() { return new TestContainmentIndexBuilder(); } /** * This method creates a new instance of the TestContainmentIndexBuilder. * The builder is initialized using an existing '<em><b>de.hub.emffrag.testmodels.frag.testmodel.TestContainmentIndex</b></em>' model object. * In order to avoid changes to the provided '<em><b>de.hub.emffrag.testmodels.frag.testmodel.TestContainmentIndex</b></em>' model object, a copy is created using <em><b>org.eclipse.emf.ecore.util.EcoreUtil.Copier</b></em>. * @param testContainmentIndex The existing '<em><b>de.hub.emffrag.testmodels.frag.testmodel.TestContainmentIndex</b></em>' model object to be used for the initialization of the builder * @return new initialized instance of the TestContainmentIndexBuilder */ public static TestContainmentIndexBuilder newTestContainmentIndexBuilder(de.hub.emffrag.testmodels.frag.testmodel.TestContainmentIndex p_testContainmentIndex) { org.eclipse.emf.ecore.util.EcoreUtil.Copier c = new org.eclipse.emf.ecore.util.EcoreUtil.Copier(); de.hub.emffrag.testmodels.frag.testmodel.TestContainmentIndex _testContainmentIndex = (de.hub.emffrag.testmodels.frag.testmodel.TestContainmentIndex) c .copy(((de.hub.emffrag.testmodels.frag.testmodel.TestContainmentIndex) p_testContainmentIndex)); c.copyReferences(); TestContainmentIndexBuilder _builder = newTestContainmentIndexBuilder(); _builder.prefix(_testContainmentIndex.getPrefix()); return _builder; } /** * This method can be used to override attributes of the builder. It constructs a new builder and copies the current values to it. */ public TestContainmentIndexBuilder but() { TestContainmentIndexBuilder _builder = newTestContainmentIndexBuilder(); _builder.m_featurePrefixSet = m_featurePrefixSet; _builder.m_prefix = m_prefix; return _builder; } /** * This method constructs the final de.hub.emffrag.testmodels.frag.testmodel.TestContainmentIndex type. * @return new instance of the de.hub.emffrag.testmodels.frag.testmodel.TestContainmentIndex type */ public de.hub.emffrag.testmodels.frag.testmodel.TestContainmentIndex build() { final de.hub.emffrag.testmodels.frag.testmodel.TestContainmentIndex _newInstance = (de.hub.emffrag.testmodels.frag.testmodel.TestContainmentIndex) de.hub.emffrag.testmodels.frag.testmodel.TestModelFactory.eINSTANCE .create(de.hub.emffrag.testmodels.frag.testmodel.TestModelPackage.eINSTANCE.getTestContainmentIndex()); if (m_featurePrefixSet) { _newInstance.setPrefix(m_prefix); } return _newInstance; } public TestContainmentIndexBuilder prefix(java.lang.String p_prefix) { m_prefix = p_prefix; m_featurePrefixSet = true; return this; } }
srirammails/emf-fragments
de.hub.emffrag.testmodels/gen-src/de/hub/emffrag/testmodels/frag/testmodel/util/builder/TestContainmentIndexBuilder.java
Java
apache-2.0
3,719
package org.zstack.image; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.zstack.core.Platform; import org.zstack.core.asyncbatch.AsyncBatchRunner; import org.zstack.core.asyncbatch.LoopAsyncBatch; import org.zstack.core.cloudbus.*; import org.zstack.core.componentloader.PluginRegistry; import org.zstack.core.config.GlobalConfig; import org.zstack.core.config.GlobalConfigUpdateExtensionPoint; import org.zstack.core.db.DatabaseFacade; import org.zstack.core.db.SimpleQuery; import org.zstack.core.db.SimpleQuery.Op; import org.zstack.core.defer.Defer; import org.zstack.core.defer.Deferred; import org.zstack.core.errorcode.ErrorFacade; import org.zstack.core.thread.CancelablePeriodicTask; import org.zstack.core.thread.ThreadFacade; import org.zstack.core.workflow.FlowChainBuilder; import org.zstack.core.workflow.ShareFlow; import org.zstack.header.AbstractService; import org.zstack.header.core.AsyncLatch; import org.zstack.header.core.NoErrorCompletion; import org.zstack.header.core.workflow.*; import org.zstack.header.errorcode.ErrorCode; import org.zstack.header.errorcode.ErrorCodeList; import org.zstack.header.errorcode.SysErrors; import org.zstack.header.exception.CloudRuntimeException; import org.zstack.header.identity.*; import org.zstack.header.image.*; import org.zstack.header.image.APICreateRootVolumeTemplateFromVolumeSnapshotEvent.Failure; import org.zstack.header.image.ImageConstant.ImageMediaType; import org.zstack.header.image.ImageDeletionPolicyManager.ImageDeletionPolicy; import org.zstack.header.managementnode.ManagementNodeReadyExtensionPoint; import org.zstack.header.message.APIMessage; import org.zstack.header.message.Message; import org.zstack.header.message.MessageReply; import org.zstack.header.message.NeedQuotaCheckMessage; import org.zstack.header.rest.RESTFacade; import org.zstack.header.search.SearchOp; import org.zstack.header.storage.backup.*; import org.zstack.header.storage.primary.PrimaryStorageVO; import org.zstack.header.storage.primary.PrimaryStorageVO_; import org.zstack.header.storage.snapshot.*; import org.zstack.header.vm.CreateTemplateFromVmRootVolumeMsg; import org.zstack.header.vm.CreateTemplateFromVmRootVolumeReply; import org.zstack.header.vm.VmInstanceConstant; import org.zstack.header.volume.*; import org.zstack.identity.AccountManager; import org.zstack.identity.QuotaUtil; import org.zstack.search.SearchQuery; import org.zstack.tag.TagManager; import org.zstack.utils.CollectionUtils; import org.zstack.utils.ObjectUtils; import org.zstack.utils.RunOnce; import org.zstack.utils.Utils; import org.zstack.utils.data.SizeUnit; import org.zstack.utils.function.ForEachFunction; import org.zstack.utils.function.Function; import org.zstack.utils.gson.JSONObjectUtil; import org.zstack.utils.logging.CLogger; import javax.persistence.Tuple; import javax.persistence.TypedQuery; import java.sql.Timestamp; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import static org.zstack.utils.CollectionDSL.list; public class ImageManagerImpl extends AbstractService implements ImageManager, ManagementNodeReadyExtensionPoint, ReportQuotaExtensionPoint, ResourceOwnerPreChangeExtensionPoint { private static final CLogger logger = Utils.getLogger(ImageManagerImpl.class); @Autowired private CloudBus bus; @Autowired private PluginRegistry pluginRgty; @Autowired private DatabaseFacade dbf; @Autowired private AccountManager acntMgr; @Autowired private ErrorFacade errf; @Autowired private TagManager tagMgr; @Autowired private ThreadFacade thdf; @Autowired private ResourceDestinationMaker destMaker; @Autowired private ImageDeletionPolicyManager deletionPolicyMgr; @Autowired protected RESTFacade restf; private Map<String, ImageFactory> imageFactories = Collections.synchronizedMap(new HashMap<>()); private static final Set<Class> allowedMessageAfterDeletion = new HashSet<>(); private Future<Void> expungeTask; static { allowedMessageAfterDeletion.add(ImageDeletionMsg.class); } @Override @MessageSafe public void handleMessage(Message msg) { if (msg instanceof ImageMessage) { passThrough((ImageMessage) msg); } else if (msg instanceof APIMessage) { handleApiMessage(msg); } else { handleLocalMessage(msg); } } private void handleLocalMessage(Message msg) { bus.dealWithUnknownMessage(msg); } private void handleApiMessage(Message msg) { if (msg instanceof APIAddImageMsg) { handle((APIAddImageMsg) msg); } else if (msg instanceof APIListImageMsg) { handle((APIListImageMsg) msg); } else if (msg instanceof APISearchImageMsg) { handle((APISearchImageMsg) msg); } else if (msg instanceof APIGetImageMsg) { handle((APIGetImageMsg) msg); } else if (msg instanceof APICreateRootVolumeTemplateFromRootVolumeMsg) { handle((APICreateRootVolumeTemplateFromRootVolumeMsg) msg); } else if (msg instanceof APICreateRootVolumeTemplateFromVolumeSnapshotMsg) { handle((APICreateRootVolumeTemplateFromVolumeSnapshotMsg) msg); } else if (msg instanceof APICreateDataVolumeTemplateFromVolumeMsg) { handle((APICreateDataVolumeTemplateFromVolumeMsg) msg); } else { bus.dealWithUnknownMessage(msg); } } private void handle(final APICreateDataVolumeTemplateFromVolumeMsg msg) { final APICreateDataVolumeTemplateFromVolumeEvent evt = new APICreateDataVolumeTemplateFromVolumeEvent(msg.getId()); FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("create-data-volume-template-from-volume-%s", msg.getVolumeUuid())); chain.then(new ShareFlow() { List<BackupStorageInventory> backupStorage = new ArrayList<>(); ImageVO image; long actualSize; @Override public void setup() { flow(new NoRollbackFlow() { String __name__ = "get-actual-size-of-data-volume"; @Override public void run(final FlowTrigger trigger, Map data) { SyncVolumeSizeMsg smsg = new SyncVolumeSizeMsg(); smsg.setVolumeUuid(msg.getVolumeUuid()); bus.makeTargetServiceIdByResourceUuid(smsg, VolumeConstant.SERVICE_ID, msg.getVolumeUuid()); bus.send(smsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { trigger.fail(reply.getError()); return; } SyncVolumeSizeReply sr = reply.castReply(); actualSize = sr.getActualSize(); trigger.next(); } }); } }); flow(new Flow() { String __name__ = "create-image-in-database"; @Override public void run(FlowTrigger trigger, Map data) { SimpleQuery<VolumeVO> q = dbf.createQuery(VolumeVO.class); q.select(VolumeVO_.format, VolumeVO_.size); q.add(VolumeVO_.uuid, Op.EQ, msg.getVolumeUuid()); Tuple t = q.findTuple(); String format = t.get(0, String.class); long size = t.get(1, Long.class); final ImageVO vo = new ImageVO(); vo.setUuid(msg.getResourceUuid() == null ? Platform.getUuid() : msg.getResourceUuid()); vo.setName(msg.getName()); vo.setDescription(msg.getDescription()); vo.setType(ImageConstant.ZSTACK_IMAGE_TYPE); vo.setMediaType(ImageMediaType.DataVolumeTemplate); vo.setSize(size); vo.setActualSize(actualSize); vo.setState(ImageState.Enabled); vo.setStatus(ImageStatus.Creating); vo.setFormat(format); vo.setUrl(String.format("volume://%s", msg.getVolumeUuid())); image = dbf.persistAndRefresh(vo); acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), vo.getUuid(), ImageVO.class); tagMgr.createTagsFromAPICreateMessage(msg, vo.getUuid(), ImageVO.class.getSimpleName()); trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { if (image != null) { dbf.remove(image); } trigger.rollback(); } }); flow(new Flow() { String __name__ = "select-backup-storage"; @Override public void run(final FlowTrigger trigger, Map data) { final String zoneUuid = new Callable<String>() { @Override @Transactional(readOnly = true) public String call() { String sql = "select ps.zoneUuid" + " from PrimaryStorageVO ps, VolumeVO vol" + " where vol.primaryStorageUuid = ps.uuid" + " and vol.uuid = :volUuid"; TypedQuery<String> q = dbf.getEntityManager().createQuery(sql, String.class); q.setParameter("volUuid", msg.getVolumeUuid()); return q.getSingleResult(); } }.call(); if (msg.getBackupStorageUuids() == null) { AllocateBackupStorageMsg amsg = new AllocateBackupStorageMsg(); amsg.setRequiredZoneUuid(zoneUuid); amsg.setSize(actualSize); bus.makeLocalServiceId(amsg, BackupStorageConstant.SERVICE_ID); bus.send(amsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (reply.isSuccess()) { backupStorage.add(((AllocateBackupStorageReply) reply).getInventory()); trigger.next(); } else { trigger.fail(errf.stringToOperationError("cannot find proper backup storage", reply.getError())); } } }); } else { List<AllocateBackupStorageMsg> amsgs = CollectionUtils.transformToList(msg.getBackupStorageUuids(), new Function<AllocateBackupStorageMsg, String>() { @Override public AllocateBackupStorageMsg call(String arg) { AllocateBackupStorageMsg amsg = new AllocateBackupStorageMsg(); amsg.setRequiredZoneUuid(zoneUuid); amsg.setSize(actualSize); amsg.setBackupStorageUuid(arg); bus.makeLocalServiceId(amsg, BackupStorageConstant.SERVICE_ID); return amsg; } }); bus.send(amsgs, new CloudBusListCallBack(trigger) { @Override public void run(List<MessageReply> replies) { List<ErrorCode> errs = new ArrayList<>(); for (MessageReply r : replies) { if (r.isSuccess()) { backupStorage.add(((AllocateBackupStorageReply) r).getInventory()); } else { errs.add(r.getError()); } } if (backupStorage.isEmpty()) { trigger.fail(errf.stringToOperationError(String.format("failed to allocate all backup storage[uuid:%s], a list of error: %s", msg.getBackupStorageUuids(), JSONObjectUtil.toJsonString(errs)))); } else { trigger.next(); } } }); } } @Override public void rollback(FlowRollback trigger, Map data) { if (!backupStorage.isEmpty()) { List<ReturnBackupStorageMsg> rmsgs = CollectionUtils.transformToList(backupStorage, new Function<ReturnBackupStorageMsg, BackupStorageInventory>() { @Override public ReturnBackupStorageMsg call(BackupStorageInventory arg) { ReturnBackupStorageMsg rmsg = new ReturnBackupStorageMsg(); rmsg.setBackupStorageUuid(arg.getUuid()); rmsg.setSize(actualSize); bus.makeLocalServiceId(rmsg, BackupStorageConstant.SERVICE_ID); return rmsg; } }); bus.send(rmsgs, new CloudBusListCallBack(null) { @Override public void run(List<MessageReply> replies) { for (MessageReply r : replies) { BackupStorageInventory bs = backupStorage.get(replies.indexOf(r)); logger.warn(String.format("failed to return %s bytes to backup storage[uuid:%s]", acntMgr, bs.getUuid())); } } }); } trigger.rollback(); } }); flow(new NoRollbackFlow() { String __name__ = "create-data-volume-template-from-volume"; @Override public void run(final FlowTrigger trigger, Map data) { List<CreateDataVolumeTemplateFromDataVolumeMsg> cmsgs = CollectionUtils.transformToList(backupStorage, new Function<CreateDataVolumeTemplateFromDataVolumeMsg, BackupStorageInventory>() { @Override public CreateDataVolumeTemplateFromDataVolumeMsg call(BackupStorageInventory bs) { CreateDataVolumeTemplateFromDataVolumeMsg cmsg = new CreateDataVolumeTemplateFromDataVolumeMsg(); cmsg.setVolumeUuid(msg.getVolumeUuid()); cmsg.setBackupStorageUuid(bs.getUuid()); cmsg.setImageUuid(image.getUuid()); bus.makeTargetServiceIdByResourceUuid(cmsg, VolumeConstant.SERVICE_ID, msg.getVolumeUuid()); return cmsg; } }); bus.send(cmsgs, new CloudBusListCallBack(msg) { @Override public void run(List<MessageReply> replies) { int fail = 0; String mdsum = null; ErrorCode err = null; String format = null; for (MessageReply r : replies) { BackupStorageInventory bs = backupStorage.get(replies.indexOf(r)); if (!r.isSuccess()) { logger.warn(String.format("failed to create data volume template from volume[uuid:%s] on backup storage[uuid:%s], %s", msg.getVolumeUuid(), bs.getUuid(), r.getError())); fail++; err = r.getError(); continue; } CreateDataVolumeTemplateFromDataVolumeReply reply = r.castReply(); ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO(); ref.setBackupStorageUuid(bs.getUuid()); ref.setStatus(ImageStatus.Ready); ref.setImageUuid(image.getUuid()); ref.setInstallPath(reply.getInstallPath()); dbf.persist(ref); if (mdsum == null) { mdsum = reply.getMd5sum(); } if (reply.getFormat() != null) { format = reply.getFormat(); } } int backupStorageNum = msg.getBackupStorageUuids() == null ? 1 : msg.getBackupStorageUuids().size(); if (fail == backupStorageNum) { ErrorCode errCode = errf.instantiateErrorCode(SysErrors.OPERATION_ERROR, String.format("failed to create data volume template from volume[uuid:%s] on all backup storage%s. See cause for one of errors", msg.getVolumeUuid(), msg.getBackupStorageUuids()), err ); trigger.fail(errCode); } else { image = dbf.reload(image); if (format != null) { image.setFormat(format); } image.setMd5Sum(mdsum); image.setStatus(ImageStatus.Ready); image = dbf.updateAndRefresh(image); trigger.next(); } } }); } }); done(new FlowDoneHandler(msg) { @Override public void handle(Map data) { evt.setInventory(ImageInventory.valueOf(image)); bus.publish(evt); } }); error(new FlowErrorHandler(msg) { @Override public void handle(ErrorCode errCode, Map data) { evt.setError(errCode); bus.publish(evt); } }); } }).start(); } private void handle(final APICreateRootVolumeTemplateFromVolumeSnapshotMsg msg) { final APICreateRootVolumeTemplateFromVolumeSnapshotEvent evt = new APICreateRootVolumeTemplateFromVolumeSnapshotEvent(msg.getId()); SimpleQuery<VolumeSnapshotVO> q = dbf.createQuery(VolumeSnapshotVO.class); q.select(VolumeSnapshotVO_.format); q.add(VolumeSnapshotVO_.uuid, Op.EQ, msg.getSnapshotUuid()); String format = q.findValue(); final ImageVO vo = new ImageVO(); if (msg.getResourceUuid() != null) { vo.setUuid(msg.getResourceUuid()); } else { vo.setUuid(Platform.getUuid()); } vo.setName(msg.getName()); vo.setSystem(msg.isSystem()); vo.setDescription(msg.getDescription()); vo.setPlatform(ImagePlatform.valueOf(msg.getPlatform())); vo.setGuestOsType(vo.getGuestOsType()); vo.setStatus(ImageStatus.Creating); vo.setState(ImageState.Enabled); vo.setFormat(format); vo.setMediaType(ImageMediaType.RootVolumeTemplate); vo.setType(ImageConstant.ZSTACK_IMAGE_TYPE); vo.setUrl(String.format("volumeSnapshot://%s", msg.getSnapshotUuid())); dbf.persist(vo); acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), vo.getUuid(), ImageVO.class); tagMgr.createTagsFromAPICreateMessage(msg, vo.getUuid(), ImageVO.class.getSimpleName()); SimpleQuery<VolumeSnapshotVO> sq = dbf.createQuery(VolumeSnapshotVO.class); sq.select(VolumeSnapshotVO_.volumeUuid, VolumeSnapshotVO_.treeUuid); sq.add(VolumeSnapshotVO_.uuid, Op.EQ, msg.getSnapshotUuid()); Tuple t = sq.findTuple(); String volumeUuid = t.get(0, String.class); String treeUuid = t.get(1, String.class); List<CreateTemplateFromVolumeSnapshotMsg> cmsgs = msg.getBackupStorageUuids().stream().map(bsUuid -> { CreateTemplateFromVolumeSnapshotMsg cmsg = new CreateTemplateFromVolumeSnapshotMsg(); cmsg.setSnapshotUuid(msg.getSnapshotUuid()); cmsg.setImageUuid(vo.getUuid()); cmsg.setVolumeUuid(volumeUuid); cmsg.setTreeUuid(treeUuid); cmsg.setBackupStorageUuid(bsUuid); String resourceUuid = volumeUuid != null ? volumeUuid : treeUuid; bus.makeTargetServiceIdByResourceUuid(cmsg, VolumeSnapshotConstant.SERVICE_ID, resourceUuid); return cmsg; }).collect(Collectors.toList()); List<Failure> failures = new ArrayList<>(); AsyncLatch latch = new AsyncLatch(cmsgs.size(), new NoErrorCompletion(msg) { @Override public void done() { if (failures.size() == cmsgs.size()) { // failed on all ErrorCodeList error = errf.stringToOperationError(String.format("failed to create template from" + " the volume snapshot[uuid:%s] on backup storage[uuids:%s]", msg.getSnapshotUuid(), msg.getBackupStorageUuids()), failures.stream().map(f -> f.error).collect(Collectors.toList())); evt.setError(error); dbf.remove(vo); } else { ImageVO imvo = dbf.reload(vo); evt.setInventory(ImageInventory.valueOf(imvo)); logger.debug(String.format("successfully created image[uuid:%s, name:%s] from volume snapshot[uuid:%s]", imvo.getUuid(), imvo.getName(), msg.getSnapshotUuid())); } if (!failures.isEmpty()) { evt.setFailuresOnBackupStorage(failures); } bus.publish(evt); } }); RunOnce once = new RunOnce(); for (CreateTemplateFromVolumeSnapshotMsg cmsg : cmsgs) { bus.send(cmsg, new CloudBusCallBack(latch) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { synchronized (failures) { Failure failure = new Failure(); failure.error = reply.getError(); failure.backupStorageUuid = cmsg.getBackupStorageUuid(); failures.add(failure); } } else { CreateTemplateFromVolumeSnapshotReply cr = reply.castReply(); ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO(); ref.setBackupStorageUuid(cr.getBackupStorageUuid()); ref.setInstallPath(cr.getBackupStorageInstallPath()); ref.setStatus(ImageStatus.Ready); ref.setImageUuid(vo.getUuid()); dbf.persist(ref); once.run(() -> { vo.setSize(cr.getSize()); vo.setActualSize(cr.getActualSize()); vo.setStatus(ImageStatus.Ready); dbf.update(vo); }); } latch.ack(); } }); } } private void passThrough(ImageMessage msg) { ImageVO vo = dbf.findByUuid(msg.getImageUuid(), ImageVO.class); if (vo == null && allowedMessageAfterDeletion.contains(msg.getClass())) { ImageEO eo = dbf.findByUuid(msg.getImageUuid(), ImageEO.class); vo = ObjectUtils.newAndCopy(eo, ImageVO.class); } if (vo == null) { String err = String.format("Cannot find image[uuid:%s], it may have been deleted", msg.getImageUuid()); logger.warn(err); bus.replyErrorByMessageType((Message) msg, errf.instantiateErrorCode(SysErrors.RESOURCE_NOT_FOUND, err)); return; } ImageFactory factory = getImageFacotry(ImageType.valueOf(vo.getType())); Image img = factory.getImage(vo); img.handleMessage((Message) msg); } private void handle(final APICreateRootVolumeTemplateFromRootVolumeMsg msg) { FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("create-template-from-root-volume-%s", msg.getRootVolumeUuid())); chain.then(new ShareFlow() { ImageVO imageVO; VolumeInventory rootVolume; Long imageActualSize; List<BackupStorageInventory> targetBackupStorages = new ArrayList<>(); String zoneUuid; { VolumeVO rootvo = dbf.findByUuid(msg.getRootVolumeUuid(), VolumeVO.class); rootVolume = VolumeInventory.valueOf(rootvo); SimpleQuery<PrimaryStorageVO> q = dbf.createQuery(PrimaryStorageVO.class); q.select(PrimaryStorageVO_.zoneUuid); q.add(PrimaryStorageVO_.uuid, Op.EQ, rootVolume.getPrimaryStorageUuid()); zoneUuid = q.findValue(); } @Override public void setup() { flow(new NoRollbackFlow() { String __name__ = "get-volume-actual-size"; @Override public void run(final FlowTrigger trigger, Map data) { SyncVolumeSizeMsg msg = new SyncVolumeSizeMsg(); msg.setVolumeUuid(rootVolume.getUuid()); bus.makeTargetServiceIdByResourceUuid(msg, VolumeConstant.SERVICE_ID, rootVolume.getPrimaryStorageUuid()); bus.send(msg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { trigger.fail(reply.getError()); return; } SyncVolumeSizeReply sr = reply.castReply(); imageActualSize = sr.getActualSize(); trigger.next(); } }); } }); flow(new Flow() { String __name__ = "create-image-in-database"; public void run(FlowTrigger trigger, Map data) { SimpleQuery<VolumeVO> q = dbf.createQuery(VolumeVO.class); q.add(VolumeVO_.uuid, Op.EQ, msg.getRootVolumeUuid()); final VolumeVO volvo = q.find(); String accountUuid = acntMgr.getOwnerAccountUuidOfResource(volvo.getUuid()); final ImageVO imvo = new ImageVO(); if (msg.getResourceUuid() != null) { imvo.setUuid(msg.getResourceUuid()); } else { imvo.setUuid(Platform.getUuid()); } imvo.setDescription(msg.getDescription()); imvo.setMediaType(ImageMediaType.RootVolumeTemplate); imvo.setState(ImageState.Enabled); imvo.setGuestOsType(msg.getGuestOsType()); imvo.setFormat(volvo.getFormat()); imvo.setName(msg.getName()); imvo.setSystem(msg.isSystem()); imvo.setPlatform(ImagePlatform.valueOf(msg.getPlatform())); imvo.setStatus(ImageStatus.Downloading); imvo.setType(ImageConstant.ZSTACK_IMAGE_TYPE); imvo.setUrl(String.format("volume://%s", msg.getRootVolumeUuid())); imvo.setSize(volvo.getSize()); imvo.setActualSize(imageActualSize); dbf.persist(imvo); acntMgr.createAccountResourceRef(accountUuid, imvo.getUuid(), ImageVO.class); tagMgr.createTagsFromAPICreateMessage(msg, imvo.getUuid(), ImageVO.class.getSimpleName()); imageVO = imvo; trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { if (imageVO != null) { dbf.remove(imageVO); } trigger.rollback(); } }); flow(new Flow() { String __name__ = String.format("select-backup-storage"); @Override public void run(final FlowTrigger trigger, Map data) { if (msg.getBackupStorageUuids() == null) { AllocateBackupStorageMsg abmsg = new AllocateBackupStorageMsg(); abmsg.setRequiredZoneUuid(zoneUuid); abmsg.setSize(imageActualSize); bus.makeLocalServiceId(abmsg, BackupStorageConstant.SERVICE_ID); bus.send(abmsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (reply.isSuccess()) { targetBackupStorages.add(((AllocateBackupStorageReply) reply).getInventory()); trigger.next(); } else { trigger.fail(reply.getError()); } } }); } else { List<AllocateBackupStorageMsg> amsgs = CollectionUtils.transformToList(msg.getBackupStorageUuids(), new Function<AllocateBackupStorageMsg, String>() { @Override public AllocateBackupStorageMsg call(String arg) { AllocateBackupStorageMsg abmsg = new AllocateBackupStorageMsg(); abmsg.setSize(imageActualSize); abmsg.setBackupStorageUuid(arg); bus.makeLocalServiceId(abmsg, BackupStorageConstant.SERVICE_ID); return abmsg; } }); bus.send(amsgs, new CloudBusListCallBack(trigger) { @Override public void run(List<MessageReply> replies) { List<ErrorCode> errs = new ArrayList<>(); for (MessageReply r : replies) { if (r.isSuccess()) { targetBackupStorages.add(((AllocateBackupStorageReply) r).getInventory()); } else { errs.add(r.getError()); } } if (targetBackupStorages.isEmpty()) { trigger.fail(errf.stringToOperationError(String.format("unable to allocate backup storage specified by uuids%s, list errors are: %s", msg.getBackupStorageUuids(), JSONObjectUtil.toJsonString(errs)))); } else { trigger.next(); } } }); } } @Override public void rollback(final FlowRollback trigger, Map data) { if (targetBackupStorages.isEmpty()) { trigger.rollback(); return; } List<ReturnBackupStorageMsg> rmsgs = CollectionUtils.transformToList(targetBackupStorages, new Function<ReturnBackupStorageMsg, BackupStorageInventory>() { @Override public ReturnBackupStorageMsg call(BackupStorageInventory arg) { ReturnBackupStorageMsg rmsg = new ReturnBackupStorageMsg(); rmsg.setBackupStorageUuid(arg.getUuid()); rmsg.setSize(imageActualSize); bus.makeLocalServiceId(rmsg, BackupStorageConstant.SERVICE_ID); return rmsg; } }); bus.send(rmsgs, new CloudBusListCallBack(trigger) { @Override public void run(List<MessageReply> replies) { for (MessageReply r : replies) { if (!r.isSuccess()) { BackupStorageInventory bs = targetBackupStorages.get(replies.indexOf(r)); logger.warn(String.format("failed to return capacity[%s] to backup storage[uuid:%s], because %s", imageActualSize, bs.getUuid(), r.getError())); } } trigger.rollback(); } }); } }); flow(new NoRollbackFlow() { String __name__ = String.format("start-creating-template"); @Override public void run(final FlowTrigger trigger, Map data) { List<CreateTemplateFromVmRootVolumeMsg> cmsgs = CollectionUtils.transformToList(targetBackupStorages, new Function<CreateTemplateFromVmRootVolumeMsg, BackupStorageInventory>() { @Override public CreateTemplateFromVmRootVolumeMsg call(BackupStorageInventory arg) { CreateTemplateFromVmRootVolumeMsg cmsg = new CreateTemplateFromVmRootVolumeMsg(); cmsg.setRootVolumeInventory(rootVolume); cmsg.setBackupStorageUuid(arg.getUuid()); cmsg.setImageInventory(ImageInventory.valueOf(imageVO)); bus.makeTargetServiceIdByResourceUuid(cmsg, VmInstanceConstant.SERVICE_ID, rootVolume.getVmInstanceUuid()); return cmsg; } }); bus.send(cmsgs, new CloudBusListCallBack(trigger) { @Override public void run(List<MessageReply> replies) { boolean success = false; ErrorCode err = null; for (MessageReply r : replies) { BackupStorageInventory bs = targetBackupStorages.get(replies.indexOf(r)); if (!r.isSuccess()) { logger.warn(String.format("failed to create image from root volume[uuid:%s] on backup storage[uuid:%s], because %s", msg.getRootVolumeUuid(), bs.getUuid(), r.getError())); err = r.getError(); continue; } CreateTemplateFromVmRootVolumeReply reply = (CreateTemplateFromVmRootVolumeReply) r; ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO(); ref.setBackupStorageUuid(bs.getUuid()); ref.setStatus(ImageStatus.Ready); ref.setImageUuid(imageVO.getUuid()); ref.setInstallPath(reply.getInstallPath()); dbf.persist(ref); imageVO.setStatus(ImageStatus.Ready); if (reply.getFormat() != null) { imageVO.setFormat(reply.getFormat()); } dbf.update(imageVO); imageVO = dbf.reload(imageVO); success = true; logger.debug(String.format("successfully created image[uuid:%s] from root volume[uuid:%s] on backup storage[uuid:%s]", imageVO.getUuid(), msg.getRootVolumeUuid(), bs.getUuid())); } if (success) { trigger.next(); } else { trigger.fail(errf.instantiateErrorCode(SysErrors.OPERATION_ERROR, String.format("failed to create image from root volume[uuid:%s] on all backup storage, see cause for one of errors", msg.getRootVolumeUuid()), err)); } } }); } }); flow(new Flow() { String __name__ = "copy-system-tag-to-image"; public void run(FlowTrigger trigger, Map data) { // find the rootimage and create some systemtag if it has SimpleQuery<VolumeVO> q = dbf.createQuery(VolumeVO.class); q.add(VolumeVO_.uuid, SimpleQuery.Op.EQ, msg.getRootVolumeUuid()); q.select(VolumeVO_.vmInstanceUuid); String vmInstanceUuid = q.findValue(); if (tagMgr.hasSystemTag(vmInstanceUuid, ImageSystemTags.IMAGE_INJECT_QEMUGA.getTagFormat())) { tagMgr.createNonInherentSystemTag(imageVO.getUuid(), ImageSystemTags.IMAGE_INJECT_QEMUGA.getTagFormat(), ImageVO.class.getSimpleName()); } trigger.next(); } @Override public void rollback(FlowRollback trigger, Map data) { trigger.rollback(); } }); done(new FlowDoneHandler(msg) { @Override public void handle(Map data) { APICreateRootVolumeTemplateFromRootVolumeEvent evt = new APICreateRootVolumeTemplateFromRootVolumeEvent(msg.getId()); imageVO = dbf.reload(imageVO); ImageInventory iinv = ImageInventory.valueOf(imageVO); evt.setInventory(iinv); logger.warn(String.format("successfully create template[uuid:%s] from root volume[uuid:%s]", iinv.getUuid(), msg.getRootVolumeUuid())); bus.publish(evt); } }); error(new FlowErrorHandler(msg) { @Override public void handle(ErrorCode errCode, Map data) { APICreateRootVolumeTemplateFromRootVolumeEvent evt = new APICreateRootVolumeTemplateFromRootVolumeEvent(msg.getId()); evt.setError(errCode); logger.warn(String.format("failed to create template from root volume[uuid:%s], because %s", msg.getRootVolumeUuid(), errCode)); bus.publish(evt); } }); } }).start(); } private void handle(APIGetImageMsg msg) { SearchQuery<ImageInventory> sq = new SearchQuery(ImageInventory.class); sq.addAccountAsAnd(msg); sq.add("uuid", SearchOp.AND_EQ, msg.getUuid()); List<ImageInventory> invs = sq.list(); APIGetImageReply reply = new APIGetImageReply(); if (!invs.isEmpty()) { reply.setInventory(JSONObjectUtil.toJsonString(invs.get(0))); } bus.reply(msg, reply); } private void handle(APISearchImageMsg msg) { SearchQuery<ImageInventory> sq = SearchQuery.create(msg, ImageInventory.class); sq.addAccountAsAnd(msg); String content = sq.listAsString(); APISearchImageReply reply = new APISearchImageReply(); reply.setContent(content); bus.reply(msg, reply); } private void handle(APIListImageMsg msg) { List<ImageVO> vos = dbf.listAll(ImageVO.class); List<ImageInventory> invs = ImageInventory.valueOf(vos); APIListImageReply reply = new APIListImageReply(); reply.setInventories(invs); bus.reply(msg, reply); } @Deferred private void handle(final APIAddImageMsg msg) { String imageType = msg.getType(); imageType = imageType == null ? DefaultImageFactory.type.toString() : imageType; final APIAddImageEvent evt = new APIAddImageEvent(msg.getId()); ImageVO vo = new ImageVO(); if (msg.getResourceUuid() != null) { vo.setUuid(msg.getResourceUuid()); } else { vo.setUuid(Platform.getUuid()); } vo.setName(msg.getName()); vo.setDescription(msg.getDescription()); if (msg.getFormat().equals(ImageConstant.ISO_FORMAT_STRING)) { vo.setMediaType(ImageMediaType.ISO); } else { vo.setMediaType(ImageMediaType.valueOf(msg.getMediaType())); } vo.setType(imageType); vo.setSystem(msg.isSystem()); vo.setGuestOsType(msg.getGuestOsType()); vo.setFormat(msg.getFormat()); vo.setStatus(ImageStatus.Downloading); vo.setState(ImageState.Enabled); vo.setUrl(msg.getUrl()); vo.setDescription(msg.getDescription()); vo.setPlatform(ImagePlatform.valueOf(msg.getPlatform())); ImageFactory factory = getImageFacotry(ImageType.valueOf(imageType)); final ImageVO ivo = factory.createImage(vo, msg); acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), vo.getUuid(), ImageVO.class); tagMgr.createTagsFromAPICreateMessage(msg, vo.getUuid(), ImageVO.class.getSimpleName()); Defer.guard(() -> dbf.remove(ivo)); final ImageInventory inv = ImageInventory.valueOf(ivo); for (AddImageExtensionPoint ext : pluginRgty.getExtensionList(AddImageExtensionPoint.class)) { ext.preAddImage(inv); } final List<DownloadImageMsg> dmsgs = CollectionUtils.transformToList(msg.getBackupStorageUuids(), new Function<DownloadImageMsg, String>() { @Override public DownloadImageMsg call(String arg) { DownloadImageMsg dmsg = new DownloadImageMsg(inv); dmsg.setBackupStorageUuid(arg); dmsg.setFormat(msg.getFormat()); dmsg.setSystemTags(msg.getSystemTags()); bus.makeTargetServiceIdByResourceUuid(dmsg, BackupStorageConstant.SERVICE_ID, arg); return dmsg; } }); CollectionUtils.safeForEach(pluginRgty.getExtensionList(AddImageExtensionPoint.class), new ForEachFunction<AddImageExtensionPoint>() { @Override public void run(AddImageExtensionPoint ext) { ext.beforeAddImage(inv); } }); new LoopAsyncBatch<DownloadImageMsg>(msg) { AtomicBoolean success = new AtomicBoolean(false); @Override protected Collection<DownloadImageMsg> collect() { return dmsgs; } @Override protected AsyncBatchRunner forEach(DownloadImageMsg dmsg) { return new AsyncBatchRunner() { @Override public void run(NoErrorCompletion completion) { ImageBackupStorageRefVO ref = new ImageBackupStorageRefVO(); ref.setImageUuid(ivo.getUuid()); ref.setInstallPath(""); ref.setBackupStorageUuid(dmsg.getBackupStorageUuid()); ref.setStatus(ImageStatus.Downloading); dbf.persist(ref); bus.send(dmsg, new CloudBusCallBack(completion) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { errors.add(reply.getError()); dbf.remove(ref); } else { DownloadImageReply re = reply.castReply(); ref.setStatus(ImageStatus.Ready); ref.setInstallPath(re.getInstallPath()); dbf.update(ref); if (success.compareAndSet(false, true)) { // In case 'Platform' etc. is changed. ImageVO vo = dbf.reload(ivo); vo.setMd5Sum(re.getMd5sum()); vo.setSize(re.getSize()); vo.setActualSize(re.getActualSize()); vo.setStatus(ImageStatus.Ready); dbf.update(vo); } logger.debug(String.format("successfully downloaded image[uuid:%s, name:%s] to backup storage[uuid:%s]", inv.getUuid(), inv.getName(), dmsg.getBackupStorageUuid())); } completion.done(); } }); } }; } @Override protected void done() { // TODO: check if the database still has the record of the image // if there is no record, that means user delete the image during the downloading, // then we need to cleanup if (success.get()) { ImageVO vo = dbf.reload(ivo); final ImageInventory einv = ImageInventory.valueOf(vo); CollectionUtils.safeForEach(pluginRgty.getExtensionList(AddImageExtensionPoint.class), new ForEachFunction<AddImageExtensionPoint>() { @Override public void run(AddImageExtensionPoint ext) { ext.afterAddImage(einv); } }); evt.setInventory(einv); } else { final ErrorCode err = errf.instantiateErrorCode(SysErrors.CREATE_RESOURCE_ERROR, String.format("Failed to download image[name:%s] on all backup storage%s.", inv.getName(), msg.getBackupStorageUuids()), errors); CollectionUtils.safeForEach(pluginRgty.getExtensionList(AddImageExtensionPoint.class), new ForEachFunction<AddImageExtensionPoint>() { @Override public void run(AddImageExtensionPoint ext) { ext.failedToAddImage(inv, err); } }); dbf.remove(ivo); evt.setError(err); } bus.publish(evt); } }.start(); } @Override public String getId() { return bus.makeLocalServiceId(ImageConstant.SERVICE_ID); } private void populateExtensions() { for (ImageFactory f : pluginRgty.getExtensionList(ImageFactory.class)) { ImageFactory old = imageFactories.get(f.getType().toString()); if (old != null) { throw new CloudRuntimeException(String.format("duplicate ImageFactory[%s, %s] for type[%s]", f.getClass().getName(), old.getClass().getName(), f.getType())); } imageFactories.put(f.getType().toString(), f); } } @Override public boolean start() { populateExtensions(); installGlobalConfigUpdater(); return true; } private void installGlobalConfigUpdater() { ImageGlobalConfig.DELETION_POLICY.installUpdateExtension(new GlobalConfigUpdateExtensionPoint() { @Override public void updateGlobalConfig(GlobalConfig oldConfig, GlobalConfig newConfig) { startExpungeTask(); } }); ImageGlobalConfig.EXPUNGE_INTERVAL.installUpdateExtension(new GlobalConfigUpdateExtensionPoint() { @Override public void updateGlobalConfig(GlobalConfig oldConfig, GlobalConfig newConfig) { startExpungeTask(); } }); ImageGlobalConfig.EXPUNGE_PERIOD.installUpdateExtension(new GlobalConfigUpdateExtensionPoint() { @Override public void updateGlobalConfig(GlobalConfig oldConfig, GlobalConfig newConfig) { startExpungeTask(); } }); } private void startExpungeTask() { if (expungeTask != null) { expungeTask.cancel(true); } expungeTask = thdf.submitCancelablePeriodicTask(new CancelablePeriodicTask() { private List<Tuple> getDeletedImageManagedByUs() { int qun = 1000; SimpleQuery q = dbf.createQuery(ImageBackupStorageRefVO.class); q.add(ImageBackupStorageRefVO_.status, Op.EQ, ImageStatus.Deleted); long amount = q.count(); int times = (int) (amount / qun) + (amount % qun != 0 ? 1 : 0); int start = 0; List<Tuple> ret = new ArrayList<Tuple>(); for (int i = 0; i < times; i++) { q = dbf.createQuery(ImageBackupStorageRefVO.class); q.select(ImageBackupStorageRefVO_.imageUuid, ImageBackupStorageRefVO_.lastOpDate, ImageBackupStorageRefVO_.backupStorageUuid); q.add(ImageBackupStorageRefVO_.status, Op.EQ, ImageStatus.Deleted); q.setLimit(qun); q.setStart(start); List<Tuple> ts = q.listTuple(); start += qun; for (Tuple t : ts) { String imageUuid = t.get(0, String.class); if (!destMaker.isManagedByUs(imageUuid)) { continue; } ret.add(t); } } return ret; } @Override public boolean run() { final List<Tuple> images = getDeletedImageManagedByUs(); if (images.isEmpty()) { logger.debug("[Image Expunge Task]: no images to expunge"); return false; } for (Tuple t : images) { String imageUuid = t.get(0, String.class); Timestamp date = t.get(1, Timestamp.class); String bsUuid = t.get(2, String.class); final Timestamp current = dbf.getCurrentSqlTime(); if (current.getTime() >= date.getTime() + TimeUnit.SECONDS.toMillis(ImageGlobalConfig.EXPUNGE_PERIOD.value(Long.class))) { ImageDeletionPolicy deletionPolicy = deletionPolicyMgr.getDeletionPolicy(imageUuid); if (ImageDeletionPolicy.Never == deletionPolicy) { logger.debug(String.format("the deletion policy[Never] is set for the image[uuid:%s] on the backup storage[uuid:%s]," + "don't expunge it", images, bsUuid)); continue; } ExpungeImageMsg msg = new ExpungeImageMsg(); msg.setImageUuid(imageUuid); msg.setBackupStorageUuid(bsUuid); bus.makeTargetServiceIdByResourceUuid(msg, ImageConstant.SERVICE_ID, imageUuid); bus.send(msg, new CloudBusCallBack(null) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { //TODO logger.warn(String.format("failed to expunge the image[uuid:%s], %s", images, reply.getError())); } } }); } } return false; } @Override public TimeUnit getTimeUnit() { return TimeUnit.SECONDS; } @Override public long getInterval() { return ImageGlobalConfig.EXPUNGE_INTERVAL.value(Long.class); } @Override public String getName() { return "expunge-image"; } }); } @Override public boolean stop() { return true; } private ImageFactory getImageFacotry(ImageType type) { ImageFactory factory = imageFactories.get(type.toString()); if (factory == null) { throw new CloudRuntimeException(String.format("Unable to find ImageFactory with type[%s]", type)); } return factory; } @Override public void managementNodeReady() { startExpungeTask(); } @Override public List<Quota> reportQuota() { Quota.QuotaOperator checker = new Quota.QuotaOperator() { @Override public void checkQuota(APIMessage msg, Map<String, Quota.QuotaPair> pairs) { if (!new QuotaUtil().isAdminAccount(msg.getSession().getAccountUuid())) { if (msg instanceof APIAddImageMsg) { check((APIAddImageMsg) msg, pairs); } else if (msg instanceof APIRecoverImageMsg) { check((APIRecoverImageMsg) msg, pairs); } else if (msg instanceof APIChangeResourceOwnerMsg) { check((APIChangeResourceOwnerMsg) msg, pairs); } } else { if (msg instanceof APIChangeResourceOwnerMsg) { check((APIChangeResourceOwnerMsg) msg, pairs); } } } @Override public void checkQuota(NeedQuotaCheckMessage msg, Map<String, Quota.QuotaPair> pairs) { } @Override public List<Quota.QuotaUsage> getQuotaUsageByAccount(String accountUuid) { List<Quota.QuotaUsage> usages = new ArrayList<>(); ImageQuotaUtil.ImageQuota imageQuota = new ImageQuotaUtil().getUsed(accountUuid); Quota.QuotaUsage usage = new Quota.QuotaUsage(); usage.setName(ImageConstant.QUOTA_IMAGE_NUM); usage.setUsed(imageQuota.imageNum); usages.add(usage); usage = new Quota.QuotaUsage(); usage.setName(ImageConstant.QUOTA_IMAGE_SIZE); usage.setUsed(imageQuota.imageSize); usages.add(usage); return usages; } @Transactional(readOnly = true) private void check(APIChangeResourceOwnerMsg msg, Map<String, Quota.QuotaPair> pairs) { String currentAccountUuid = msg.getSession().getAccountUuid(); String resourceTargetOwnerAccountUuid = msg.getAccountUuid(); if (new QuotaUtil().isAdminAccount(resourceTargetOwnerAccountUuid)) { return; } SimpleQuery<AccountResourceRefVO> q = dbf.createQuery(AccountResourceRefVO.class); q.add(AccountResourceRefVO_.resourceUuid, Op.EQ, msg.getResourceUuid()); AccountResourceRefVO accResRefVO = q.find(); if (accResRefVO.getResourceType().equals(ImageVO.class.getSimpleName())) { long imageNumQuota = pairs.get(ImageConstant.QUOTA_IMAGE_NUM).getValue(); long imageSizeQuota = pairs.get(ImageConstant.QUOTA_IMAGE_SIZE).getValue(); long imageNumUsed = new ImageQuotaUtil().getUsedImageNum(resourceTargetOwnerAccountUuid); long imageSizeUsed = new ImageQuotaUtil().getUsedImageSize(resourceTargetOwnerAccountUuid); ImageVO image = dbf.getEntityManager().find(ImageVO.class, msg.getResourceUuid()); long imageNumAsked = 1; long imageSizeAsked = image.getSize(); QuotaUtil.QuotaCompareInfo quotaCompareInfo; { quotaCompareInfo = new QuotaUtil.QuotaCompareInfo(); quotaCompareInfo.currentAccountUuid = currentAccountUuid; quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid; quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_NUM; quotaCompareInfo.quotaValue = imageNumQuota; quotaCompareInfo.currentUsed = imageNumUsed; quotaCompareInfo.request = imageNumAsked; new QuotaUtil().CheckQuota(quotaCompareInfo); } { quotaCompareInfo = new QuotaUtil.QuotaCompareInfo(); quotaCompareInfo.currentAccountUuid = currentAccountUuid; quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid; quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_SIZE; quotaCompareInfo.quotaValue = imageSizeQuota; quotaCompareInfo.currentUsed = imageSizeUsed; quotaCompareInfo.request = imageSizeAsked; new QuotaUtil().CheckQuota(quotaCompareInfo); } } } @Transactional(readOnly = true) private void check(APIRecoverImageMsg msg, Map<String, Quota.QuotaPair> pairs) { String currentAccountUuid = msg.getSession().getAccountUuid(); String resourceTargetOwnerAccountUuid = new QuotaUtil().getResourceOwnerAccountUuid(msg.getImageUuid()); long imageNumQuota = pairs.get(ImageConstant.QUOTA_IMAGE_NUM).getValue(); long imageSizeQuota = pairs.get(ImageConstant.QUOTA_IMAGE_SIZE).getValue(); long imageNumUsed = new ImageQuotaUtil().getUsedImageNum(resourceTargetOwnerAccountUuid); long imageSizeUsed = new ImageQuotaUtil().getUsedImageSize(resourceTargetOwnerAccountUuid); ImageVO image = dbf.getEntityManager().find(ImageVO.class, msg.getImageUuid()); long imageNumAsked = 1; long imageSizeAsked = image.getSize(); QuotaUtil.QuotaCompareInfo quotaCompareInfo; { quotaCompareInfo = new QuotaUtil.QuotaCompareInfo(); quotaCompareInfo.currentAccountUuid = currentAccountUuid; quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid; quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_NUM; quotaCompareInfo.quotaValue = imageNumQuota; quotaCompareInfo.currentUsed = imageNumUsed; quotaCompareInfo.request = imageNumAsked; new QuotaUtil().CheckQuota(quotaCompareInfo); } { quotaCompareInfo = new QuotaUtil.QuotaCompareInfo(); quotaCompareInfo.currentAccountUuid = currentAccountUuid; quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid; quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_SIZE; quotaCompareInfo.quotaValue = imageSizeQuota; quotaCompareInfo.currentUsed = imageSizeUsed; quotaCompareInfo.request = imageSizeAsked; new QuotaUtil().CheckQuota(quotaCompareInfo); } } @Transactional(readOnly = true) private void check(APIAddImageMsg msg, Map<String, Quota.QuotaPair> pairs) { String currentAccountUuid = msg.getSession().getAccountUuid(); String resourceTargetOwnerAccountUuid = msg.getSession().getAccountUuid(); long imageNumQuota = pairs.get(ImageConstant.QUOTA_IMAGE_NUM).getValue(); long imageNumUsed = new ImageQuotaUtil().getUsedImageNum(resourceTargetOwnerAccountUuid); long imageNumAsked = 1; QuotaUtil.QuotaCompareInfo quotaCompareInfo; { quotaCompareInfo = new QuotaUtil.QuotaCompareInfo(); quotaCompareInfo.currentAccountUuid = currentAccountUuid; quotaCompareInfo.resourceTargetOwnerAccountUuid = resourceTargetOwnerAccountUuid; quotaCompareInfo.quotaName = ImageConstant.QUOTA_IMAGE_NUM; quotaCompareInfo.quotaValue = imageNumQuota; quotaCompareInfo.currentUsed = imageNumUsed; quotaCompareInfo.request = imageNumAsked; new QuotaUtil().CheckQuota(quotaCompareInfo); } new ImageQuotaUtil().checkImageSizeQuotaUseHttpHead(msg, pairs); } }; Quota quota = new Quota(); quota.setOperator(checker); quota.addMessageNeedValidation(APIAddImageMsg.class); quota.addMessageNeedValidation(APIRecoverImageMsg.class); quota.addMessageNeedValidation(APIChangeResourceOwnerMsg.class); Quota.QuotaPair p = new Quota.QuotaPair(); p.setName(ImageConstant.QUOTA_IMAGE_NUM); p.setValue(20); quota.addPair(p); p = new Quota.QuotaPair(); p.setName(ImageConstant.QUOTA_IMAGE_SIZE); p.setValue(SizeUnit.TERABYTE.toByte(10)); quota.addPair(p); return list(quota); } @Override @Transactional(readOnly = true) public void resourceOwnerPreChange(AccountResourceRefInventory ref, String newOwnerUuid) { } }
hhjuliet/zstack
image/src/main/java/org/zstack/image/ImageManagerImpl.java
Java
apache-2.0
66,374
/* * Created by Orchextra * * Copyright (C) 2016 Gigigo Mobile Services SL * * 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.gigigo.orchextra.device.bluetooth.beacons.ranging; import com.gigigo.orchextra.domain.abstractions.beacons.BackgroundBeaconsRangingTimeType; import com.gigigo.orchextra.domain.abstractions.beacons.RegionsProviderListener; import com.gigigo.orchextra.domain.model.triggers.params.AppRunningModeType; import java.util.List; import org.altbeacon.beacon.Region; public interface BeaconRangingScanner extends RegionsProviderListener { void initRangingScanForAllKnownRegions(AppRunningModeType appRunningModeType); void initRangingScanForDetectedRegion(List<Region> regions, BackgroundBeaconsRangingTimeType backgroundBeaconsRangingTimeType); void stopAllCurrentRangingScannedRegions(); void stopRangingScanForDetectedRegion(Region region); BackgroundBeaconsRangingTimeType getBackgroundBeaconsRangingTimeType(); boolean isRanging(); }
fSergio101/orchextra-android-sdk
orchextrasdk/src/main/java/com/gigigo/orchextra/device/bluetooth/beacons/ranging/BeaconRangingScanner.java
Java
apache-2.0
1,504
/* This file was generated by SableCC (http://www.sablecc.org/). */ package org.acre.lang.node; import java.util.*; import org.acre.lang.analysis.*; public final class ASingleParameterList extends PParameterList { private PType _type_; private TIdentifier _identifier_; public ASingleParameterList() { } public ASingleParameterList( PType _type_, TIdentifier _identifier_) { setType(_type_); setIdentifier(_identifier_); } public Object clone() { return new ASingleParameterList( (PType) cloneNode(_type_), (TIdentifier) cloneNode(_identifier_)); } public void apply(Switch sw) { ((Analysis) sw).caseASingleParameterList(this); } public PType getType() { return _type_; } public void setType(PType node) { if(_type_ != null) { _type_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } _type_ = node; } public TIdentifier getIdentifier() { return _identifier_; } public void setIdentifier(TIdentifier node) { if(_identifier_ != null) { _identifier_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } _identifier_ = node; } public String toString() { return "" + toString(_type_) + toString(_identifier_); } void removeChild(Node child) { if(_type_ == child) { _type_ = null; return; } if(_identifier_ == child) { _identifier_ = null; return; } } void replaceChild(Node oldChild, Node newChild) { if(_type_ == oldChild) { setType((PType) newChild); return; } if(_identifier_ == oldChild) { setIdentifier((TIdentifier) newChild); return; } } }
deepakalur/acre
src/main/org/acre/lang/node/ASingleParameterList.java
Java
apache-2.0
2,444
/** * Copyright 2010 The Apache Software Foundation * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.regionserver; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; import java.io.IOException; import java.util.List; import java.util.NavigableMap; import java.util.concurrent.CountDownLatch; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.catalog.MetaReader; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.executor.EventHandler.EventType; import org.apache.hadoop.hbase.executor.RegionTransitionData; import org.apache.hadoop.hbase.master.AssignmentManager; import org.apache.hadoop.hbase.master.AssignmentManager.RegionState; import org.apache.hadoop.hbase.master.HMaster; import org.apache.hadoop.hbase.master.handler.SplitRegionHandler; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.JVMClusterUtil.RegionServerThread; import org.apache.hadoop.hbase.util.Threads; import org.apache.hadoop.hbase.zookeeper.ZKAssign; import org.apache.hadoop.hbase.zookeeper.ZKUtil; import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.KeeperException.NodeExistsException; import org.apache.zookeeper.data.Stat; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; /** * Like {@link TestSplitTransaction} in that we're testing {@link SplitTransaction} * only the below tests are against a running cluster where {@link TestSplitTransaction} * is tests against a bare {@link HRegion}. */ @Category(LargeTests.class) public class TestSplitTransactionOnCluster { private static final Log LOG = LogFactory.getLog(TestSplitTransactionOnCluster.class); private HBaseAdmin admin = null; private MiniHBaseCluster cluster = null; private static final int NB_SERVERS = 2; private static CountDownLatch latch = new CountDownLatch(1); private static volatile boolean secondSplit = false; private static volatile boolean callRollBack = false; private static volatile boolean firstSplitCompleted = false; private static final HBaseTestingUtility TESTING_UTIL = new HBaseTestingUtility(); @BeforeClass public static void before() throws Exception { TESTING_UTIL.getConfiguration().setInt("hbase.balancer.period", 60000); // Needed because some tests have splits happening on RS that are killed // We don't want to wait 3min for the master to figure it out TESTING_UTIL.getConfiguration().setInt( "hbase.master.assignment.timeoutmonitor.timeout", 4000); TESTING_UTIL.startMiniCluster(NB_SERVERS); } @AfterClass public static void after() throws Exception { TESTING_UTIL.shutdownMiniCluster(); } @Before public void setup() throws IOException { TESTING_UTIL.ensureSomeNonStoppedRegionServersAvailable(NB_SERVERS); this.admin = new HBaseAdmin(TESTING_UTIL.getConfiguration()); this.cluster = TESTING_UTIL.getMiniHBaseCluster(); } private HRegionInfo getAndCheckSingleTableRegion(final List<HRegion> regions) { assertEquals(1, regions.size()); return regions.get(0).getRegionInfo(); } @Test(timeout = 2000000) public void testShouldFailSplitIfZNodeDoesNotExistDueToPrevRollBack() throws Exception { final byte[] tableName = Bytes .toBytes("testShouldFailSplitIfZNodeDoesNotExistDueToPrevRollBack"); HBaseAdmin admin = new HBaseAdmin(TESTING_UTIL.getConfiguration()); try { // Create table then get the single region for our new table. HTable t = createTableAndWait(tableName, Bytes.toBytes("cf")); final List<HRegion> regions = cluster.getRegions(tableName); HRegionInfo hri = getAndCheckSingleTableRegion(regions); int regionServerIndex = cluster.getServerWith(regions.get(0).getRegionName()); final HRegionServer regionServer = cluster.getRegionServer(regionServerIndex); insertData(tableName, admin, t); // Turn off balancer so it doesn't cut in and mess up our placements. this.admin.setBalancerRunning(false, false); // Turn off the meta scanner so it don't remove parent on us. cluster.getMaster().setCatalogJanitorEnabled(false); new Thread() { public void run() { SplitTransaction st = null; st = new MockedSplitTransaction(regions.get(0), Bytes.toBytes("row2")); try { st.prepare(); st.execute(regionServer, regionServer); } catch (IOException e) { } } }.start(); for (int i = 0; !callRollBack && i < 100; i++) { Thread.sleep(100); } assertTrue("Waited too long for rollback", callRollBack); SplitTransaction st = null; st = new MockedSplitTransaction(regions.get(0), Bytes.toBytes("row2")); try { secondSplit = true; st.prepare(); st.execute(regionServer, regionServer); } catch (IOException e) { LOG.debug("Rollback started :"+ e.getMessage()); st.rollback(regionServer, regionServer); } for (int i=0; !firstSplitCompleted && i<100; i++) { Thread.sleep(100); } assertTrue("fist split did not complete", firstSplitCompleted); NavigableMap<String, RegionState> rit = cluster.getMaster().getAssignmentManager() .getRegionsInTransition(); for (int i=0; rit.containsKey(hri.getTableNameAsString()) && i<100; i++) { Thread.sleep(100); } assertFalse("region still in transition", rit.containsKey(hri.getTableNameAsString())); List<HRegion> onlineRegions = regionServer.getOnlineRegions(tableName); // Region server side split is successful. assertEquals("The parent region should be splitted", 2, onlineRegions.size()); //Should be present in RIT List<HRegionInfo> regionsOfTable = cluster.getMaster().getAssignmentManager().getRegionsOfTable(tableName); // Master side should also reflect the same assertEquals("No of regions in master", 2, regionsOfTable.size()); } finally { admin.setBalancerRunning(true, false); secondSplit = false; firstSplitCompleted = false; callRollBack = false; cluster.getMaster().setCatalogJanitorEnabled(true); } if (admin.isTableAvailable(tableName) && admin.isTableEnabled(tableName)) { admin.disableTable(tableName); admin.deleteTable(tableName); admin.close(); } } /** * A test that intentionally has master fail the processing of the split message. * Tests that the regionserver split ephemeral node gets cleaned up if it * crashes and that after we process server shutdown, the daughters are up on * line. * @throws IOException * @throws InterruptedException * @throws NodeExistsException * @throws KeeperException */ @Test (timeout = 300000) public void testRSSplitEphemeralsDisappearButDaughtersAreOnlinedAfterShutdownHandling() throws IOException, InterruptedException, NodeExistsException, KeeperException { final byte [] tableName = Bytes.toBytes("ephemeral"); // Create table then get the single region for our new table. HTable t = createTableAndWait(tableName, HConstants.CATALOG_FAMILY); List<HRegion> regions = cluster.getRegions(tableName); HRegionInfo hri = getAndCheckSingleTableRegion(regions); int tableRegionIndex = ensureTableRegionNotOnSameServerAsMeta(admin, hri); // Turn off balancer so it doesn't cut in and mess up our placements. this.admin.setBalancerRunning(false, true); // Turn off the meta scanner so it don't remove parent on us. cluster.getMaster().setCatalogJanitorEnabled(false); try { // Add a bit of load up into the table so splittable. TESTING_UTIL.loadTable(t, HConstants.CATALOG_FAMILY); // Get region pre-split. HRegionServer server = cluster.getRegionServer(tableRegionIndex); printOutRegions(server, "Initial regions: "); int regionCount = server.getOnlineRegions().size(); // Now, before we split, set special flag in master, a flag that has // it FAIL the processing of split. SplitRegionHandler.TEST_SKIP = true; // Now try splitting and it should work. split(hri, server, regionCount); // Get daughters List<HRegion> daughters = checkAndGetDaughters(tableName); // Assert the ephemeral node is up in zk. String path = ZKAssign.getNodeName(t.getConnection().getZooKeeperWatcher(), hri.getEncodedName()); Stat stats = t.getConnection().getZooKeeperWatcher().getRecoverableZooKeeper().exists(path, false); LOG.info("EPHEMERAL NODE BEFORE SERVER ABORT, path=" + path + ", stats=" + stats); RegionTransitionData rtd = ZKAssign.getData(t.getConnection().getZooKeeperWatcher(), hri.getEncodedName()); // State could be SPLIT or SPLITTING. assertTrue(rtd.getEventType().equals(EventType.RS_ZK_REGION_SPLIT) || rtd.getEventType().equals(EventType.RS_ZK_REGION_SPLITTING)); // Now crash the server cluster.abortRegionServer(tableRegionIndex); waitUntilRegionServerDead(); awaitDaughters(tableName, daughters.size()); // Assert daughters are online. regions = cluster.getRegions(tableName); for (HRegion r: regions) { assertTrue(daughters.contains(r)); } // Finally assert that the ephemeral SPLIT znode was cleaned up. for (int i=0; i<100; i++) { // wait a bit (10s max) for the node to disappear stats = t.getConnection().getZooKeeperWatcher().getRecoverableZooKeeper().exists(path, false); if (stats == null) break; Thread.sleep(100); } LOG.info("EPHEMERAL NODE AFTER SERVER ABORT, path=" + path + ", stats=" + stats); assertTrue(stats == null); } finally { // Set this flag back. SplitRegionHandler.TEST_SKIP = false; admin.setBalancerRunning(true, false); cluster.getMaster().setCatalogJanitorEnabled(true); t.close(); } } @Test (timeout = 300000) public void testExistingZnodeBlocksSplitAndWeRollback() throws IOException, InterruptedException, NodeExistsException, KeeperException { final byte [] tableName = Bytes.toBytes("testExistingZnodeBlocksSplitAndWeRollback"); // Create table then get the single region for our new table. HTable t = createTableAndWait(tableName, HConstants.CATALOG_FAMILY); List<HRegion> regions = cluster.getRegions(tableName); HRegionInfo hri = getAndCheckSingleTableRegion(regions); int tableRegionIndex = ensureTableRegionNotOnSameServerAsMeta(admin, hri); // Turn off balancer so it doesn't cut in and mess up our placements. this.admin.setBalancerRunning(false, true); // Turn off the meta scanner so it don't remove parent on us. cluster.getMaster().setCatalogJanitorEnabled(false); try { // Add a bit of load up into the table so splittable. TESTING_UTIL.loadTable(t, HConstants.CATALOG_FAMILY); // Get region pre-split. HRegionServer server = cluster.getRegionServer(tableRegionIndex); printOutRegions(server, "Initial regions: "); int regionCount = server.getOnlineRegions().size(); // Insert into zk a blocking znode, a znode of same name as region // so it gets in way of our splitting. ZKAssign.createNodeClosing(t.getConnection().getZooKeeperWatcher(), hri, new ServerName("any.old.server", 1234, -1)); // Now try splitting.... should fail. And each should successfully // rollback. this.admin.split(hri.getRegionNameAsString()); this.admin.split(hri.getRegionNameAsString()); this.admin.split(hri.getRegionNameAsString()); // Wait around a while and assert count of regions remains constant. for (int i = 0; i < 10; i++) { Thread.sleep(100); assertEquals(regionCount, server.getOnlineRegions().size()); } // Now clear the zknode ZKAssign.deleteClosingNode(t.getConnection().getZooKeeperWatcher(), hri); // Now try splitting and it should work. split(hri, server, regionCount); // Get daughters checkAndGetDaughters(tableName); // OK, so split happened after we cleared the blocking node. } finally { admin.setBalancerRunning(true, false); cluster.getMaster().setCatalogJanitorEnabled(true); t.close(); } } /** * Messy test that simulates case where SplitTransactions fails to add one * of the daughters up into the .META. table before crash. We're testing * fact that the shutdown handler will fixup the missing daughter region * adding it back into .META. * @throws IOException * @throws InterruptedException */ @Test (timeout = 300000) public void testShutdownSimpleFixup() throws IOException, InterruptedException { final byte [] tableName = Bytes.toBytes("testShutdownSimpleFixup"); // Create table then get the single region for our new table. HTable t = createTableAndWait(tableName, HConstants.CATALOG_FAMILY); List<HRegion> regions = cluster.getRegions(tableName); HRegionInfo hri = getAndCheckSingleTableRegion(regions); int tableRegionIndex = ensureTableRegionNotOnSameServerAsMeta(admin, hri); // Turn off balancer so it doesn't cut in and mess up our placements. this.admin.setBalancerRunning(false, true); // Turn off the meta scanner so it don't remove parent on us. cluster.getMaster().setCatalogJanitorEnabled(false); try { // Add a bit of load up into the table so splittable. TESTING_UTIL.loadTable(t, HConstants.CATALOG_FAMILY); // Get region pre-split. HRegionServer server = cluster.getRegionServer(tableRegionIndex); printOutRegions(server, "Initial regions: "); int regionCount = server.getOnlineRegions().size(); // Now split. split(hri, server, regionCount); // Get daughters List<HRegion> daughters = checkAndGetDaughters(tableName); // Remove one of the daughters from .META. to simulate failed insert of // daughter region up into .META. removeDaughterFromMeta(daughters.get(0).getRegionName()); // Now crash the server cluster.abortRegionServer(tableRegionIndex); waitUntilRegionServerDead(); awaitDaughters(tableName, daughters.size()); // Assert daughters are online. regions = cluster.getRegions(tableName); for (HRegion r: regions) { assertTrue(daughters.contains(r)); } } finally { admin.setBalancerRunning(true, false); cluster.getMaster().setCatalogJanitorEnabled(true); t.close(); } } /** * Test that if daughter split on us, we won't do the shutdown handler fixup * just because we can't find the immediate daughter of an offlined parent. * @throws IOException * @throws InterruptedException */ @Test (timeout=300000) public void testShutdownFixupWhenDaughterHasSplit() throws IOException, InterruptedException { final byte [] tableName = Bytes.toBytes("testShutdownFixupWhenDaughterHasSplit"); // Create table then get the single region for our new table. HTable t = createTableAndWait(tableName, HConstants.CATALOG_FAMILY); List<HRegion> regions = cluster.getRegions(tableName); HRegionInfo hri = getAndCheckSingleTableRegion(regions); int tableRegionIndex = ensureTableRegionNotOnSameServerAsMeta(admin, hri); // Turn off balancer so it doesn't cut in and mess up our placements. this.admin.setBalancerRunning(false, true); // Turn off the meta scanner so it don't remove parent on us. cluster.getMaster().setCatalogJanitorEnabled(false); try { // Add a bit of load up into the table so splittable. TESTING_UTIL.loadTable(t, HConstants.CATALOG_FAMILY); // Get region pre-split. HRegionServer server = cluster.getRegionServer(tableRegionIndex); printOutRegions(server, "Initial regions: "); int regionCount = server.getOnlineRegions().size(); // Now split. split(hri, server, regionCount); // Get daughters List<HRegion> daughters = checkAndGetDaughters(tableName); // Now split one of the daughters. regionCount = server.getOnlineRegions().size(); HRegionInfo daughter = daughters.get(0).getRegionInfo(); // Compact first to ensure we have cleaned up references -- else the split // will fail. this.admin.compact(daughter.getRegionName()); daughters = cluster.getRegions(tableName); HRegion daughterRegion = null; for (HRegion r: daughters) { if (r.getRegionInfo().equals(daughter)) daughterRegion = r; } assertTrue(daughterRegion != null); for (int i=0; i<100; i++) { if (!daughterRegion.hasReferences()) break; Threads.sleep(100); } assertFalse("Waiting for refereces to be compacted", daughterRegion.hasReferences()); split(daughter, server, regionCount); // Get list of daughters daughters = cluster.getRegions(tableName); // Now crash the server cluster.abortRegionServer(tableRegionIndex); waitUntilRegionServerDead(); awaitDaughters(tableName, daughters.size()); // Assert daughters are online and ONLY the original daughters -- that // fixup didn't insert one during server shutdown recover. regions = cluster.getRegions(tableName); assertEquals(daughters.size(), regions.size()); for (HRegion r: regions) { assertTrue(daughters.contains(r)); } } finally { admin.setBalancerRunning(true, false); cluster.getMaster().setCatalogJanitorEnabled(true); t.close(); } } /** * Verifies HBASE-5806. When splitting is partially done and the master goes down * when the SPLIT node is in either SPLIT or SPLITTING state. * * @throws IOException * @throws InterruptedException * @throws NodeExistsException * @throws KeeperException */ @Test(timeout = 300000) public void testMasterRestartWhenSplittingIsPartial() throws IOException, InterruptedException, NodeExistsException, KeeperException { final byte[] tableName = Bytes.toBytes("testMasterRestartWhenSplittingIsPartial"); // Create table then get the single region for our new table. HTable t = createTableAndWait(tableName, HConstants.CATALOG_FAMILY); List<HRegion> regions = cluster.getRegions(tableName); HRegionInfo hri = getAndCheckSingleTableRegion(regions); int tableRegionIndex = ensureTableRegionNotOnSameServerAsMeta(admin, hri); // Turn off the meta scanner so it don't remove parent on us. cluster.getMaster().setCatalogJanitorEnabled(false); // Turn off balancer so it doesn't cut in and mess up our placements. this.admin.setBalancerRunning(false, true); try { // Add a bit of load up into the table so splittable. TESTING_UTIL.loadTable(t, HConstants.CATALOG_FAMILY); // Get region pre-split. HRegionServer server = cluster.getRegionServer(tableRegionIndex); printOutRegions(server, "Initial regions: "); int regionCount = server.getOnlineRegions().size(); // Now, before we split, set special flag in master, a flag that has // it FAIL the processing of split. SplitRegionHandler.TEST_SKIP = true; // Now try splitting and it should work. split(hri, server, regionCount); // Get daughters checkAndGetDaughters(tableName); // Assert the ephemeral node is up in zk. String path = ZKAssign.getNodeName(t.getConnection() .getZooKeeperWatcher(), hri.getEncodedName()); Stat stats = t.getConnection().getZooKeeperWatcher() .getRecoverableZooKeeper().exists(path, false); LOG.info("EPHEMERAL NODE BEFORE SERVER ABORT, path=" + path + ", stats=" + stats); RegionTransitionData rtd = ZKAssign.getData(t.getConnection() .getZooKeeperWatcher(), hri.getEncodedName()); // State could be SPLIT or SPLITTING. assertTrue(rtd.getEventType().equals(EventType.RS_ZK_REGION_SPLIT) || rtd.getEventType().equals(EventType.RS_ZK_REGION_SPLITTING)); // abort and wait for new master. MockMasterWithoutCatalogJanitor master = abortAndWaitForMaster(); this.admin = new HBaseAdmin(TESTING_UTIL.getConfiguration()); // update the hri to be offlined and splitted. hri.setOffline(true); hri.setSplit(true); ServerName regionServerOfRegion = master.getAssignmentManager() .getRegionServerOfRegion(hri); assertTrue(regionServerOfRegion != null); } finally { // Set this flag back. SplitRegionHandler.TEST_SKIP = false; admin.setBalancerRunning(true, false); cluster.getMaster().setCatalogJanitorEnabled(true); t.close(); } } /** * Verifies HBASE-5806. Here the case is that splitting is completed but before the * CJ could remove the parent region the master is killed and restarted. * @throws IOException * @throws InterruptedException * @throws NodeExistsException * @throws KeeperException */ @Test (timeout = 300000) public void testMasterRestartAtRegionSplitPendingCatalogJanitor() throws IOException, InterruptedException, NodeExistsException, KeeperException { final byte[] tableName = Bytes.toBytes("testMasterRestartAtRegionSplitPendingCatalogJanitor"); // Create table then get the single region for our new table. this.admin = new HBaseAdmin(TESTING_UTIL.getConfiguration()); HTable t = createTableAndWait(tableName, HConstants.CATALOG_FAMILY); List<HRegion> regions = cluster.getRegions(tableName); HRegionInfo hri = getAndCheckSingleTableRegion(regions); int tableRegionIndex = ensureTableRegionNotOnSameServerAsMeta(admin, hri); // Turn off balancer so it doesn't cut in and mess up our placements. this.admin.setBalancerRunning(false, true); // Turn off the meta scanner so it don't remove parent on us. cluster.getMaster().setCatalogJanitorEnabled(false); try { // Add a bit of load up into the table so splittable. TESTING_UTIL.loadTable(t, HConstants.CATALOG_FAMILY); // Get region pre-split. HRegionServer server = cluster.getRegionServer(tableRegionIndex); printOutRegions(server, "Initial regions: "); int regionCount = server.getOnlineRegions().size(); split(hri, server, regionCount); // Get daughters checkAndGetDaughters(tableName); // Assert the ephemeral node is up in zk. String path = ZKAssign.getNodeName(t.getConnection() .getZooKeeperWatcher(), hri.getEncodedName()); Stat stats = t.getConnection().getZooKeeperWatcher() .getRecoverableZooKeeper().exists(path, false); LOG.info("EPHEMERAL NODE BEFORE SERVER ABORT, path=" + path + ", stats=" + stats); String node = ZKAssign.getNodeName(t.getConnection() .getZooKeeperWatcher(), hri.getEncodedName()); Stat stat = new Stat(); byte[] data = ZKUtil.getDataNoWatch(t.getConnection() .getZooKeeperWatcher(), node, stat); // ZKUtil.create for (int i=0; data != null && i<60; i++) { Thread.sleep(1000); data = ZKUtil.getDataNoWatch(t.getConnection().getZooKeeperWatcher(), node, stat); } assertNull("Waited too long for ZK node to be removed: "+node, data); MockMasterWithoutCatalogJanitor master = abortAndWaitForMaster(); this.admin = new HBaseAdmin(TESTING_UTIL.getConfiguration()); hri.setOffline(true); hri.setSplit(true); ServerName regionServerOfRegion = master.getAssignmentManager() .getRegionServerOfRegion(hri); assertTrue(regionServerOfRegion == null); } finally { // Set this flag back. SplitRegionHandler.TEST_SKIP = false; this.admin.setBalancerRunning(true, false); cluster.getMaster().setCatalogJanitorEnabled(true); t.close(); } } /** * While transitioning node from RS_ZK_REGION_SPLITTING to * RS_ZK_REGION_SPLITTING during region split,if zookeper went down split always * fails for the region. HBASE-6088 fixes this scenario. * This test case is to test the znode is deleted(if created) or not in roll back. * * @throws IOException * @throws InterruptedException * @throws KeeperException */ @Test public void testSplitBeforeSettingSplittingInZK() throws Exception, InterruptedException, KeeperException { testSplitBeforeSettingSplittingInZK(true); testSplitBeforeSettingSplittingInZK(false); } private void testSplitBeforeSettingSplittingInZK(boolean nodeCreated) throws Exception { final byte[] tableName = Bytes.toBytes("testSplitBeforeSettingSplittingInZK"); HBaseAdmin admin = new HBaseAdmin(TESTING_UTIL.getConfiguration()); // Create table then get the single region for our new table. HTableDescriptor htd = new HTableDescriptor(tableName); htd.addFamily(new HColumnDescriptor("cf")); admin.createTable(htd); List<HRegion> regions = null; for (int i=0; i<100; i++) { regions = cluster.getRegions(tableName); if (regions.size() > 0) break; Thread.sleep(100); } int regionServerIndex = cluster.getServerWith(regions.get(0).getRegionName()); HRegionServer regionServer = cluster.getRegionServer(regionServerIndex); SplitTransaction st = null; if (nodeCreated) { st = new MockedSplitTransaction(regions.get(0), null) { @Override int transitionNodeSplitting(ZooKeeperWatcher zkw, HRegionInfo parent, ServerName serverName, int version) throws KeeperException, IOException { throw new TransitionToSplittingFailedException(); } }; } else { st = new MockedSplitTransaction(regions.get(0), null) { @Override void createNodeSplitting(ZooKeeperWatcher zkw, HRegionInfo region, ServerName serverName) throws KeeperException, IOException { throw new SplittingNodeCreationFailedException (); } }; } String node = ZKAssign.getNodeName(regionServer.getZooKeeper(), regions.get(0) .getRegionInfo().getEncodedName()); // make sure the client is uptodate regionServer.getZooKeeper().sync(node); for (int i = 0; i < 100; i++) { // We expect the znode to be deleted by this time. Here the znode could be in OPENED state and the // master has not yet deleted the znode. if (ZKUtil.checkExists(regionServer.getZooKeeper(), node) != -1) { Thread.sleep(100); } } try { st.execute(regionServer, regionServer); } catch (IOException e) { // check for the specific instance in case the Split failed due to the existence of the znode in OPENED state. // This will at least make the test to fail; if (nodeCreated) { assertTrue("Should be instance of TransitionToSplittingFailedException", e instanceof TransitionToSplittingFailedException); } else { assertTrue("Should be instance of CreateSplittingNodeFailedException", e instanceof SplittingNodeCreationFailedException ); } node = ZKAssign.getNodeName(regionServer.getZooKeeper(), regions.get(0) .getRegionInfo().getEncodedName()); // make sure the client is uptodate regionServer.getZooKeeper().sync(node); if (nodeCreated) { assertFalse(ZKUtil.checkExists(regionServer.getZooKeeper(), node) == -1); } else { assertTrue(ZKUtil.checkExists(regionServer.getZooKeeper(), node) == -1); } assertTrue(st.rollback(regionServer, regionServer)); assertTrue(ZKUtil.checkExists(regionServer.getZooKeeper(), node) == -1); } if (admin.isTableAvailable(tableName) && admin.isTableEnabled(tableName)) { admin.disableTable(tableName); admin.deleteTable(tableName); } } @Test public void testShouldClearRITWhenNodeFoundInSplittingState() throws Exception { final byte[] tableName = Bytes.toBytes("testShouldClearRITWhenNodeFoundInSplittingState"); HBaseAdmin admin = new HBaseAdmin(TESTING_UTIL.getConfiguration()); // Create table then get the single region for our new table. HTableDescriptor htd = new HTableDescriptor(tableName); htd.addFamily(new HColumnDescriptor("cf")); admin.createTable(htd); for (int i = 0; cluster.getRegions(tableName).size() == 0 && i < 100; i++) { Thread.sleep(100); } assertTrue("Table not online", cluster.getRegions(tableName).size() != 0); HRegion region = cluster.getRegions(tableName).get(0); int regionServerIndex = cluster.getServerWith(region.getRegionName()); HRegionServer regionServer = cluster.getRegionServer(regionServerIndex); SplitTransaction st = null; st = new MockedSplitTransaction(region, null) { @Override void createSplitDir(FileSystem fs, Path splitdir) throws IOException { throw new IOException(""); } }; try { st.execute(regionServer, regionServer); } catch (IOException e) { String node = ZKAssign.getNodeName(regionServer.getZooKeeper(), region .getRegionInfo().getEncodedName()); assertFalse(ZKUtil.checkExists(regionServer.getZooKeeper(), node) == -1); AssignmentManager am = cluster.getMaster().getAssignmentManager(); for (int i = 0; !am.getRegionsInTransition().containsKey( region.getRegionInfo().getEncodedName()) && i < 100; i++) { Thread.sleep(200); } assertTrue("region is not in transition "+region, am.getRegionsInTransition().containsKey(region.getRegionInfo().getEncodedName())); RegionState regionState = am.getRegionsInTransition().get(region.getRegionInfo() .getEncodedName()); assertTrue(regionState.getState() == RegionState.State.SPLITTING); assertTrue(st.rollback(regionServer, regionServer)); assertTrue(ZKUtil.checkExists(regionServer.getZooKeeper(), node) == -1); for (int i=0; am.getRegionsInTransition().containsKey(region.getRegionInfo().getEncodedName()) && i<100; i++) { // Just in case the nodeDeleted event did not get executed. Thread.sleep(200); } assertFalse("region is still in transition", am.getRegionsInTransition().containsKey(region.getRegionInfo().getEncodedName())); } if (admin.isTableAvailable(tableName) && admin.isTableEnabled(tableName)) { admin.disableTable(tableName); admin.deleteTable(tableName); admin.close(); } } @Test(timeout = 60000) public void testTableExistsIfTheSpecifiedTableRegionIsSplitParent() throws Exception { ZooKeeperWatcher zkw = HBaseTestingUtility.getZooKeeperWatcher(TESTING_UTIL); final byte[] tableName = Bytes.toBytes("testTableExistsIfTheSpecifiedTableRegionIsSplitParent"); HRegionServer regionServer = null; List<HRegion> regions = null; HBaseAdmin admin = new HBaseAdmin(TESTING_UTIL.getConfiguration()); try { // Create table then get the single region for our new table. HTable t = createTableAndWait(tableName, Bytes.toBytes("cf")); regions = cluster.getRegions(tableName); int regionServerIndex = cluster.getServerWith(regions.get(0).getRegionName()); regionServer = cluster.getRegionServer(regionServerIndex); insertData(tableName, admin, t); // Turn off balancer so it doesn't cut in and mess up our placements. cluster.getMaster().setCatalogJanitorEnabled(false); boolean tableExists = MetaReader.tableExists(regionServer.getCatalogTracker(), Bytes.toString(tableName)); assertEquals("The specified table should present.", true, tableExists); SplitTransaction st = new SplitTransaction(regions.get(0), Bytes.toBytes("row2")); try { st.prepare(); st.createDaughters(regionServer, regionServer); } catch (IOException e) { } tableExists = MetaReader.tableExists(regionServer.getCatalogTracker(), Bytes.toString(tableName)); assertEquals("The specified table should present.", true, tableExists); } finally { if (regions != null) { String node = ZKAssign.getNodeName(zkw, regions.get(0).getRegionInfo() .getEncodedName()); ZKUtil.deleteNodeFailSilent(zkw, node); } cluster.getMaster().setCatalogJanitorEnabled(true); admin.close(); } } @Test(timeout = 180000) public void testSplitShouldNotThrowNPEEvenARegionHasEmptySplitFiles() throws Exception { Configuration conf = TESTING_UTIL.getConfiguration(); ZooKeeperWatcher zkw = HBaseTestingUtility.getZooKeeperWatcher(TESTING_UTIL); String userTableName = "testSplitShouldNotThrowNPEEvenARegionHasEmptySplitFiles"; HTableDescriptor htd = new HTableDescriptor(userTableName); HColumnDescriptor hcd = new HColumnDescriptor("col"); htd.addFamily(hcd); admin.createTable(htd); HTable table = new HTable(conf, userTableName); try { for (int i = 0; i <= 5; i++) { String row = "row" + i; Put p = new Put(row.getBytes()); String val = "Val" + i; p.add("col".getBytes(), "ql".getBytes(), val.getBytes()); table.put(p); admin.flush(userTableName); Delete d = new Delete(row.getBytes()); // Do a normal delete table.delete(d); admin.flush(userTableName); } admin.majorCompact(userTableName); List<HRegionInfo> regionsOfTable = TESTING_UTIL.getMiniHBaseCluster() .getMaster().getAssignmentManager() .getRegionsOfTable(userTableName.getBytes()); HRegionInfo hRegionInfo = regionsOfTable.get(0); Put p = new Put("row6".getBytes()); p.add("col".getBytes(), "ql".getBytes(), "val".getBytes()); table.put(p); p = new Put("row7".getBytes()); p.add("col".getBytes(), "ql".getBytes(), "val".getBytes()); table.put(p); p = new Put("row8".getBytes()); p.add("col".getBytes(), "ql".getBytes(), "val".getBytes()); table.put(p); admin.flush(userTableName); admin.split(hRegionInfo.getRegionName(), "row7".getBytes()); regionsOfTable = TESTING_UTIL.getMiniHBaseCluster().getMaster() .getAssignmentManager().getRegionsOfTable(userTableName.getBytes()); while (regionsOfTable.size() != 2) { Thread.sleep(2000); regionsOfTable = TESTING_UTIL.getMiniHBaseCluster().getMaster() .getAssignmentManager().getRegionsOfTable(userTableName.getBytes()); } assertEquals(2, regionsOfTable.size()); Scan s = new Scan(); ResultScanner scanner = table.getScanner(s); int mainTableCount = 0; for (Result rr = scanner.next(); rr != null; rr = scanner.next()) { mainTableCount++; } assertEquals(3, mainTableCount); } finally { table.close(); } } private void insertData(final byte[] tableName, HBaseAdmin admin, HTable t) throws IOException, InterruptedException { Put p = new Put(Bytes.toBytes("row1")); p.add(Bytes.toBytes("cf"), Bytes.toBytes("q1"), Bytes.toBytes("1")); t.put(p); p = new Put(Bytes.toBytes("row2")); p.add(Bytes.toBytes("cf"), Bytes.toBytes("q1"), Bytes.toBytes("2")); t.put(p); p = new Put(Bytes.toBytes("row3")); p.add(Bytes.toBytes("cf"), Bytes.toBytes("q1"), Bytes.toBytes("3")); t.put(p); p = new Put(Bytes.toBytes("row4")); p.add(Bytes.toBytes("cf"), Bytes.toBytes("q1"), Bytes.toBytes("4")); t.put(p); admin.flush(tableName); } public static class MockedSplitTransaction extends SplitTransaction { private HRegion currentRegion; public MockedSplitTransaction(HRegion r, byte[] splitrow) { super(r, splitrow); this.currentRegion = r; } @Override void transitionZKNode(Server server, RegionServerServices services, HRegion a, HRegion b) throws IOException { if (this.currentRegion.getRegionInfo().getTableNameAsString() .equals("testShouldFailSplitIfZNodeDoesNotExistDueToPrevRollBack")) { try { if (!secondSplit){ callRollBack = true; latch.await(); } } catch (InterruptedException e) { } } super.transitionZKNode(server, services, a, b); if (this.currentRegion.getRegionInfo().getTableNameAsString() .equals("testShouldFailSplitIfZNodeDoesNotExistDueToPrevRollBack")) { firstSplitCompleted = true; } } @Override public boolean rollback(Server server, RegionServerServices services) throws IOException { if (this.currentRegion.getRegionInfo().getTableNameAsString() .equals("testShouldFailSplitIfZNodeDoesNotExistDueToPrevRollBack")) { if(secondSplit){ super.rollback(server, services); latch.countDown(); return true; } } return super.rollback(server, services); } } private List<HRegion> checkAndGetDaughters(byte[] tableName) throws InterruptedException { List<HRegion> daughters = null; // try up to 10s for (int i=0; i<100; i++) { daughters = cluster.getRegions(tableName); if (daughters.size() >= 2) break; Thread.sleep(100); } assertTrue(daughters.size() >= 2); return daughters; } private MockMasterWithoutCatalogJanitor abortAndWaitForMaster() throws IOException, InterruptedException { cluster.abortMaster(0); cluster.waitOnMaster(0); cluster.getConfiguration().setClass(HConstants.MASTER_IMPL, MockMasterWithoutCatalogJanitor.class, HMaster.class); MockMasterWithoutCatalogJanitor master = null; master = (MockMasterWithoutCatalogJanitor) cluster.startMaster().getMaster(); cluster.waitForActiveAndReadyMaster(); return master; } private void split(final HRegionInfo hri, final HRegionServer server, final int regionCount) throws IOException, InterruptedException { this.admin.split(hri.getRegionNameAsString()); for (int i=0; server.getOnlineRegions().size() <= regionCount && i<100; i++) { LOG.debug("Waiting on region to split"); Thread.sleep(100); } assertFalse("Waited too long for split", server.getOnlineRegions().size() <= regionCount); } private void removeDaughterFromMeta(final byte [] regionName) throws IOException { HTable metaTable = new HTable(TESTING_UTIL.getConfiguration(), HConstants.META_TABLE_NAME); Delete d = new Delete(regionName); LOG.info("Deleted " + Bytes.toString(regionName)); metaTable.delete(d); } /** * Ensure single table region is not on same server as the single .META. table * region. * @param admin * @param hri * @return Index of the server hosting the single table region * @throws UnknownRegionException * @throws MasterNotRunningException * @throws ZooKeeperConnectionException * @throws InterruptedException */ private int ensureTableRegionNotOnSameServerAsMeta(final HBaseAdmin admin, final HRegionInfo hri) throws UnknownRegionException, MasterNotRunningException, ZooKeeperConnectionException, InterruptedException { MiniHBaseCluster cluster = TESTING_UTIL.getMiniHBaseCluster(); // Now make sure that the table region is not on same server as that hosting // .META. We don't want .META. replay polluting our test when we later crash // the table region serving server. int metaServerIndex = cluster.getServerWithMeta(); assertTrue(metaServerIndex != -1); HRegionServer metaRegionServer = cluster.getRegionServer(metaServerIndex); int tableRegionIndex = cluster.getServerWith(hri.getRegionName()); assertTrue(tableRegionIndex != -1); HRegionServer tableRegionServer = cluster.getRegionServer(tableRegionIndex); if (metaRegionServer.getServerName().equals(tableRegionServer.getServerName())) { HRegionServer hrs = getOtherRegionServer(cluster, metaRegionServer); assertNotNull(hrs); assertNotNull(hri); LOG. info("Moving " + hri.getRegionNameAsString() + " to " + hrs.getServerName() + "; metaServerIndex=" + metaServerIndex); for (int i = 0; cluster.getMaster().getAssignmentManager() .getRegionServerOfRegion(hri) == null && i < 100; i++) { Thread.sleep(10); } admin.move(hri.getEncodedNameAsBytes(), Bytes.toBytes(hrs.getServerName().toString())); } // Wait till table region is up on the server that is NOT carrying .META.. for (int i=0; i<100; i++) { tableRegionIndex = cluster.getServerWith(hri.getRegionName()); if (tableRegionIndex != -1 && tableRegionIndex != metaServerIndex) break; LOG.debug("Waiting on region move off the .META. server; current index " + tableRegionIndex + " and metaServerIndex=" + metaServerIndex); Thread.sleep(100); } assertTrue("Region not moved off .META. server", tableRegionIndex != -1 && tableRegionIndex != metaServerIndex); // Verify for sure table region is not on same server as .META. tableRegionIndex = cluster.getServerWith(hri.getRegionName()); assertTrue(tableRegionIndex != -1); assertNotSame(metaServerIndex, tableRegionIndex); return tableRegionIndex; } /** * Find regionserver other than the one passed. * Can't rely on indexes into list of regionservers since crashed servers * occupy an index. * @param cluster * @param notThisOne * @return A regionserver that is not <code>notThisOne</code> or null if none * found */ private HRegionServer getOtherRegionServer(final MiniHBaseCluster cluster, final HRegionServer notThisOne) { for (RegionServerThread rst: cluster.getRegionServerThreads()) { HRegionServer hrs = rst.getRegionServer(); if (hrs.getServerName().equals(notThisOne.getServerName())) continue; if (hrs.isStopping() || hrs.isStopped()) continue; return hrs; } return null; } private void printOutRegions(final HRegionServer hrs, final String prefix) throws IOException { List<HRegionInfo> regions = hrs.getOnlineRegions(); for (HRegionInfo region: regions) { LOG.info(prefix + region.getRegionNameAsString()); } } private void waitUntilRegionServerDead() throws InterruptedException { // Wait until the master processes the RS shutdown for (int i=0; cluster.getMaster().getClusterStatus(). getServers().size() == NB_SERVERS && i<100; i++) { LOG.info("Waiting on server to go down"); Thread.sleep(100); } assertFalse("Waited too long for RS to die", cluster.getMaster().getClusterStatus(). getServers().size() == NB_SERVERS); } private void awaitDaughters(byte[] tableName, int numDaughters) throws InterruptedException { // Wait till regions are back on line again. for (int i=0; cluster.getRegions(tableName).size() < numDaughters && i<60; i++) { LOG.info("Waiting for repair to happen"); Thread.sleep(1000); } if (cluster.getRegions(tableName).size() < numDaughters) { fail("Waiting too long for daughter regions"); } } private HTable createTableAndWait(byte[] tableName, byte[] cf) throws IOException, InterruptedException { HTable t = TESTING_UTIL.createTable(tableName, cf); for (int i = 0; cluster.getRegions(tableName).size() == 0 && i < 100; i++) { Thread.sleep(100); } assertTrue("Table not online: "+Bytes.toString(tableName), cluster.getRegions(tableName).size() != 0); return t; } @org.junit.Rule public org.apache.hadoop.hbase.ResourceCheckerJUnitRule cu = new org.apache.hadoop.hbase.ResourceCheckerJUnitRule(); public static class MockMasterWithoutCatalogJanitor extends HMaster { public MockMasterWithoutCatalogJanitor(Configuration conf) throws IOException, KeeperException, InterruptedException { super(conf); } protected void startCatalogJanitorChore() { LOG.debug("Customised master executed."); } } private static class TransitionToSplittingFailedException extends IOException { public TransitionToSplittingFailedException() { super(); } } private static class SplittingNodeCreationFailedException extends IOException { public SplittingNodeCreationFailedException () { super(); } } }
xiaofu/apache-hbase-0.94.10-read
src/test/java/org/apache/hadoop/hbase/regionserver/TestSplitTransactionOnCluster.java
Java
apache-2.0
46,178
package uk.dangrew.nuts.graphics.label; import javafx.collections.FXCollections; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.ComboBox; import javafx.scene.control.ListView; import javafx.scene.control.SelectionMode; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import uk.dangrew.kode.concept.Concept; import uk.dangrew.kode.javafx.style.JavaFxStyle; import uk.dangrew.kode.javafx.style.LabelBuilder; import uk.dangrew.nuts.label.Label; import uk.dangrew.nuts.label.Labelables; import uk.dangrew.nuts.store.Database; public class UiLabelConfigurationView extends GridPane { public UiLabelConfigurationView( Database database ) { UiLabelController controller = new UiLabelController( database ); JavaFxStyle styling = new JavaFxStyle(); styling.configureConstraintsForRowPercentages( this, 10, 90, 5 ); styling.configureConstraintsForColumnPercentages( this, 48, 4, 48 ); ListView< Concept > selectedLabelConcepts = new ListView<>( controller.selectedLabelConcepts() ); selectedLabelConcepts.getSelectionModel().setSelectionMode( SelectionMode.MULTIPLE ); styling.setStringConverter( selectedLabelConcepts, c -> c.properties().nameProperty().get() ); controller.monitorLabelSelection( selectedLabelConcepts.getSelectionModel().getSelectedItems() ); add( selectedLabelConcepts, 0, 1 ); ListView< Concept > selectedConceptTypes = new ListView<>( controller.selectedDatabaseConcepts() ); selectedConceptTypes.getSelectionModel().setSelectionMode( SelectionMode.MULTIPLE ); styling.setStringConverter( selectedConceptTypes, c -> c.properties().nameProperty().get() ); controller.monitorDatabaseSelection( selectedConceptTypes.getSelectionModel().getSelectedItems() ); add( selectedConceptTypes, 2, 1 ); ComboBox< Label > labelSelection = new ComboBox<>( database.labels().objectList() ); labelSelection.getSelectionModel().selectedItemProperty().addListener( ( s, o, n ) -> controller.selectLabel( n ) ); HBox labelSelectionContainer = new HBox( 10, new LabelBuilder().asBold().withText( "Label" ).build(), labelSelection ); labelSelectionContainer.setPadding( new Insets( 10 ) ); labelSelectionContainer.setAlignment( Pos.CENTER_LEFT ); add( labelSelectionContainer, 0, 0 ); ComboBox< Labelables > conceptSelection = new ComboBox<>( FXCollections.observableArrayList( Labelables.values() ) ); conceptSelection.getSelectionModel().selectedItemProperty().addListener( ( s, o, n ) -> controller.selectLabelable( n ) ); HBox conceptSelectionContainer = new HBox( 10, new LabelBuilder().asBold().withText( "Concepts" ).build(), conceptSelection ); conceptSelectionContainer.setPadding( new Insets( 10 ) ); conceptSelectionContainer.setAlignment( Pos.CENTER_LEFT ); add( conceptSelectionContainer, 2, 0 ); add( new UiLabelControls( controller ), 1, 1 ); add( new UiLabelCreationControls( controller ), 0, 2 ); }//End Constructor }//End Class
DanGrew/Nuts
nuts/src/uk/dangrew/nuts/graphics/label/UiLabelConfigurationView.java
Java
apache-2.0
3,232
package com.example.yqhok.coolweather.gson; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.SerializedName; /** * Created by yqhok on 2017/5/24. */ public class Forecast implements Parcelable { public String date; @SerializedName("tmp") public Temperature temperature; @SerializedName("cond") public More more; public class Temperature { public String max; public String min; } public class More { @SerializedName("txt_d") public String info; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(date); } public static final Parcelable.Creator<Forecast> CREATOR = new Parcelable.Creator<Forecast>() { @Override public Forecast createFromParcel(Parcel source) { Forecast forecast = new Forecast(); forecast.date = source.readString(); return forecast; } @Override public Forecast[] newArray(int size) { return new Forecast[size]; } }; }
yqhok1/coolweather
app/src/main/java/com/example/yqhok/coolweather/gson/Forecast.java
Java
apache-2.0
1,192
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.carbondata.core.carbon.metadata.schema.table.column; import java.util.ArrayList; import java.util.List; import org.apache.carbondata.core.carbon.metadata.encoder.Encoding; public class CarbonDimension extends CarbonColumn { /** * serialization version */ private static final long serialVersionUID = 3648269871656322681L; /** * List of child dimension for complex type */ private List<CarbonDimension> listOfChildDimensions; /** * in case of dictionary dimension this will store the ordinal * of the dimension in mdkey */ private int keyOrdinal; /** * column group column ordinal * for example if column is second column in the group * it will store 2 */ private int columnGroupOrdinal; /** * to store complex type dimension ordinal */ private int complexTypeOrdinal; public CarbonDimension(ColumnSchema columnSchema, int ordinal, int keyOrdinal, int columnGroupOrdinal, int complexTypeOrdinal) { this(columnSchema, ordinal, 0, keyOrdinal, columnGroupOrdinal, complexTypeOrdinal); } public CarbonDimension(ColumnSchema columnSchema, int ordinal, int schemaOrdinal, int keyOrdinal, int columnGroupOrdinal, int complexTypeOrdinal) { super(columnSchema, ordinal, schemaOrdinal); this.keyOrdinal = keyOrdinal; this.columnGroupOrdinal = columnGroupOrdinal; this.complexTypeOrdinal = complexTypeOrdinal; } /** * this method will initialize list based on number of child dimensions Count */ public void initializeChildDimensionsList(int childDimension) { listOfChildDimensions = new ArrayList<CarbonDimension>(childDimension); } /** * @return number of children for complex type */ public int getNumberOfChild() { return columnSchema.getNumberOfChild(); } /** * @return list of children dims for complex type */ public List<CarbonDimension> getListOfChildDimensions() { return listOfChildDimensions; } /** * @return return the number of child present in case of complex type */ public int numberOfChild() { return columnSchema.getNumberOfChild(); } public boolean hasEncoding(Encoding encoding) { return columnSchema.getEncodingList().contains(encoding); } /** * @return the keyOrdinal */ public int getKeyOrdinal() { return keyOrdinal; } /** * @return the columnGroupOrdinal */ public int getColumnGroupOrdinal() { return columnGroupOrdinal; } /** * @return the complexTypeOrdinal */ public int getComplexTypeOrdinal() { return complexTypeOrdinal; } public void setComplexTypeOridnal(int complexTypeOrdinal) { this.complexTypeOrdinal = complexTypeOrdinal; } /** * to generate the hash code for this class */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((columnSchema == null) ? 0 : columnSchema.hashCode()); return result; } /** * to check whether to dimension are equal or not */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof CarbonDimension)) { return false; } CarbonDimension other = (CarbonDimension) obj; if (columnSchema == null) { if (other.columnSchema != null) { return false; } } else if (!columnSchema.equals(other.columnSchema)) { return false; } return true; } }
ashokblend/incubator-carbondata
core/src/main/java/org/apache/carbondata/core/carbon/metadata/schema/table/column/CarbonDimension.java
Java
apache-2.0
4,325
/* * Copyright (C) 2004-2015 Volker Bergmann ([email protected]). * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.databene.commons.converter; import org.databene.commons.Converter; import org.databene.commons.ThreadAware; /** * Parent class for {@link Converter}s that hold a reference to another converter instance. * Created: 26.02.2010 17:55:21 * @param <S> the type to convert from * @param <T> the type to convert to * @since 0.5.0 * @author Volker Bergmann */ public abstract class ConverterWrapper<S, T> implements ThreadAware, Cloneable { protected Converter<S, T> realConverter; protected ConverterWrapper(Converter<S, T> realConverter) { this.realConverter = realConverter; } @Override public boolean isParallelizable() { return realConverter.isParallelizable(); } @Override public boolean isThreadSafe() { return realConverter.isParallelizable(); } @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } }
aravindc/databenecommons
src/main/java/org/databene/commons/converter/ConverterWrapper.java
Java
apache-2.0
1,711
package com.tenode.baleen.extras.readers; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.uima.UimaContext; import org.apache.uima.fit.descriptor.ExternalResource; import org.apache.uima.jcas.JCas; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import uk.gov.dstl.baleen.exceptions.BaleenException; /** * A collection reader which loads SGM files from the Reuters21578 archive. * * Available for download at http://www.daviddlewis.com/resources/testcollections/reuters21578/ * * Extract the data (use 'tar xvf reuters21579.tar.gz' or 7zip on Windows). */ public class ReuterReader extends AbstractStreamCollectionReader<String> { public ReuterReader() { // Do nothing } /** * Location of the directory containing the sgm files. * * @baleen.resource String */ public static final String KEY_PATH = "path"; @ExternalResource(key = KEY_PATH, mandatory = false) private String sgmPath; public void setSgmPath(final String sgmPath) { this.sgmPath = sgmPath; } @Override protected Stream<String> initializeStream(UimaContext context) throws BaleenException { final File[] files = new File(sgmPath) .listFiles(f -> f.getName().endsWith(".sgm") && f.isFile()); DocumentBuilder documentBuilder; try { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); documentBuilder = factory.newDocumentBuilder(); } catch (final Exception e) { throw new BaleenException(e); } return Arrays.stream(files) .flatMap(sgmlFile -> { try { final byte[] bytes = Files.readAllBytes(sgmlFile.toPath()); final String sgml = new String(bytes, "UTF-8"); // Remove the <!DOCTYPE lewis SYSTEM "lewis.dtd"> // Then add a root element String xml = "<root>" + sgml.substring("<!DOCTYPE lewis SYSTEM \"lewis.dtd\">".length()) + "</root>"; // Remove the xml = xml.replaceAll("&#\\d+;", ""); final ByteArrayInputStream input = new ByteArrayInputStream(xml.getBytes("UTF-8")); final Document doc = documentBuilder.parse(input); final NodeList reutersDocument = doc.getElementsByTagName("REUTERS"); return nodeListToElements(reutersDocument); } catch (final Exception e) { getMonitor().warn("Unable to process SGML file {}", sgmlFile.getAbsolutePath(), e); } return Stream.<Element> empty(); }).flatMap(e -> { return nodeListToText(e.getElementsByTagName("BODY")); }).filter(s -> { return !s.isEmpty(); }); } private Stream<String> nodeListToText(final NodeList list) { final List<String> elements = new ArrayList<>(list.getLength()); for (int i = 0; i < list.getLength(); i++) { final Node n = list.item(i); String text = n.getTextContent(); text = text.replaceAll("Reuter?\\s*$", ""); elements.add(text.trim()); } return elements.stream(); } private Stream<Element> nodeListToElements(final NodeList list) { final List<Element> elements = new ArrayList<>(list.getLength()); for (int i = 0; i < list.getLength(); i++) { final Node n = list.item(i); if (n.getNodeType() == Element.ELEMENT_NODE) { elements.add((Element) n); } } return elements.stream(); } @Override protected void apply(String text, JCas jCas) { jCas.setDocumentLanguage("en"); jCas.setDocumentText(text); } @Override protected void doClose() throws IOException { // Do nothing } }
tenode/baleen-extras
baleen-extras-readers/src/main/java/com/tenode/baleen/extras/readers/ReuterReader.java
Java
apache-2.0
3,870
package com.cebedo.pmsys.validator; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import org.springframework.web.multipart.MultipartFile; import com.cebedo.pmsys.bean.EstimateComputationInput; import com.cebedo.pmsys.helper.ValidationHelper; @Component public class EstimateInputValidator implements Validator { private ValidationHelper validationHelper = new ValidationHelper(); @Override public boolean supports(Class<?> clazz) { return EstimateComputationInput.class.isAssignableFrom(clazz); } @Override public void validate(Object target, Errors errors) { if (errors.hasErrors()) { this.validationHelper.rejectMissingRequiredFields(errors); return; } EstimateComputationInput targetObj = (EstimateComputationInput) target; MultipartFile file = targetObj.getEstimationFile(); String name = targetObj.getName(); String remarks = targetObj.getRemarks(); // Name is not blank. if (this.validationHelper.stringIsBlank(name)) { this.validationHelper.rejectInvalidProperty(errors, "name"); } // Name length = 32 if (this.validationHelper.stringLengthIsGreaterThanMax(name, 32)) { this.validationHelper.rejectGreaterThanMaxLength(errors, "name", 32); } // Remarks length = 255 if (this.validationHelper.stringLengthIsGreaterThanMax(remarks, 255)) { this.validationHelper.rejectGreaterThanMaxLength(errors, "remarks", 255); } // If the file is XLSX. if (this.validationHelper.fileIsExcelXLSX(file)) { this.validationHelper.rejectXLSXFile(errors); } // If file is null, or file is empty. // Handle case when other file types are uploaded. // Filter only Excel files: "application/vnd.ms-excel" else if (this.validationHelper.fileIsNullOrEmpty(file) || this.validationHelper.fileIsNotExcelXLS(file)) { this.validationHelper.rejectInvalidProperty(errors, "Excel (*.xls) file"); } } }
VicCebedo/PracticeRepo
mod-webapp-codebase/src/main/java/com/cebedo/pmsys/validator/EstimateInputValidator.java
Java
apache-2.0
1,971
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.codecommit.model; import javax.annotation.Generated; /** * <p> * You cannot modify or delete this comment. Only comment authors can modify or delete their comments. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CommentNotCreatedByCallerException extends com.amazonaws.services.codecommit.model.AWSCodeCommitException { private static final long serialVersionUID = 1L; /** * Constructs a new CommentNotCreatedByCallerException with the specified error message. * * @param message * Describes the error encountered. */ public CommentNotCreatedByCallerException(String message) { super(message); } }
jentfoo/aws-sdk-java
aws-java-sdk-codecommit/src/main/java/com/amazonaws/services/codecommit/model/CommentNotCreatedByCallerException.java
Java
apache-2.0
1,306
/** * Exercise 16 */ package com.ciaoshen.thinkinjava.chapter12; public class Exercise16 { public static class Shape { Shape(int i) { System.out.println("Shape constructor"); } void dispose() { System.out.println("Shape dispose"); } } public static class Circle extends Shape { Circle(int i) { super(i); System.out.println("Drawing Circle"); } void dispose() { System.out.println("Erasing Circle"); super.dispose(); } } public static class Triangle extends Shape { Triangle(int i) { super(i); System.out.println("Drawing Triangle"); } void dispose() { System.out.println("Erasing Triangle"); super.dispose(); } } public static class Line extends Shape { private int start, end; Line(int start, int end) { super(start); this.start = start; this.end = end; System.out.println("Drawing Line: " + start + ", " + end); } void dispose() { System.out.println("Erasing Line: " + start + ", " + end); super.dispose(); } } public static class CADSystem extends Shape { private Circle c; private Triangle t; private Line[] lines = new Line[3]; public CADSystem(int i) { super(i + 1); for(int j = 0; j < lines.length; j++) { lines[j] = new Line(j, j*j); } c = new Circle(1); t = new Triangle(1); System.out.println("Combined constructor"); } public void dispose() { System.out.println("CADSystem.dispose()"); // The order of cleanup is the reverse // of the order of initialization: t.dispose(); c.dispose(); for(int i = lines.length - 1; i >= 0; i--) { lines[i].dispose(); } super.dispose(); } } public static void main(String[] args) { Exercise16.CADSystem x = new Exercise16.CADSystem(47); try { // Code and exception handling... return; } finally { x.dispose(); } } }
helloShen/thinkinginjava
chapter12/Exercise16.java
Java
apache-2.0
2,323
package org.onetwo.common.spring.utils; import java.util.Enumeration; import java.util.NoSuchElementException; import java.util.Properties; import org.onetwo.common.log.JFishLoggerFactory; import org.onetwo.common.spring.utils.ConfigableBeanMapper.BeanAccessors; import org.onetwo.common.utils.StringUtils; import org.slf4j.Logger; import org.springframework.beans.ConfigurablePropertyAccessor; public class BeanPropertiesMapper { public static BeanPropertiesMapper props(Properties config, String prefix, boolean ignoreFoundProperty){ return new BeanPropertiesMapper(config, prefix, ignoreFoundProperty); } public static BeanPropertiesMapper ignoreNotFoundProperty(Properties config){ return new BeanPropertiesMapper(config, null, true); } private final Logger logger = JFishLoggerFactory.getLogger(this.getClass()); final private Properties config; final private String prefix; private boolean ignoreNotFoundProperty = false; private BeanAccessors beanAccessors = BeanAccessors.PROPERTY; private boolean ignoreBlankString; public BeanPropertiesMapper(Properties config, String prefix) { this(config, prefix, false); } public BeanPropertiesMapper(Properties config, String prefix, boolean ignoreFoundProperty) { super(); this.config = config; this.prefix = prefix; this.ignoreNotFoundProperty = ignoreFoundProperty; } public BeanPropertiesMapper ignoreBlankString() { this.ignoreBlankString = true; return this; } public void setIgnoreBlankString(boolean ignoreBlankString) { this.ignoreBlankString = ignoreBlankString; } public void setBeanAccessors(BeanAccessors beanAccessors) { this.beanAccessors = beanAccessors; } public BeanPropertiesMapper fieldAccessors() { this.beanAccessors = BeanAccessors.FIELD; return this; } public void mapToObject(Object obj) { if(config==null || config.isEmpty()){ return ; } boolean hasPrefix = StringUtils.isNotBlank(prefix); ConfigurablePropertyAccessor bw = beanAccessors.createAccessor(obj); Enumeration<?> names = config.propertyNames(); while(names.hasMoreElements()){ String propertyName = names.nextElement().toString(); String value = config.getProperty(propertyName); if(value==null){ continue; } if(StringUtils.isBlank(value) && ignoreBlankString){ continue; } if(hasPrefix){ if(propertyName.startsWith(prefix)){ propertyName = propertyName.substring(prefix.length()); setPropertyValue(obj, bw, propertyName, value); } }else{ setPropertyValue(obj, bw, propertyName, value); } } } protected void setPropertyValue(Object obj, ConfigurablePropertyAccessor bw, String propertyName, Object value){ if(!bw.isWritableProperty(propertyName)){ if(!ignoreNotFoundProperty){ throw new NoSuchElementException("no setter found for property: " + propertyName+", target: " + obj); } logger.debug("ignore property: {}={} ", propertyName, value); return ; } bw.setPropertyValue(propertyName, value); if(logger.isDebugEnabled()){ logger.debug("set property: {}={} ", propertyName, value); } } }
wayshall/onetwo
core/modules/spring/src/main/java/org/onetwo/common/spring/utils/BeanPropertiesMapper.java
Java
apache-2.0
3,111
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.db.rows; import java.util.Comparator; import java.util.Iterator; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.db.*; import org.apache.cassandra.db.filter.ColumnFilter; /** * An iterator that merges a source of rows with the range tombstone and partition level deletion of a give partition. * <p> * This is used by our {@code Partition} implementations to produce a {@code UnfilteredRowIterator} by merging the rows * and deletion infos that are kept separate. This has also 2 additional role: * 1) this make sure the row returned only includes the columns selected for the resulting iterator. * 2) this (optionally) remove any data that can be shadowed (see commet on 'removeShadowedData' below for more details) */ public class RowAndDeletionMergeIterator extends AbstractUnfilteredRowIterator { // For some of our Partition implementation, we can't guarantee that the deletion information (partition level // deletion and range tombstones) don't shadow data in the rows. If that is the case, this class also take // cares of skipping such shadowed data (since it is the contract of an UnfilteredRowIterator that it doesn't // shadow its own data). Sometimes however, we know this can't happen, in which case we can skip that step. private final boolean removeShadowedData; private final Comparator<Clusterable> comparator; private final ColumnFilter selection; private final Iterator<Row> rows; private Row nextRow; private final Iterator<RangeTombstone> ranges; private RangeTombstone nextRange; // The currently open tombstone. Note that unless this is null, there is no point in checking nextRange. private RangeTombstone openRange; public RowAndDeletionMergeIterator(CFMetaData metadata, DecoratedKey partitionKey, DeletionTime partitionLevelDeletion, ColumnFilter selection, Row staticRow, boolean isReversed, EncodingStats stats, Iterator<Row> rows, Iterator<RangeTombstone> ranges, boolean removeShadowedData) { super(metadata, partitionKey, partitionLevelDeletion, selection.fetchedColumns(), staticRow, isReversed, stats); this.comparator = isReversed ? metadata.comparator.reversed() : metadata.comparator; this.selection = selection; this.removeShadowedData = removeShadowedData; this.rows = rows; this.ranges = ranges; } private Unfiltered computeNextInternal() { while (true) { updateNextRow(); if (nextRow == null) { if (openRange != null) return closeOpenedRange(); updateNextRange(); return nextRange == null ? endOfData() : openRange(); } // We have a next row if (openRange == null) { // We have no currently open tombstone range. So check if we have a next range and if it sorts before this row. // If it does, the opening of that range should go first. Otherwise, the row goes first. updateNextRange(); if (nextRange != null && comparator.compare(openBound(nextRange), nextRow.clustering()) < 0) return openRange(); Row row = consumeNextRow(); // it's possible for the row to be fully shadowed by the current range tombstone if (row != null) return row; } else { // We have both a next row and a currently opened tombstone. Check which goes first between the range closing and the row. if (comparator.compare(closeBound(openRange), nextRow.clustering()) < 0) return closeOpenedRange(); Row row = consumeNextRow(); if (row != null) return row; } } } /** * RangeTombstoneList doesn't correctly merge multiple superseded rts, or overlapping rts with the * same ts. This causes it to emit noop boundary markers which can cause unneeded read repairs and * repair over streaming. This should technically be fixed in RangeTombstoneList. However, fixing * it isn't trivial and that class is already so complicated that the fix would have a good chance * of adding a worse bug. So we just swallow the noop boundary markers here. See CASSANDRA-14894 */ private static boolean shouldSkip(Unfiltered unfiltered) { if (unfiltered == null || !unfiltered.isRangeTombstoneMarker()) return false; RangeTombstoneMarker marker = (RangeTombstoneMarker) unfiltered; if (!marker.isBoundary()) return false; DeletionTime open = marker.openDeletionTime(false); DeletionTime close = marker.closeDeletionTime(false); return open.equals(close); } @Override protected Unfiltered computeNext() { while (true) { Unfiltered next = computeNextInternal(); if (shouldSkip(next)) continue; return next; } } private void updateNextRow() { if (nextRow == null && rows.hasNext()) nextRow = rows.next(); } private void updateNextRange() { while (nextRange == null && ranges.hasNext()) { nextRange = ranges.next(); if ((removeShadowedData && partitionLevelDeletion().supersedes(nextRange.deletionTime())) || nextRange.deletedSlice().isEmpty(metadata.comparator)) nextRange = null; } } private Row consumeNextRow() { Row row = nextRow; nextRow = null; if (!removeShadowedData) return row.filter(selection, metadata()); DeletionTime activeDeletion = openRange == null ? partitionLevelDeletion() : openRange.deletionTime(); return row.filter(selection, activeDeletion, false, metadata()); } private RangeTombstone consumeNextRange() { RangeTombstone range = nextRange; nextRange = null; return range; } private RangeTombstone consumeOpenRange() { RangeTombstone range = openRange; openRange = null; return range; } private ClusteringBound openBound(RangeTombstone range) { return range.deletedSlice().open(isReverseOrder()); } private ClusteringBound closeBound(RangeTombstone range) { return range.deletedSlice().close(isReverseOrder()); } private RangeTombstoneMarker closeOpenedRange() { // Check if that close if actually a boundary between markers updateNextRange(); RangeTombstoneMarker marker; if (nextRange != null && comparator.compare(closeBound(openRange), openBound(nextRange)) == 0) { marker = RangeTombstoneBoundaryMarker.makeBoundary(isReverseOrder(), closeBound(openRange), openBound(nextRange), openRange.deletionTime(), nextRange.deletionTime()); openRange = consumeNextRange(); } else { RangeTombstone toClose = consumeOpenRange(); marker = new RangeTombstoneBoundMarker(closeBound(toClose), toClose.deletionTime()); } return marker; } private RangeTombstoneMarker openRange() { assert openRange == null && nextRange != null; openRange = consumeNextRange(); return new RangeTombstoneBoundMarker(openBound(openRange), openRange.deletionTime()); } }
strapdata/cassandra
src/java/org/apache/cassandra/db/rows/RowAndDeletionMergeIterator.java
Java
apache-2.0
8,796
package common; import org.neo4j.graphdb.Label; /** * Created by dmhum_000 on 5/15/2016. */ public class CommonLabels { public static final Label ACCOUNT = Label.label("Account"); public static final Label SUBJECT = Label.label("Subject"); public static final Label MERCHANT = Label.label("Merchant"); public static final Label BRAND_FAMILY = Label.label("BrandFamily"); public static final Label BRAND = Label.label("Brand"); public static final Label SOURCE = Label.label("Source"); public static final Label CATALOG = Label.label("Catalog"); public static final Label PRODUCT = Label.label("Product"); public static final Label SERVICE = Label.label("Service"); public static final Label PACKAGE = Label.label("Package"); public static final Label CATEGORY = Label.label("Category"); public static final Label UGC = Label.label("UGC"); public static final Label REVIEW = Label.label("Review"); public static final Label QUESTION = Label.label("Question"); public static final Label ANSWER = Label.label("Answer"); public static final Label RESPONSE = Label.label("Response"); public static final Label UPDATE = Label.label("Update"); public static final Label[] COMPLETE_PACKAGE= {SUBJECT,PACKAGE}; public static final Label[] COMPLETE_SERVICE= {SUBJECT,SERVICE}; public static final Label[] COMPLETE_PRODUCT= {SUBJECT,PRODUCT}; public static final Label[] COMPLETE_CATEGORY= {SUBJECT,CATEGORY}; public static final Label[] COMPLETE_ACCOUNT= {ACCOUNT}; public static final Label[] COMPLETE_BRANDFAMILY= {SUBJECT,BRAND_FAMILY,SOURCE}; public static final Label[] COMPLETE_BRAND= {SUBJECT,BRAND,SOURCE}; public static final Label[] COMPLETE_MERCHANT= {SUBJECT,MERCHANT,CATALOG}; public static final Label[] COMPLETE_MERCHANT_BRAND= {SUBJECT,MERCHANT,BRAND,CATALOG,SOURCE}; public static final Label[] COMPLETE_REVIEW= {UGC,REVIEW}; public static final Label[] COMPLETE_UPDATE= {UGC,UPDATE}; public static final Label[] COMPLETE_QUESTION= {UGC,QUESTION}; public static final Label[] COMPLETE_ANSWER= {UGC,ANSWER}; public static final Label[] COMPLETE_RESPONSE= {UGC,RESPONSE}; }
davehummel/neo4jplugins
src/main/java/common/CommonLabels.java
Java
apache-2.0
2,217
package org.spincast.testing.junitrunner; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation to specify that a test or a test class * will be ran until it fails or the max number of tries is * reached. * <p> * You should not use this except when you try to debug * a test that sometimes fails... This allows you to run * it multiple times to trigger the error. * <p> * Also, this may be obvious, but notice that * the code annotated with this will be * ran more than once! Make sure this code does support it * and doesn't have unwanted side effects. */ @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface RepeatUntilFailure { /** * The maximum number of loops. */ int value(); /** * Sleep time in milliseconds between two loops. * <p> * Defaults: no sleep. */ int sleep() default 0; }
spincast/spincast-framework
spincast-testing/spincast-testing-junit-runner/src/main/java/org/spincast/testing/junitrunner/RepeatUntilFailure.java
Java
apache-2.0
1,026
package com.logginghub.logging.frontend.modules; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.junit.Test; import com.logginghub.utils.StringUtils; public class TestPingMonitorModule { @Test public void test_regex() throws Exception { String regex = "(\\d*) bytes from ([^ (]*)[ ]*(.*): icmp_seq=(\\d*) ttl=(\\d*) time=([\\d\\.]*) ms"; String input1 = "64 bytes from hosting (95.172.2.226): icmp_seq=3 ttl=47 time=24.5 ms"; assertThat(StringUtils.matchGroupsArray(input1, regex), is(new String[] { "64", "hosting", "(95.172.2.226)", "3", "47", "24.5" })); String input2 = "64 bytes from 54.171.42.240: icmp_seq=3 ttl=52 time=21.5 ms"; assertThat(StringUtils.matchGroupsArray(input2, regex), is(new String[] { "64", "54.171.42.240", "", "3", "52", "21.5" })); } }
logginghub/core
logginghub-frontend/src/test/java/com/logginghub/logging/frontend/modules/TestPingMonitorModule.java
Java
apache-2.0
901
package com.cmput301.cs.project.activities; import android.app.Activity; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentSender; import android.location.Location; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AutoCompleteTextView; import com.cmput301.cs.project.R; import com.cmput301.cs.project.adapters.PlaceAutocompleteAdapter; import com.cmput301.cs.project.controllers.SettingsController; import com.cmput301.cs.project.models.Destination; import com.cmput301.cs.project.utils.Utils; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.places.Place; import com.google.android.gms.location.places.PlaceBuffer; import com.google.android.gms.location.places.Places; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.MarkerOptions; /** * Map activity returns a result with a destination packaged in the intent as {@link #KEY_DESTINATION} * <p/> * It allows a user to select a place on the map or enter the place name in a text box */ // Apr 3, 2015 https://github.com/googlesamples/android-play-places/blob/master/PlaceComplete/Application/src/main/java/com/example/google/playservices/placecomplete/MainActivity.java // Mar 31, 2015 http://developer.android.com/google/auth/api-client.html#Starting public class MapActivity extends Activity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, GoogleMap.OnMapClickListener, GoogleMap.OnCameraChangeListener, GoogleMap.OnMyLocationChangeListener { public static final String KEY_DESTINATION = "key_destination"; // Request code to use when launching the resolution activity private static final int REQUEST_RESOLVE_ERROR = 1001; // Unique tag for the error dialog fragment private static final String DIALOG_ERROR = "dialog_error"; private static final String STATE_RESOLVING_ERROR = "resolving_error"; // fallback default bounds; will get updated with "my location" private static final LatLngBounds BOUNDS_GREATER_SYDNEY = new LatLngBounds( new LatLng(-34.041458, 150.790100), new LatLng(-33.682247, 151.383362)); private static final float ZOOM_PERCENTAGE = 0.8f; // 80% zoom level private AutoCompleteTextView mAddressSearch; private Destination mOriginalDestination; private GoogleApiClient mGoogleApiClient; // Bool to track whether the app is already resolving an error private boolean mResolvingError = false; private GoogleMap mGoogleMap; private PlaceAutocompleteAdapter mAdapter; private Destination mHome; private final Destination.Builder mBuilder = new Destination.Builder(); /** * Listener that handles selections from suggestions from the AutoCompleteTextView that * displays Place suggestions. * Gets the place id of the selected item and issues a request to the Places Geo Data API * to retrieve more details about the place. * * @see com.google.android.gms.location.places.GeoDataApi#getPlaceById(com.google.android.gms.common.api.GoogleApiClient, * String...) */ private AdapterView.OnItemClickListener mAutocompleteClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { /* Retrieve the place ID of the selected item from the Adapter. The adapter stores each Place suggestion in a PlaceAutocomplete object from which we read the place ID. */ final PlaceAutocompleteAdapter.PlaceAutocomplete item = mAdapter.getItem(position); final String placeId = String.valueOf(item.placeId); /* Issue a request to the Places Geo Data API to retrieve a Place object with additional details about the place. */ PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi .getPlaceById(mGoogleApiClient, placeId); placeResult.setResultCallback(mUpdatePlaceDetailsCallback); } }; /** * Callback for results from a Places Geo Data API query that shows the first place result in * the details view on screen. */ private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback = new ResultCallback<PlaceBuffer>() { @Override public void onResult(PlaceBuffer places) { if (!places.getStatus().isSuccess()) { // Request did not complete successfully return; } // Get the Place object from the buffer. final Place place = places.get(0); final LatLng latLng = place.getLatLng(); updateWithNameAndLatLng(place.getName(), latLng); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupActionBar(); setContentView(R.layout.map_activity); setResult(RESULT_CANCELED); mResolvingError = savedInstanceState != null && savedInstanceState.getBoolean(STATE_RESOLVING_ERROR, false); buildGoogleApiClient(); final MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); mAdapter = new PlaceAutocompleteAdapter(this, android.R.layout.simple_list_item_1, BOUNDS_GREATER_SYDNEY, null); mAddressSearch = (AutoCompleteTextView) findViewById(R.id.address_search); mAddressSearch.setAdapter(mAdapter); mAddressSearch.setOnItemClickListener(mAutocompleteClickListener); findViewById(R.id.clear).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAddressSearch.setText(""); } }); mOriginalDestination = getIntent().getParcelableExtra(KEY_DESTINATION); mHome = SettingsController.get(this).loadHomeAsDestination(); final LatLng location = mHome.getLocation(); final String name = mHome.getName(); if (location != null) { final View view = findViewById(R.id.home_btn); view.setVisibility(View.VISIBLE); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { animateMapTo(location); if (name == null) { setSearchTextWithoutAdapter(getString(R.string.home)); updateLatLng(location); } else { updateWithNameAndLatLng(name, location); } } }); } } private void updateWithNameAndLatLng(CharSequence name, LatLng latLng) { if (latLng == null) return; updateLatLng(latLng); if (latLng.equals(mHome.getLocation())) { setSearchTextWithoutAdapter(getString(R.string.formated_home, name)); } else { setSearchTextWithoutAdapter(name); } setResult(RESULT_OK, new Intent() .putExtra(KEY_DESTINATION, mBuilder .name(name.toString()) // .location(latLng) already set to the builder by updateLatLng(LatLng) .build())); } private void updateLatLng(LatLng latLng) { if (latLng == null) return; mGoogleMap.clear(); mGoogleMap.addMarker(new MarkerOptions().position(latLng)); animateMapTo(latLng); setResult(RESULT_OK, new Intent() .putExtra(KEY_DESTINATION, mBuilder .location(latLng) .build())); } private void setSearchTextWithoutAdapter(CharSequence charSequence) { //noinspection ConstantConditions incorrect NonNull annotation mAddressSearch.setAdapter(null); mAddressSearch.setText(charSequence); mAddressSearch.setAdapter(mAdapter); } @Override protected void onStart() { super.onStart(); if (!mResolvingError) { mGoogleApiClient.connect(); } } @Override protected void onStop() { mGoogleApiClient.disconnect(); super.onStop(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_RESOLVE_ERROR) { mResolvingError = false; if (resultCode == RESULT_OK) { // Make sure the app is not already connected or attempting to connect if (!mGoogleApiClient.isConnecting() && !mGoogleApiClient.isConnected()) { mGoogleApiClient.connect(); } } } else { super.onActivityResult(requestCode, resultCode, data); } } private void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Places.GEO_DATA_API) .addApi(Places.PLACE_DETECTION_API) .addApi(LocationServices.API) .build(); } private void setupActionBar() { Utils.setupDiscardDoneBar(this, new View.OnClickListener() { @Override public void onClick(View v) { setResult(RESULT_CANCELED); finish(); } }, new View.OnClickListener() { @Override public void onClick(View v) { // setResult is called in updateWithNameAndLatLng finish(); } }); } @Override public void onMapReady(GoogleMap map) { mGoogleMap = map; map.setMyLocationEnabled(true); map.setOnMapClickListener(this); map.setOnCameraChangeListener(this); if (mOriginalDestination != null) { final String name = mOriginalDestination.getName(); final LatLng location = mOriginalDestination.getLocation(); updateWithNameAndLatLng(name, location); } else { map.setOnMyLocationChangeListener(this); } } @Override public void onMapClick(LatLng latLng) { updateWithNameAndLatLng(getText(R.string.custom_location), latLng); } @Override public void onMyLocationChange(Location l) { mGoogleMap.setOnMyLocationChangeListener(null); final LatLng latLng = new LatLng(l.getLatitude(), l.getLongitude()); updateWithNameAndLatLng(getText(R.string.custom_location), latLng); } private void animateMapTo(LatLng latLng) { mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom( latLng, mGoogleMap.getMaxZoomLevel() * ZOOM_PERCENTAGE)); } @Override public void onCameraChange(CameraPosition cameraPosition) { mAdapter.setBounds(mGoogleMap.getProjection().getVisibleRegion().latLngBounds); } @Override public void onConnected(Bundle connectionHint) { // Successfully connected to the API client. Pass it to the adapter to enable API access. mAdapter.setGoogleApiClient(mGoogleApiClient); } @Override public void onConnectionSuspended(int cause) { // Connection to the API client has been suspended. Disable API access in the client. mAdapter.setGoogleApiClient(null); } @Override public void onConnectionFailed(ConnectionResult result) { if (mResolvingError) { // Already attempting to resolve an error. return; } else if (result.hasResolution()) { try { mResolvingError = true; result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR); } catch (IntentSender.SendIntentException e) { // There was an error with the resolution intent. Try again. mGoogleApiClient.connect(); } } else { // Show dialog using GooglePlayServicesUtil.getErrorDialog() showErrorDialog(result.getErrorCode()); mResolvingError = true; } mAdapter.setGoogleApiClient(null); } // The rest of this code is all about building the error dialog /* Creates a dialog for an error message */ private void showErrorDialog(int errorCode) { // Create a fragment for the error dialog ErrorDialogFragment dialogFragment = new ErrorDialogFragment(); // Pass the error that should be displayed Bundle args = new Bundle(); args.putInt(DIALOG_ERROR, errorCode); dialogFragment.setArguments(args); dialogFragment.show(getFragmentManager(), "errordialog"); } /* Called from ErrorDialogFragment when the dialog is dismissed. */ public void onDialogDismissed() { mResolvingError = false; } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(STATE_RESOLVING_ERROR, mResolvingError); } /* A fragment to display an error dialog */ public static class ErrorDialogFragment extends DialogFragment { public ErrorDialogFragment() { } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Get the error code and retrieve the appropriate dialog int errorCode = this.getArguments().getInt(DIALOG_ERROR); return GooglePlayServicesUtil.getErrorDialog(errorCode, this.getActivity(), REQUEST_RESOLVE_ERROR); } @Override public void onDismiss(DialogInterface dialog) { ((MapActivity) getActivity()).onDialogDismissed(); } } }
CMPUT301W15T10/301-Project
src/com/cmput301/cs/project/activities/MapActivity.java
Java
apache-2.0
14,790
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.servicequotas.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a * href="http://docs.aws.amazon.com/goto/WebAPI/service-quotas-2019-06-24/ListServiceQuotaIncreaseRequestsInTemplate" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListServiceQuotaIncreaseRequestsInTemplateResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * Information about the quota increase requests. * </p> */ private java.util.List<ServiceQuotaIncreaseRequestInTemplate> serviceQuotaIncreaseRequestInTemplateList; /** * <p> * The token to use to retrieve the next page of results. This value is null when there are no more results to * return. * </p> */ private String nextToken; /** * <p> * Information about the quota increase requests. * </p> * * @return Information about the quota increase requests. */ public java.util.List<ServiceQuotaIncreaseRequestInTemplate> getServiceQuotaIncreaseRequestInTemplateList() { return serviceQuotaIncreaseRequestInTemplateList; } /** * <p> * Information about the quota increase requests. * </p> * * @param serviceQuotaIncreaseRequestInTemplateList * Information about the quota increase requests. */ public void setServiceQuotaIncreaseRequestInTemplateList( java.util.Collection<ServiceQuotaIncreaseRequestInTemplate> serviceQuotaIncreaseRequestInTemplateList) { if (serviceQuotaIncreaseRequestInTemplateList == null) { this.serviceQuotaIncreaseRequestInTemplateList = null; return; } this.serviceQuotaIncreaseRequestInTemplateList = new java.util.ArrayList<ServiceQuotaIncreaseRequestInTemplate>( serviceQuotaIncreaseRequestInTemplateList); } /** * <p> * Information about the quota increase requests. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setServiceQuotaIncreaseRequestInTemplateList(java.util.Collection)} or * {@link #withServiceQuotaIncreaseRequestInTemplateList(java.util.Collection)} if you want to override the existing * values. * </p> * * @param serviceQuotaIncreaseRequestInTemplateList * Information about the quota increase requests. * @return Returns a reference to this object so that method calls can be chained together. */ public ListServiceQuotaIncreaseRequestsInTemplateResult withServiceQuotaIncreaseRequestInTemplateList( ServiceQuotaIncreaseRequestInTemplate... serviceQuotaIncreaseRequestInTemplateList) { if (this.serviceQuotaIncreaseRequestInTemplateList == null) { setServiceQuotaIncreaseRequestInTemplateList(new java.util.ArrayList<ServiceQuotaIncreaseRequestInTemplate>( serviceQuotaIncreaseRequestInTemplateList.length)); } for (ServiceQuotaIncreaseRequestInTemplate ele : serviceQuotaIncreaseRequestInTemplateList) { this.serviceQuotaIncreaseRequestInTemplateList.add(ele); } return this; } /** * <p> * Information about the quota increase requests. * </p> * * @param serviceQuotaIncreaseRequestInTemplateList * Information about the quota increase requests. * @return Returns a reference to this object so that method calls can be chained together. */ public ListServiceQuotaIncreaseRequestsInTemplateResult withServiceQuotaIncreaseRequestInTemplateList( java.util.Collection<ServiceQuotaIncreaseRequestInTemplate> serviceQuotaIncreaseRequestInTemplateList) { setServiceQuotaIncreaseRequestInTemplateList(serviceQuotaIncreaseRequestInTemplateList); return this; } /** * <p> * The token to use to retrieve the next page of results. This value is null when there are no more results to * return. * </p> * * @param nextToken * The token to use to retrieve the next page of results. This value is null when there are no more results * to return. */ public void setNextToken(String nextToken) { this.nextToken = nextToken; } /** * <p> * The token to use to retrieve the next page of results. This value is null when there are no more results to * return. * </p> * * @return The token to use to retrieve the next page of results. This value is null when there are no more results * to return. */ public String getNextToken() { return this.nextToken; } /** * <p> * The token to use to retrieve the next page of results. This value is null when there are no more results to * return. * </p> * * @param nextToken * The token to use to retrieve the next page of results. This value is null when there are no more results * to return. * @return Returns a reference to this object so that method calls can be chained together. */ public ListServiceQuotaIncreaseRequestsInTemplateResult withNextToken(String nextToken) { setNextToken(nextToken); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getServiceQuotaIncreaseRequestInTemplateList() != null) sb.append("ServiceQuotaIncreaseRequestInTemplateList: ").append(getServiceQuotaIncreaseRequestInTemplateList()).append(","); if (getNextToken() != null) sb.append("NextToken: ").append(getNextToken()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListServiceQuotaIncreaseRequestsInTemplateResult == false) return false; ListServiceQuotaIncreaseRequestsInTemplateResult other = (ListServiceQuotaIncreaseRequestsInTemplateResult) obj; if (other.getServiceQuotaIncreaseRequestInTemplateList() == null ^ this.getServiceQuotaIncreaseRequestInTemplateList() == null) return false; if (other.getServiceQuotaIncreaseRequestInTemplateList() != null && other.getServiceQuotaIncreaseRequestInTemplateList().equals(this.getServiceQuotaIncreaseRequestInTemplateList()) == false) return false; if (other.getNextToken() == null ^ this.getNextToken() == null) return false; if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getServiceQuotaIncreaseRequestInTemplateList() == null) ? 0 : getServiceQuotaIncreaseRequestInTemplateList().hashCode()); hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode()); return hashCode; } @Override public ListServiceQuotaIncreaseRequestsInTemplateResult clone() { try { return (ListServiceQuotaIncreaseRequestsInTemplateResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
aws/aws-sdk-java
aws-java-sdk-servicequotas/src/main/java/com/amazonaws/services/servicequotas/model/ListServiceQuotaIncreaseRequestsInTemplateResult.java
Java
apache-2.0
8,685
/******************************************************************************* * Copyright 2014 United States Government as represented by the * Administrator of the National Aeronautics and Space Administration. * All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ /** * <copyright> * </copyright> * * $Id$ */ package gov.nasa.arc.spife.timeline.model.impl; import gov.nasa.arc.spife.timeline.TimelinePackage; import gov.nasa.arc.spife.timeline.model.ZoomOption; import javax.measure.quantity.Duration; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.jscience.physics.amount.Amount; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Zoom Option</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link gov.nasa.arc.spife.timeline.model.impl.ZoomOptionImpl#getName <em>Name</em>}</li> * <li>{@link gov.nasa.arc.spife.timeline.model.impl.ZoomOptionImpl#getMajorTickInterval <em>Major Tick Interval</em>}</li> * <li>{@link gov.nasa.arc.spife.timeline.model.impl.ZoomOptionImpl#getMinorTickInterval <em>Minor Tick Interval</em>}</li> * <li>{@link gov.nasa.arc.spife.timeline.model.impl.ZoomOptionImpl#getMsInterval <em>Ms Interval</em>}</li> * <li>{@link gov.nasa.arc.spife.timeline.model.impl.ZoomOptionImpl#getMsMoveThreshold <em>Ms Move Threshold</em>}</li> * <li>{@link gov.nasa.arc.spife.timeline.model.impl.ZoomOptionImpl#getMsNudgeThreshold <em>Ms Nudge Threshold</em>}</li> * <li>{@link gov.nasa.arc.spife.timeline.model.impl.ZoomOptionImpl#getScrollInterval <em>Scroll Interval</em>}</li> * </ul> * </p> * * @generated */ public class ZoomOptionImpl extends MinimalEObjectImpl.Container implements ZoomOption { /** * The default value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The default value of the '{@link #getMajorTickInterval() <em>Major Tick Interval</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMajorTickInterval() * @generated * @ordered */ protected static final long MAJOR_TICK_INTERVAL_EDEFAULT = 86400000L; /** * The cached value of the '{@link #getMajorTickInterval() <em>Major Tick Interval</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMajorTickInterval() * @generated * @ordered */ protected long majorTickInterval = MAJOR_TICK_INTERVAL_EDEFAULT; /** * The default value of the '{@link #getMinorTickInterval() <em>Minor Tick Interval</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMinorTickInterval() * @generated * @ordered */ protected static final long MINOR_TICK_INTERVAL_EDEFAULT = 3600000L; /** * The cached value of the '{@link #getMinorTickInterval() <em>Minor Tick Interval</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMinorTickInterval() * @generated * @ordered */ protected long minorTickInterval = MINOR_TICK_INTERVAL_EDEFAULT; /** * The default value of the '{@link #getMsInterval() <em>Ms Interval</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMsInterval() * @generated * @ordered */ protected static final long MS_INTERVAL_EDEFAULT = 0L; /** * The cached value of the '{@link #getMsInterval() <em>Ms Interval</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMsInterval() * @generated * @ordered */ protected long msInterval = MS_INTERVAL_EDEFAULT; /** * The default value of the '{@link #getMsMoveThreshold() <em>Ms Move Threshold</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMsMoveThreshold() * @generated * @ordered */ protected static final long MS_MOVE_THRESHOLD_EDEFAULT = 0L; /** * The cached value of the '{@link #getMsMoveThreshold() <em>Ms Move Threshold</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMsMoveThreshold() * @generated * @ordered */ protected long msMoveThreshold = MS_MOVE_THRESHOLD_EDEFAULT; /** * The default value of the '{@link #getMsNudgeThreshold() <em>Ms Nudge Threshold</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMsNudgeThreshold() * @generated * @ordered */ protected static final long MS_NUDGE_THRESHOLD_EDEFAULT = 0L; /** * The cached value of the '{@link #getMsNudgeThreshold() <em>Ms Nudge Threshold</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMsNudgeThreshold() * @generated * @ordered */ protected long msNudgeThreshold = MS_NUDGE_THRESHOLD_EDEFAULT; /** * The cached value of the '{@link #getScrollInterval() <em>Scroll Interval</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getScrollInterval() * @generated * @ordered */ protected Amount<Duration> scrollInterval; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ZoomOptionImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return TimelinePackage.Literals.ZOOM_OPTION; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, TimelinePackage.ZOOM_OPTION__NAME, oldName, name)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public long getMajorTickInterval() { return majorTickInterval; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMajorTickInterval(long newMajorTickInterval) { long oldMajorTickInterval = majorTickInterval; majorTickInterval = newMajorTickInterval; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, TimelinePackage.ZOOM_OPTION__MAJOR_TICK_INTERVAL, oldMajorTickInterval, majorTickInterval)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public long getMinorTickInterval() { return minorTickInterval; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMinorTickInterval(long newMinorTickInterval) { long oldMinorTickInterval = minorTickInterval; minorTickInterval = newMinorTickInterval; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, TimelinePackage.ZOOM_OPTION__MINOR_TICK_INTERVAL, oldMinorTickInterval, minorTickInterval)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public long getMsInterval() { return msInterval; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMsInterval(long newMsInterval) { long oldMsInterval = msInterval; msInterval = newMsInterval; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, TimelinePackage.ZOOM_OPTION__MS_INTERVAL, oldMsInterval, msInterval)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public long getMsMoveThreshold() { return msMoveThreshold; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMsMoveThreshold(long newMsMoveThreshold) { long oldMsMoveThreshold = msMoveThreshold; msMoveThreshold = newMsMoveThreshold; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, TimelinePackage.ZOOM_OPTION__MS_MOVE_THRESHOLD, oldMsMoveThreshold, msMoveThreshold)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public long getMsNudgeThreshold() { return msNudgeThreshold; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMsNudgeThreshold(long newMsNudgeThreshold) { long oldMsNudgeThreshold = msNudgeThreshold; msNudgeThreshold = newMsNudgeThreshold; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, TimelinePackage.ZOOM_OPTION__MS_NUDGE_THRESHOLD, oldMsNudgeThreshold, msNudgeThreshold)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Amount<Duration> getScrollInterval() { return scrollInterval; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setScrollInterval(Amount<Duration> newScrollInterval) { Amount<Duration> oldScrollInterval = scrollInterval; scrollInterval = newScrollInterval; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, TimelinePackage.ZOOM_OPTION__SCROLL_INTERVAL, oldScrollInterval, scrollInterval)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case TimelinePackage.ZOOM_OPTION__NAME: return getName(); case TimelinePackage.ZOOM_OPTION__MAJOR_TICK_INTERVAL: return getMajorTickInterval(); case TimelinePackage.ZOOM_OPTION__MINOR_TICK_INTERVAL: return getMinorTickInterval(); case TimelinePackage.ZOOM_OPTION__MS_INTERVAL: return getMsInterval(); case TimelinePackage.ZOOM_OPTION__MS_MOVE_THRESHOLD: return getMsMoveThreshold(); case TimelinePackage.ZOOM_OPTION__MS_NUDGE_THRESHOLD: return getMsNudgeThreshold(); case TimelinePackage.ZOOM_OPTION__SCROLL_INTERVAL: return getScrollInterval(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case TimelinePackage.ZOOM_OPTION__NAME: setName((String)newValue); return; case TimelinePackage.ZOOM_OPTION__MAJOR_TICK_INTERVAL: setMajorTickInterval((Long)newValue); return; case TimelinePackage.ZOOM_OPTION__MINOR_TICK_INTERVAL: setMinorTickInterval((Long)newValue); return; case TimelinePackage.ZOOM_OPTION__MS_INTERVAL: setMsInterval((Long)newValue); return; case TimelinePackage.ZOOM_OPTION__MS_MOVE_THRESHOLD: setMsMoveThreshold((Long)newValue); return; case TimelinePackage.ZOOM_OPTION__MS_NUDGE_THRESHOLD: setMsNudgeThreshold((Long)newValue); return; case TimelinePackage.ZOOM_OPTION__SCROLL_INTERVAL: setScrollInterval((Amount<Duration>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case TimelinePackage.ZOOM_OPTION__NAME: setName(NAME_EDEFAULT); return; case TimelinePackage.ZOOM_OPTION__MAJOR_TICK_INTERVAL: setMajorTickInterval(MAJOR_TICK_INTERVAL_EDEFAULT); return; case TimelinePackage.ZOOM_OPTION__MINOR_TICK_INTERVAL: setMinorTickInterval(MINOR_TICK_INTERVAL_EDEFAULT); return; case TimelinePackage.ZOOM_OPTION__MS_INTERVAL: setMsInterval(MS_INTERVAL_EDEFAULT); return; case TimelinePackage.ZOOM_OPTION__MS_MOVE_THRESHOLD: setMsMoveThreshold(MS_MOVE_THRESHOLD_EDEFAULT); return; case TimelinePackage.ZOOM_OPTION__MS_NUDGE_THRESHOLD: setMsNudgeThreshold(MS_NUDGE_THRESHOLD_EDEFAULT); return; case TimelinePackage.ZOOM_OPTION__SCROLL_INTERVAL: setScrollInterval((Amount<Duration>)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case TimelinePackage.ZOOM_OPTION__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case TimelinePackage.ZOOM_OPTION__MAJOR_TICK_INTERVAL: return majorTickInterval != MAJOR_TICK_INTERVAL_EDEFAULT; case TimelinePackage.ZOOM_OPTION__MINOR_TICK_INTERVAL: return minorTickInterval != MINOR_TICK_INTERVAL_EDEFAULT; case TimelinePackage.ZOOM_OPTION__MS_INTERVAL: return msInterval != MS_INTERVAL_EDEFAULT; case TimelinePackage.ZOOM_OPTION__MS_MOVE_THRESHOLD: return msMoveThreshold != MS_MOVE_THRESHOLD_EDEFAULT; case TimelinePackage.ZOOM_OPTION__MS_NUDGE_THRESHOLD: return msNudgeThreshold != MS_NUDGE_THRESHOLD_EDEFAULT; case TimelinePackage.ZOOM_OPTION__SCROLL_INTERVAL: return scrollInterval != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * We just want the 'name' property to be returned * <!-- end-user-doc --> * @generated NOT */ @Override public String toString() { if (eIsProxy()) return super.toString(); return getName(); } } //ZoomOptionImpl
nasa/OpenSPIFe
gov.nasa.arc.spife/src/gov/nasa/arc/spife/timeline/model/impl/ZoomOptionImpl.java
Java
apache-2.0
14,158
package mil.emp3.api.listeners; import mil.emp3.api.events.MapViewChangeEvent; /** * A class must implement this interface to process map view change events. */ public interface IMapViewChangeEventListener extends IEventListener<MapViewChangeEvent> { }
missioncommand/emp3-android
sdk/sdk-api/src/main/java/mil/emp3/api/listeners/IMapViewChangeEventListener.java
Java
apache-2.0
257
package com.fsck.k9.mailstore; import java.io.ByteArrayInputStream; import java.util.Date; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.annotation.VisibleForTesting; import android.util.Log; import com.fsck.k9.Account; import com.fsck.k9.BuildConfig; import com.fsck.k9.K9; import com.fsck.k9.activity.MessageReference; import com.fsck.k9.mail.Address; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Folder; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.internet.MimeMessage; import com.fsck.k9.mail.message.MessageHeaderParser; import com.fsck.k9.mailstore.LockableDatabase.DbCallback; import com.fsck.k9.mailstore.LockableDatabase.WrappedException; import com.fsck.k9.message.extractors.PreviewResult.PreviewType; public class LocalMessage extends MimeMessage { protected MessageReference mReference; private final LocalStore localStore; private long mId; private int mAttachmentCount; private String mSubject; private String mPreview = ""; private long mThreadId; private long mRootId; private long messagePartId; private String mimeType; private PreviewType previewType; private LocalMessage(LocalStore localStore) { this.localStore = localStore; } LocalMessage(LocalStore localStore, String uid, Folder folder) { this.localStore = localStore; this.mUid = uid; this.mFolder = folder; } void populateFromGetMessageCursor(Cursor cursor) throws MessagingException { final String subject = cursor.getString(0); this.setSubject(subject == null ? "" : subject); Address[] from = Address.unpack(cursor.getString(1)); if (from.length > 0) { this.setFrom(from[0]); } this.setInternalSentDate(new Date(cursor.getLong(2))); this.setUid(cursor.getString(3)); String flagList = cursor.getString(4); if (flagList != null && flagList.length() > 0) { String[] flags = flagList.split(","); for (String flag : flags) { try { this.setFlagInternal(Flag.valueOf(flag), true); } catch (Exception e) { if (!"X_BAD_FLAG".equals(flag)) { Log.w(K9.LOG_TAG, "Unable to parse flag " + flag); } } } } this.mId = cursor.getLong(5); this.setRecipients(RecipientType.TO, Address.unpack(cursor.getString(6))); this.setRecipients(RecipientType.CC, Address.unpack(cursor.getString(7))); this.setRecipients(RecipientType.BCC, Address.unpack(cursor.getString(8))); this.setReplyTo(Address.unpack(cursor.getString(9))); this.mAttachmentCount = cursor.getInt(10); this.setInternalDate(new Date(cursor.getLong(11))); this.setMessageId(cursor.getString(12)); String previewTypeString = cursor.getString(24); DatabasePreviewType databasePreviewType = DatabasePreviewType.fromDatabaseValue(previewTypeString); previewType = databasePreviewType.getPreviewType(); if (previewType == PreviewType.TEXT) { mPreview = cursor.getString(14); } else { mPreview = ""; } if (this.mFolder == null) { LocalFolder f = new LocalFolder(this.localStore, cursor.getInt(13)); f.open(LocalFolder.OPEN_MODE_RW); this.mFolder = f; } mThreadId = (cursor.isNull(15)) ? -1 : cursor.getLong(15); mRootId = (cursor.isNull(16)) ? -1 : cursor.getLong(16); boolean deleted = (cursor.getInt(17) == 1); boolean read = (cursor.getInt(18) == 1); boolean flagged = (cursor.getInt(19) == 1); boolean answered = (cursor.getInt(20) == 1); boolean forwarded = (cursor.getInt(21) == 1); setFlagInternal(Flag.DELETED, deleted); setFlagInternal(Flag.SEEN, read); setFlagInternal(Flag.FLAGGED, flagged); setFlagInternal(Flag.ANSWERED, answered); setFlagInternal(Flag.FORWARDED, forwarded); setMessagePartId(cursor.getLong(22)); mimeType = cursor.getString(23); byte[] header = cursor.getBlob(25); if (header != null) { MessageHeaderParser.parse(this, new ByteArrayInputStream(header)); } else { Log.d(K9.LOG_TAG, "No headers available for this message!"); } } @VisibleForTesting public void setMessagePartId(long messagePartId) { this.messagePartId = messagePartId; } public long getMessagePartId() { return messagePartId; } @Override public String getMimeType() { return mimeType; } /* Custom version of writeTo that updates the MIME message based on localMessage * changes. */ public PreviewType getPreviewType() { return previewType; } public String getPreview() { return mPreview; } @Override public String getSubject() { return mSubject; } @Override public void setSubject(String subject) { mSubject = subject; } @Override public void setMessageId(String messageId) { mMessageId = messageId; } @Override public void setUid(String uid) { super.setUid(uid); this.mReference = null; } @Override public boolean hasAttachments() { return (mAttachmentCount > 0); } public int getAttachmentCount() { return mAttachmentCount; } @Override public void setFrom(Address from) { this.mFrom = new Address[] { from }; } @Override public void setReplyTo(Address[] replyTo) { if (replyTo == null || replyTo.length == 0) { mReplyTo = null; } else { mReplyTo = replyTo; } } /* * For performance reasons, we add headers instead of setting them (see super implementation) * which removes (expensive) them before adding them */ @Override public void setRecipients(RecipientType type, Address[] addresses) { if (type == RecipientType.TO) { if (addresses == null || addresses.length == 0) { this.mTo = null; } else { this.mTo = addresses; } } else if (type == RecipientType.CC) { if (addresses == null || addresses.length == 0) { this.mCc = null; } else { this.mCc = addresses; } } else if (type == RecipientType.BCC) { if (addresses == null || addresses.length == 0) { this.mBcc = null; } else { this.mBcc = addresses; } } else { throw new IllegalArgumentException("Unrecognized recipient type."); } } public void setFlagInternal(Flag flag, boolean set) throws MessagingException { super.setFlag(flag, set); } @Override public long getId() { return mId; } @Override public void setFlag(final Flag flag, final boolean set) throws MessagingException { try { this.localStore.database.execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { if (flag == Flag.DELETED && set) { delete(); } LocalMessage.super.setFlag(flag, set); } catch (MessagingException e) { throw new WrappedException(e); } /* * Set the flags on the message. */ ContentValues cv = new ContentValues(); cv.put("flags", LocalMessage.this.localStore.serializeFlags(getFlags())); cv.put("read", isSet(Flag.SEEN) ? 1 : 0); cv.put("flagged", isSet(Flag.FLAGGED) ? 1 : 0); cv.put("answered", isSet(Flag.ANSWERED) ? 1 : 0); cv.put("forwarded", isSet(Flag.FORWARDED) ? 1 : 0); db.update("messages", cv, "id = ?", new String[] { Long.toString(mId) }); return null; } }); } catch (WrappedException e) { throw(MessagingException) e.getCause(); } this.localStore.notifyChange(); } /* * If a message is being marked as deleted we want to clear out its content. Delete will not actually remove the * row since we need to retain the UID for synchronization purposes. */ private void delete() throws MessagingException { try { localStore.database.execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { ContentValues cv = new ContentValues(); cv.put("deleted", 1); cv.put("empty", 1); cv.putNull("subject"); cv.putNull("sender_list"); cv.putNull("date"); cv.putNull("to_list"); cv.putNull("cc_list"); cv.putNull("bcc_list"); cv.putNull("preview"); cv.putNull("reply_to_list"); cv.putNull("message_part_id"); db.update("messages", cv, "id = ?", new String[] { Long.toString(mId) }); try { ((LocalFolder) mFolder).deleteMessagePartsAndDataFromDisk(messagePartId); } catch (MessagingException e) { throw new WrappedException(e); } return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } localStore.notifyChange(); } public void debugClearLocalData() throws MessagingException { if (!BuildConfig.DEBUG) { throw new AssertionError("method must only be used in debug build!"); } try { localStore.database.execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, MessagingException { ContentValues cv = new ContentValues(); cv.putNull("message_part_id"); db.update("messages", cv, "id = ?", new String[] { Long.toString(mId) }); try { ((LocalFolder) mFolder).deleteMessagePartsAndDataFromDisk(messagePartId); } catch (MessagingException e) { throw new WrappedException(e); } setFlag(Flag.X_DOWNLOADED_FULL, false); setFlag(Flag.X_DOWNLOADED_PARTIAL, false); return null; } }); } catch (WrappedException e) { throw (MessagingException) e.getCause(); } localStore.notifyChange(); } /* * Completely remove a message from the local database * * TODO: document how this updates the thread structure */ @Override public void destroy() throws MessagingException { try { this.localStore.database.execute(true, new DbCallback<Void>() { @Override public Void doDbWork(final SQLiteDatabase db) throws WrappedException, UnavailableStorageException { try { LocalFolder localFolder = (LocalFolder) mFolder; localFolder.deleteMessagePartsAndDataFromDisk(messagePartId); deleteFulltextIndexEntry(db, mId); if (hasThreadChildren(db, mId)) { // This message has children in the thread structure so we need to // make it an empty message. ContentValues cv = new ContentValues(); cv.put("id", mId); cv.put("folder_id", localFolder.getId()); cv.put("deleted", 0); cv.put("message_id", getMessageId()); cv.put("empty", 1); db.replace("messages", null, cv); // Nothing else to do return null; } // Get the message ID of the parent message if it's empty long currentId = getEmptyThreadParent(db, mId); // Delete the placeholder message deleteMessageRow(db, mId); /* * Walk the thread tree to delete all empty parents without children */ while (currentId != -1) { if (hasThreadChildren(db, currentId)) { // We made sure there are no empty leaf nodes and can stop now. break; } // Get ID of the (empty) parent for the next iteration long newId = getEmptyThreadParent(db, currentId); // Delete the empty message deleteMessageRow(db, currentId); currentId = newId; } } catch (MessagingException e) { throw new WrappedException(e); } return null; } }); } catch (WrappedException e) { throw(MessagingException) e.getCause(); } this.localStore.notifyChange(); } /** * Get ID of the the given message's parent if the parent is an empty message. * * @param db * {@link SQLiteDatabase} instance to access the database. * @param messageId * The database ID of the message to get the parent for. * * @return Message ID of the parent message if there exists a parent and it is empty. * Otherwise {@code -1}. */ private long getEmptyThreadParent(SQLiteDatabase db, long messageId) { Cursor cursor = db.rawQuery( "SELECT m.id " + "FROM threads t1 " + "JOIN threads t2 ON (t1.parent = t2.id) " + "LEFT JOIN messages m ON (t2.message_id = m.id) " + "WHERE t1.message_id = ? AND m.empty = 1", new String[] { Long.toString(messageId) }); try { return (cursor.moveToFirst() && !cursor.isNull(0)) ? cursor.getLong(0) : -1; } finally { cursor.close(); } } /** * Check whether or not a message has child messages in the thread structure. * * @param db * {@link SQLiteDatabase} instance to access the database. * @param messageId * The database ID of the message to get the children for. * * @return {@code true} if the message has children. {@code false} otherwise. */ private boolean hasThreadChildren(SQLiteDatabase db, long messageId) { Cursor cursor = db.rawQuery( "SELECT COUNT(t2.id) " + "FROM threads t1 " + "JOIN threads t2 ON (t2.parent = t1.id) " + "WHERE t1.message_id = ?", new String[] { Long.toString(messageId) }); try { return (cursor.moveToFirst() && !cursor.isNull(0) && cursor.getLong(0) > 0L); } finally { cursor.close(); } } private void deleteFulltextIndexEntry(SQLiteDatabase db, long messageId) { String[] idArg = { Long.toString(messageId) }; db.delete("messages_fulltext", "docid = ?", idArg); } /** * Delete a message from the 'messages' and 'threads' tables. * * @param db * {@link SQLiteDatabase} instance to access the database. * @param messageId * The database ID of the message to delete. */ private void deleteMessageRow(SQLiteDatabase db, long messageId) { String[] idArg = { Long.toString(messageId) }; // Delete the message db.delete("messages", "id = ?", idArg); // Delete row in 'threads' table // TODO: create trigger for 'messages' table to get rid of the row in 'threads' table db.delete("threads", "message_id = ?", idArg); } @Override public LocalMessage clone() { LocalMessage message = new LocalMessage(localStore); super.copy(message); message.mId = mId; message.mAttachmentCount = mAttachmentCount; message.mSubject = mSubject; message.mPreview = mPreview; return message; } public long getThreadId() { return mThreadId; } public long getRootId() { return mRootId; } public Account getAccount() { return localStore.getAccount(); } public MessageReference makeMessageReference() { if (mReference == null) { mReference = new MessageReference(getFolder().getAccountUuid(), getFolder().getName(), mUid, null); } return mReference; } @Override protected void copy(MimeMessage destination) { super.copy(destination); if (destination instanceof LocalMessage) { ((LocalMessage)destination).mReference = mReference; } } @Override public LocalFolder getFolder() { return (LocalFolder) super.getFolder(); } public String getUri() { return "email://messages/" + getAccount().getAccountNumber() + "/" + getFolder().getName() + "/" + getUid(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } // distinguish by account uuid, in addition to what Message.equals() does above String thisAccountUuid = getAccountUuid(); String thatAccountUuid = ((LocalMessage) o).getAccountUuid(); return thisAccountUuid != null ? thisAccountUuid.equals(thatAccountUuid) : thatAccountUuid == null; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (getAccountUuid() != null ? getAccountUuid().hashCode() : 0); return result; } private String getAccountUuid() { return getAccount().getUuid(); } public boolean isBodyMissing() { return getBody() == null; } }
sedrubal/k-9
k9mail/src/main/java/com/fsck/k9/mailstore/LocalMessage.java
Java
apache-2.0
19,368
/* * @(#)StringAttribute.java * * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistribution 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 Sun Microsystems, Inc. or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use in * the design, construction, operation or maintenance of any nuclear facility. */ package com.sun.xacml.attr; import java.net.URI; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Representation of an xs:string value. This class supports parsing * xs:string values. All objects of this class are immutable and * all methods of the class are thread-safe. * <p> * Note that there is currently some confusion in the XACML specification * about whether this datatype should be able to handle XML elements (ie, * whether &lt;AttributeValue DataType="...string"&gt;&lt;foo/&gt; * &lt;/AttributeValue&gt; is valid). Until that is clarified the strict * definition of the string datatype is used in this code, which means that * elements are not valid. * * @since 1.0 * @author Marco Barreno * @author Seth Proctor * @author Steve Hanna */ public class StringAttribute extends AttributeValue { /** * Official name of this type */ public static final String identifier = "http://www.w3.org/2001/XMLSchema#string"; /** * URI version of name for this type * <p> * This field is initialized by a static initializer so that * we can catch any exceptions thrown by URI(String) and * transform them into a RuntimeException, since this should * never happen but should be reported properly if it ever does. */ private static URI identifierURI; /** * RuntimeException that wraps an Exception thrown during the * creation of identifierURI, null if none. */ private static RuntimeException earlyException; /** * Static initializer that initializes the identifierURI * class field so that we can catch any exceptions thrown * by URI(String) and transform them into a RuntimeException. * Such exceptions should never happen but should be reported * properly if they ever do. */ static { try { identifierURI = new URI(identifier); } catch (Exception e) { earlyException = new IllegalArgumentException(); earlyException.initCause(e); } }; /** * The actual String value that this object represents. */ private String value; /** * Creates a new <code>StringAttribute</code> that represents * the String value supplied. * * @param value the <code>String</code> value to be represented */ public StringAttribute(String value) { super(identifierURI); // Shouldn't happen, but just in case... if (earlyException != null) throw earlyException; this.value = value; } /** * Returns a new <code>StringAttribute</code> that represents * the xs:string at a particular DOM node. * * @param root the <code>Node</code> that contains the desired value * @return a new <code>StringAttribute</code> representing the * appropriate value (null if there is a parsing error) */ public static StringAttribute getInstance(Node root) { Node node = root.getFirstChild(); // Strings are allowed to have an empty AttributeValue element and are // just treated as empty strings...we have to handle this case if (node == null) return new StringAttribute(""); // get the type of the node short type = node.getNodeType(); // now see if we have (effectively) a simple string value if ((type == Node.TEXT_NODE) || (type == Node.CDATA_SECTION_NODE) || (type == Node.COMMENT_NODE)) { return getInstance(node.getNodeValue()); } // there is some confusion in the specifications about what should // happen at this point, but the strict reading of the XMLSchema // specification suggests that this should be an error return null; } /** * Returns a new <code>StringAttribute</code> that represents * the xs:string value indicated by the <code>String</code> provided. * * @param value a string representing the desired value * @return a new <code>StringAttribute</code> representing the * appropriate value */ public static StringAttribute getInstance(String value) { return new StringAttribute(value); } /** * Returns the <code>String</code> value represented by this object. * * @return the <code>String</code> value */ public String getValue() { return value; } /** * Returns true if the input is an instance of this class and if its * value equals the value contained in this class. * * @param o the object to compare * * @return true if this object and the input represent the same value */ public boolean equals(Object o) { if (! (o instanceof StringAttribute)) return false; StringAttribute other = (StringAttribute)o; return value.equals(other.value); } /** * Returns the hashcode value used to index and compare this object with * others of the same type. Typically this is the hashcode of the backing * data object. * * @return the object's hashcode value */ public int hashCode() { return value.hashCode(); } /** * Converts to a String representation. * * @return the String representation */ public String toString() { return "StringAttribute: \"" + value + "\""; } /** * */ public String encode() { return value; } }
townbull/mtaaas
src/sunxacml/com/sun/xacml/attr/StringAttribute.java
Java
apache-2.0
7,356
package com.mbui.sdk.feature.viewpager.features; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.util.SparseArray; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Scroller; import com.mbui.sdk.afix.FixedViewPager; import com.mbui.sdk.feature.abs.AbsFeature; import com.mbui.sdk.feature.callback.AddFeatureCallBack; import com.mbui.sdk.feature.callback.ComputeScrollCallBack; import com.mbui.sdk.feature.view.features.ViewTouchFeature; import com.mbui.sdk.feature.viewpager.callback.PageItemListener; import com.mbui.sdk.feature.viewpager.callback.PageScrolledCallBack; import com.mbui.sdk.reforms.Debug; import com.nineoldandroids.view.ViewHelper; /** * Created by chenwei on 15/1/20. */ public class PageTransFeature extends ViewTouchFeature<FixedViewPager> implements PageItemListener, PageScrolledCallBack, ComputeScrollCallBack, AddFeatureCallBack { private String debug = "PageTransFeature"; private SparseArray<View> views; private Scroller mScroller; private FixedViewPager viewPager; private int transChildId; private boolean ON_POINT_UP; private TRANS_MODE transMode = TRANS_MODE.FADE_MIX; private int currPosition = 0; private float SCALE_MAX = 1.3f; private boolean viewChanged; public static enum TRANS_MODE { FADE_MIX, FADE_ORDER } public PageTransFeature(Context context) { super(context); initSelf(); } private void initSelf() { views = new SparseArray<>(); } public SparseArray<View> getViews() { return views; } public void setTransMode(TRANS_MODE mode) { this.transMode = mode; } @Override public void constructor(Context context, AttributeSet attrs, int defStyle) { } @Override public void afterInstantiateItem(ViewGroup container, View item, int position) { views.put(position, item); Debug.print(debug, "afterInstantiateItem " + position); } @Override public void beforeDestroyItem(ViewGroup container, View item, int position) { int offset = 2 * viewPager.getOffscreenPageLimit() + 2; if (views.get(position + offset) != null) views.remove(position + offset); if (position >= offset && views.get(position - offset) != null) views.remove(position - offset); Debug.print(debug, "beforeDestroyItem " + position); } @Override public void beforePageScrolled(int position, float positionOffset, int positionOffsetPixels) { currPosition = position; transView(views.get(position), views.get(position + 1), positionOffset, positionOffsetPixels); Debug.print(debug, "beforePageScrolled " + " " + positionOffsetPixels); } @Override public void afterPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } //与 viewPager.getCurrentItem()相比,这个是完成过程的动态位置,viewPager.getCurrentItem()是最终结果 public int getScrollPosition() { return currPosition; } public void setScaleMax(float scaleMax) { this.SCALE_MAX = scaleMax; } @Override public void beforeComputeScroll() { if (ON_POINT_UP && viewPager.getWidth() > 0 && mScroller.computeScrollOffset()) { int positionOffsetPixels = mScroller.getCurrX() % viewPager.getWidth(); transView(views.get(currPosition), views.get(currPosition + 1), 1.0f * positionOffsetPixels / viewPager.getWidth(), positionOffsetPixels); Debug.print(debug, "beforeComputeScroll " + 1.0f * positionOffsetPixels / viewPager.getWidth() + " " + positionOffsetPixels); } } @Override public void afterComputeScroll() { } /** * 设置变换的View * * @param view * @return */ private View getChildView(View view) { if (view == null || transChildId == 0 || view.findViewById(transChildId) == null) return view; return view.findViewById(transChildId); } //设置切换效果的View,默认是页面本身,可以设置他的子View public void setTransChildId(int resId) { this.transChildId = resId; } //选择切换方式 private void transView(View left, View right, float positionOffset, int positionOffsetPixels) { if (positionOffset < 0 || positionOffsetPixels < 0) return; if (positionOffset < 1e-6) { if (viewChanged) { disableHardwareLayer(); resetView(); viewChanged = false; } } else { switch (transMode) { case FADE_MIX: case FADE_ORDER: animateFade(left, right, positionOffset, positionOffsetPixels); break; } viewChanged = true; } } private void animateFade(View left, View right, float positionOffset, int positionOffsetPixels) { Debug.print(debug, "animateFade " + positionOffset + " " + positionOffsetPixels); if (right != null) { manageLayer(right, true); int mTrans = -viewPager.getWidth() - viewPager.getPageMargin() + positionOffsetPixels; switch (transMode) { case FADE_MIX: ViewHelper.setTranslationX(right, mTrans); ViewHelper.setAlpha(getChildView(right), positionOffset); break; case FADE_ORDER: ViewHelper.setTranslationX(right, mTrans); ViewHelper.setAlpha(getChildView(right), positionOffset < 0.5 ? 0 : 2f * positionOffset - 1f); break; } } if (left != null) { manageLayer(left, true); float mScale = (SCALE_MAX - 1) * positionOffset + 1; ViewHelper.setTranslationX(left, positionOffsetPixels); ViewHelper.setScaleX(left, mScale); ViewHelper.setScaleY(left, mScale); switch (transMode) { case FADE_MIX: ViewHelper.setAlpha(getChildView(left), 1 - positionOffset); break; case FADE_ORDER: ViewHelper.setAlpha(getChildView(left), positionOffset > 0.5 ? 0f : 1 - 2f * positionOffset); break; } } } private void resetView() { for (int i = 0; i < viewPager.getChildCount(); i++) { View view = viewPager.getChildAt(i); if (view != null) { ViewHelper.setTranslationX(view, 0); ViewHelper.setScaleX(view, 1f); ViewHelper.setScaleY(view, 1f); ViewHelper.setAlpha(getChildView(view), 1f); } } } @Override public boolean beforeDispatchTouchEvent(MotionEvent event) { ON_POINT_UP = event.getAction() == MotionEvent.ACTION_UP; return super.beforeDispatchTouchEvent(event); } @Override public void afterDispatchTouchEvent(MotionEvent event) { super.afterDispatchTouchEvent(event); } @Override public void beforeAddFeature(AbsFeature feature) { } @Override public void afterAddFeature(AbsFeature feature) { mScroller = getHost().getScroller(); viewPager = getHost(); viewPager.setScrollDurationFactor(4f); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void disableHardwareLayer() { if (Build.VERSION.SDK_INT < 11) return; for (int i = 0; i < viewPager.getChildCount(); i++) { View v = viewPager.getChildAt(i); if (v.getLayerType() != View.LAYER_TYPE_NONE) v.setLayerType(View.LAYER_TYPE_NONE, null); } } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void manageLayer(View v, boolean enableHardware) { if (Build.VERSION.SDK_INT < 11) return; int layerType = enableHardware ? View.LAYER_TYPE_HARDWARE : View.LAYER_TYPE_NONE; if (layerType != v.getLayerType()) v.setLayerType(layerType, null); } }
cheerr/uirepo
library/src/main/java/com/mbui/sdk/feature/viewpager/features/PageTransFeature.java
Java
apache-2.0
8,305
/** * Copyright 2004-2014 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kpme.pm.report.group; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.kuali.kpme.core.groupkey.HrGroupKeyBo; import org.kuali.kpme.pm.PMIntegrationTestCase; import org.kuali.kpme.pm.positionreportgroup.PositionReportGroupBo; import org.kuali.kpme.pm.positionreportgroup.PositionReportGroupKeyBo; import org.kuali.rice.krad.service.BusinessObjectService; import org.kuali.rice.krad.service.KRADServiceLocator; import org.kuali.rice.krad.service.KRADServiceLocatorWeb; import org.kuali.rice.krad.service.LegacyDataAdapter; public class PositionReportGroupKeyWhiteListTest extends PMIntegrationTestCase { private LegacyDataAdapter boService; @Before public void setUp() throws Exception { super.setUp(); boService = KRADServiceLocatorWeb.getLegacyDataAdapter(); } @Test public void testEffectiveKeySetAndListLoad() { PositionReportGroupBo pstnRptGrpBo = boService.findByPrimaryKey(PositionReportGroupBo.class, Collections.singletonMap("pmPositionReportGroupId", "1")); Assert.assertNotNull(pstnRptGrpBo); List<PositionReportGroupKeyBo> effectiveKeyList = pstnRptGrpBo.getEffectiveKeyList(); Assert.assertNotNull(effectiveKeyList); Assert.assertEquals(effectiveKeyList.size(), 2); Set<PositionReportGroupKeyBo> effectiveKeySet = pstnRptGrpBo.getEffectiveKeySet(); Assert.assertNotNull(effectiveKeySet); Assert.assertEquals(effectiveKeySet.size(), 2); Set<String> idSet = new HashSet<String>(); for(PositionReportGroupKeyBo keyBo: effectiveKeySet) { idSet.add(keyBo.getId()); Assert.assertTrue(effectiveKeyList.contains(keyBo)); Assert.assertTrue( ( (keyBo.getId().equals("kpme_neeraj_test_1000")) && (keyBo.getGroupKeyCode().equalsIgnoreCase("ISU-IA")) ) || ( (keyBo.getId().equals("kpme_neeraj_test_1001")) && (keyBo.getGroupKeyCode().equalsIgnoreCase("UGA-GA")) ) ); } Assert.assertTrue(idSet.contains("kpme_neeraj_test_1000")); Assert.assertTrue(idSet.contains("kpme_neeraj_test_1001")); pstnRptGrpBo = boService.findByPrimaryKey(PositionReportGroupBo.class, Collections.singletonMap("pmPositionReportGroupId", "4")); Assert.assertNotNull(pstnRptGrpBo); effectiveKeyList = pstnRptGrpBo.getEffectiveKeyList(); Assert.assertNotNull(effectiveKeyList); Assert.assertEquals(effectiveKeyList.size(), 2); effectiveKeySet = pstnRptGrpBo.getEffectiveKeySet(); Assert.assertNotNull(effectiveKeySet); Assert.assertEquals(effectiveKeySet.size(), 2); idSet = new HashSet<String>(); for(PositionReportGroupKeyBo keyBo: effectiveKeySet) { Assert.assertEquals(keyBo.getOwnerId(), "4"); idSet.add(keyBo.getId()); Assert.assertTrue(effectiveKeyList.contains(keyBo)); Assert.assertTrue( ( (keyBo.getId().equals("kpme_neeraj_test_1002")) && (keyBo.getGroupKeyCode().equalsIgnoreCase("UGA-GA")) ) || ( (keyBo.getId().equals("kpme_neeraj_test_1003")) && (keyBo.getGroupKeyCode().equalsIgnoreCase("IU-IN")) ) ); } Assert.assertTrue(idSet.contains("kpme_neeraj_test_1002")); Assert.assertTrue(idSet.contains("kpme_neeraj_test_1003")); pstnRptGrpBo = boService.findByPrimaryKey(PositionReportGroupBo.class, Collections.singletonMap("pmPositionReportGroupId", "2")); Assert.assertNotNull(pstnRptGrpBo); effectiveKeyList = pstnRptGrpBo.getEffectiveKeyList(); Assert.assertTrue( (effectiveKeyList == null) || effectiveKeyList.isEmpty() ); effectiveKeySet = pstnRptGrpBo.getEffectiveKeySet(); Assert.assertTrue( (effectiveKeySet == null) || effectiveKeySet.isEmpty() ); pstnRptGrpBo = boService.findByPrimaryKey(PositionReportGroupBo.class, Collections.singletonMap("pmPositionReportGroupId", "3")); Assert.assertNotNull(pstnRptGrpBo); effectiveKeyList = pstnRptGrpBo.getEffectiveKeyList(); Assert.assertTrue( (effectiveKeyList == null) || effectiveKeyList.isEmpty() ); effectiveKeySet = pstnRptGrpBo.getEffectiveKeySet(); Assert.assertTrue( (effectiveKeySet == null) || effectiveKeySet.isEmpty() ); } @Test public void testGroupKeySetExtraction() { PositionReportGroupBo pstnRptGrpBo = boService.findByPrimaryKey(PositionReportGroupBo.class, Collections.singletonMap("pmPositionReportGroupId", "1")); Assert.assertFalse(pstnRptGrpBo.getGroupKeySet().isEmpty()); Set<String> extractedGroupKeyCodeWithIdSet = new HashSet<String>(); Set<HrGroupKeyBo> extractedGroupKeySet = pstnRptGrpBo.getGroupKeySet(); for(HrGroupKeyBo extractedGroupKey : extractedGroupKeySet) { extractedGroupKeyCodeWithIdSet.add(extractedGroupKey.getGroupKeyCode() + "-" + extractedGroupKey.getId()); } Assert.assertEquals(extractedGroupKeyCodeWithIdSet.size(), 2); Assert.assertTrue(extractedGroupKeyCodeWithIdSet.contains("ISU-IA-8")); Assert.assertTrue(extractedGroupKeyCodeWithIdSet.contains("UGA-GA-7")); pstnRptGrpBo = boService.findByPrimaryKey(PositionReportGroupBo.class, Collections.singletonMap("pmPositionReportGroupId", "4")); Assert.assertFalse(pstnRptGrpBo.getGroupKeySet().isEmpty()); extractedGroupKeyCodeWithIdSet = new HashSet<String>(); extractedGroupKeySet = pstnRptGrpBo.getGroupKeySet(); for(HrGroupKeyBo extractedGroupKey : extractedGroupKeySet) { extractedGroupKeyCodeWithIdSet.add(extractedGroupKey.getGroupKeyCode() + "-" + extractedGroupKey.getId()); } Assert.assertEquals(extractedGroupKeyCodeWithIdSet.size(), 2); Assert.assertTrue(extractedGroupKeyCodeWithIdSet.contains("IU-IN-5")); Assert.assertTrue(extractedGroupKeyCodeWithIdSet.contains("UGA-GA-7")); pstnRptGrpBo = boService.findByPrimaryKey(PositionReportGroupBo.class, Collections.singletonMap("pmPositionReportGroupId", "2")); extractedGroupKeySet = pstnRptGrpBo.getGroupKeySet(); Assert.assertTrue( (extractedGroupKeySet == null) || extractedGroupKeySet.isEmpty() ); pstnRptGrpBo = boService.findByPrimaryKey(PositionReportGroupBo.class, Collections.singletonMap("pmPositionReportGroupId", "3")); extractedGroupKeySet = pstnRptGrpBo.getGroupKeySet(); Assert.assertTrue( (extractedGroupKeySet == null) || extractedGroupKeySet.isEmpty() ); } @Test public void testGroupKeyCodeSetExtraction() { PositionReportGroupBo pstnRptGrpBo = boService.findByPrimaryKey(PositionReportGroupBo.class, Collections.singletonMap("pmPositionReportGroupId", "1")); Set<String> extractedGroupKeyCodeWithIdSet = pstnRptGrpBo.getGroupKeyCodeSet(); Assert.assertEquals(extractedGroupKeyCodeWithIdSet.size(), 2); Assert.assertTrue(extractedGroupKeyCodeWithIdSet.contains("ISU-IA")); Assert.assertTrue(extractedGroupKeyCodeWithIdSet.contains("UGA-GA")); pstnRptGrpBo = boService.findByPrimaryKey(PositionReportGroupBo.class, Collections.singletonMap("pmPositionReportGroupId", "4")); extractedGroupKeyCodeWithIdSet = pstnRptGrpBo.getGroupKeyCodeSet(); Assert.assertEquals(extractedGroupKeyCodeWithIdSet.size(), 2); Assert.assertTrue(extractedGroupKeyCodeWithIdSet.contains("IU-IN")); Assert.assertTrue(extractedGroupKeyCodeWithIdSet.contains("UGA-GA")); pstnRptGrpBo = boService.findByPrimaryKey(PositionReportGroupBo.class, Collections.singletonMap("pmPositionReportGroupId", "2")); extractedGroupKeyCodeWithIdSet = pstnRptGrpBo.getGroupKeyCodeSet(); Assert.assertTrue( (extractedGroupKeyCodeWithIdSet == null) || extractedGroupKeyCodeWithIdSet.isEmpty() ); pstnRptGrpBo = boService.findByPrimaryKey(PositionReportGroupBo.class, Collections.singletonMap("pmPositionReportGroupId", "3")); extractedGroupKeyCodeWithIdSet = pstnRptGrpBo.getGroupKeyCodeSet(); Assert.assertTrue( (extractedGroupKeyCodeWithIdSet == null) || extractedGroupKeyCodeWithIdSet.isEmpty() ); } @Test public void testKeyCodeSetOwnerAssignment() { PositionReportGroupBo pstnRptGrpBo = boService.findByPrimaryKey(PositionReportGroupBo.class, Collections.singletonMap("pmPositionReportGroupId", "1")); for(PositionReportGroupKeyBo keyBo: pstnRptGrpBo.getEffectiveKeySet()) { Assert.assertEquals(keyBo.getOwnerId(), "1"); } pstnRptGrpBo = boService.findByPrimaryKey(PositionReportGroupBo.class, Collections.singletonMap("pmPositionReportGroupId", "4")); for(PositionReportGroupKeyBo keyBo: pstnRptGrpBo.getEffectiveKeySet()) { Assert.assertEquals(keyBo.getOwnerId(), "4"); } } }
kuali/kpme
pm/impl/src/test/java/org/kuali/kpme/pm/report/group/PositionReportGroupKeyWhiteListTest.java
Java
apache-2.0
9,249
/* * Copyright 2010-2020 Alfresco Software, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.test.matchers; import java.util.List; import java.util.stream.Collectors; import org.activiti.api.process.model.ProcessInstance; import org.activiti.api.process.model.events.ProcessRuntimeEvent; import org.activiti.api.process.runtime.events.ProcessCompletedEvent; import org.activiti.api.process.runtime.events.ProcessCreatedEvent; import org.activiti.api.process.runtime.events.ProcessStartedEvent; import org.activiti.api.task.model.Task; import org.activiti.test.TaskSource; import static org.activiti.api.process.model.events.ProcessRuntimeEvent.ProcessEvents.PROCESS_STARTED; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; public class ProcessInstanceMatchers { private ProcessInstanceMatchers() { } public static ProcessInstanceMatchers processInstance() { return new ProcessInstanceMatchers(); } public OperationScopeMatcher hasBeenStarted() { return (operationScope, events) -> { List<ProcessCreatedEvent> processCreatedEvents = events .stream() .filter(event -> ProcessRuntimeEvent.ProcessEvents.PROCESS_CREATED.equals(event.getEventType())) .map(ProcessCreatedEvent.class::cast) .collect(Collectors.toList()); assertThat(processCreatedEvents) .extracting(event -> event.getEntity().getId()) .as("Unable to find related " + ProcessRuntimeEvent.ProcessEvents.PROCESS_CREATED.name() + " event!") .contains(operationScope.getProcessInstanceId()); List<ProcessStartedEvent> processStartedEvents = events .stream() .filter(event -> ProcessRuntimeEvent.ProcessEvents.PROCESS_STARTED.equals(event.getEventType())) .map(ProcessStartedEvent.class::cast) .collect(Collectors.toList()); assertThat(processStartedEvents) .extracting(event -> event.getEntity().getId()) .as("Unable to find related " + PROCESS_STARTED.name() + " event!") .contains(operationScope.getProcessInstanceId()); }; } public OperationScopeMatcher hasBeenCompleted() { return (operationScope, events) -> { List<ProcessCompletedEvent> processCompletedEvents = events .stream() .filter(event -> ProcessRuntimeEvent.ProcessEvents.PROCESS_COMPLETED.equals(event.getEventType())) .map(ProcessCompletedEvent.class::cast) .collect(Collectors.toList()); assertThat(processCompletedEvents) .extracting(event -> event.getEntity().getId()) .as("Unable to find related " + ProcessRuntimeEvent.ProcessEvents.PROCESS_COMPLETED.name() + " event!") .contains(operationScope.getProcessInstanceId()); }; } public ProcessResultMatcher status(ProcessInstance.ProcessInstanceStatus status){ return (processInstance) -> assertThat(processInstance.getStatus()).isEqualTo(status); } public ProcessResultMatcher name(String name) { return (processInstance) -> assertThat(processInstance.getName()).isEqualTo(name); } public ProcessResultMatcher businessKey(String businessKey) { return (processInstance) -> assertThat(processInstance.getBusinessKey()).isEqualTo(businessKey); } public ProcessTaskMatcher hasTask(String taskName, Task.TaskStatus taskStatus, TaskResultMatcher ... taskResultMatchers) { return (processInstanceId, taskProviders) -> { for (TaskSource provider : taskProviders) { if (provider.canHandle(taskStatus)) { List<Task> tasks = provider.getTasks(processInstanceId); assertThat(tasks) .extracting(Task::getName, Task::getStatus) .contains(tuple(taskName, taskStatus)); Task matchingTask = tasks.stream() .filter(task -> task.getName().equals(taskName)) .findFirst() .orElse(null); if (taskResultMatchers != null) { for (TaskResultMatcher taskResultMatcher : taskResultMatchers) { taskResultMatcher.match(matchingTask); } } } } }; } }
Activiti/Activiti
activiti-core-common/activiti-core-test/activiti-core-test-assertions/src/main/java/org/activiti/test/matchers/ProcessInstanceMatchers.java
Java
apache-2.0
5,411
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.gamelift.model; import java.io.Serializable; /** * <p> * IP addresses and port settings used to limit access by incoming traffic * (players) to a fleet. Permissions specify a range of IP addresses and port * settings that must be used to gain access to a game server on a fleet * machine. * </p> */ public class IpPermission implements Serializable, Cloneable { /** * <p> * Starting value for a range of allowed port numbers. * </p> */ private Integer fromPort; /** * <p> * Ending value for a range of allowed port numbers. Port numbers are * end-inclusive. This value must be higher than <i>FromPort</i>. * </p> */ private Integer toPort; /** * <p> * Range of allowed IP addresses. This value must be expressed in <a * href="https://tools.ietf.org/id/cidr">CIDR notation</a>. Example: " * <code>000.000.000.000/[subnet mask]</code> * " or optionally the shortened version "<code>0.0.0.0/[subnet mask]</code> * ". * </p> */ private String ipRange; /** * <p> * Network communication protocol used by the fleet. * </p> */ private String protocol; /** * <p> * Starting value for a range of allowed port numbers. * </p> * * @param fromPort * Starting value for a range of allowed port numbers. */ public void setFromPort(Integer fromPort) { this.fromPort = fromPort; } /** * <p> * Starting value for a range of allowed port numbers. * </p> * * @return Starting value for a range of allowed port numbers. */ public Integer getFromPort() { return this.fromPort; } /** * <p> * Starting value for a range of allowed port numbers. * </p> * * @param fromPort * Starting value for a range of allowed port numbers. * @return Returns a reference to this object so that method calls can be * chained together. */ public IpPermission withFromPort(Integer fromPort) { setFromPort(fromPort); return this; } /** * <p> * Ending value for a range of allowed port numbers. Port numbers are * end-inclusive. This value must be higher than <i>FromPort</i>. * </p> * * @param toPort * Ending value for a range of allowed port numbers. Port numbers are * end-inclusive. This value must be higher than <i>FromPort</i>. */ public void setToPort(Integer toPort) { this.toPort = toPort; } /** * <p> * Ending value for a range of allowed port numbers. Port numbers are * end-inclusive. This value must be higher than <i>FromPort</i>. * </p> * * @return Ending value for a range of allowed port numbers. Port numbers * are end-inclusive. This value must be higher than * <i>FromPort</i>. */ public Integer getToPort() { return this.toPort; } /** * <p> * Ending value for a range of allowed port numbers. Port numbers are * end-inclusive. This value must be higher than <i>FromPort</i>. * </p> * * @param toPort * Ending value for a range of allowed port numbers. Port numbers are * end-inclusive. This value must be higher than <i>FromPort</i>. * @return Returns a reference to this object so that method calls can be * chained together. */ public IpPermission withToPort(Integer toPort) { setToPort(toPort); return this; } /** * <p> * Range of allowed IP addresses. This value must be expressed in <a * href="https://tools.ietf.org/id/cidr">CIDR notation</a>. Example: " * <code>000.000.000.000/[subnet mask]</code> * " or optionally the shortened version "<code>0.0.0.0/[subnet mask]</code> * ". * </p> * * @param ipRange * Range of allowed IP addresses. This value must be expressed in <a * href="https://tools.ietf.org/id/cidr">CIDR notation</a>. Example: * "<code>000.000.000.000/[subnet mask]</code> * " or optionally the shortened version " * <code>0.0.0.0/[subnet mask]</code>". */ public void setIpRange(String ipRange) { this.ipRange = ipRange; } /** * <p> * Range of allowed IP addresses. This value must be expressed in <a * href="https://tools.ietf.org/id/cidr">CIDR notation</a>. Example: " * <code>000.000.000.000/[subnet mask]</code> * " or optionally the shortened version "<code>0.0.0.0/[subnet mask]</code> * ". * </p> * * @return Range of allowed IP addresses. This value must be expressed in <a * href="https://tools.ietf.org/id/cidr">CIDR notation</a>. Example: * "<code>000.000.000.000/[subnet mask]</code> * " or optionally the shortened version " * <code>0.0.0.0/[subnet mask]</code>". */ public String getIpRange() { return this.ipRange; } /** * <p> * Range of allowed IP addresses. This value must be expressed in <a * href="https://tools.ietf.org/id/cidr">CIDR notation</a>. Example: " * <code>000.000.000.000/[subnet mask]</code> * " or optionally the shortened version "<code>0.0.0.0/[subnet mask]</code> * ". * </p> * * @param ipRange * Range of allowed IP addresses. This value must be expressed in <a * href="https://tools.ietf.org/id/cidr">CIDR notation</a>. Example: * "<code>000.000.000.000/[subnet mask]</code> * " or optionally the shortened version " * <code>0.0.0.0/[subnet mask]</code>". * @return Returns a reference to this object so that method calls can be * chained together. */ public IpPermission withIpRange(String ipRange) { setIpRange(ipRange); return this; } /** * <p> * Network communication protocol used by the fleet. * </p> * * @param protocol * Network communication protocol used by the fleet. * @see IpProtocol */ public void setProtocol(String protocol) { this.protocol = protocol; } /** * <p> * Network communication protocol used by the fleet. * </p> * * @return Network communication protocol used by the fleet. * @see IpProtocol */ public String getProtocol() { return this.protocol; } /** * <p> * Network communication protocol used by the fleet. * </p> * * @param protocol * Network communication protocol used by the fleet. * @return Returns a reference to this object so that method calls can be * chained together. * @see IpProtocol */ public IpPermission withProtocol(String protocol) { setProtocol(protocol); return this; } /** * <p> * Network communication protocol used by the fleet. * </p> * * @param protocol * Network communication protocol used by the fleet. * @return Returns a reference to this object so that method calls can be * chained together. * @see IpProtocol */ public void setProtocol(IpProtocol protocol) { this.protocol = protocol.toString(); } /** * <p> * Network communication protocol used by the fleet. * </p> * * @param protocol * Network communication protocol used by the fleet. * @return Returns a reference to this object so that method calls can be * chained together. * @see IpProtocol */ public IpPermission withProtocol(IpProtocol protocol) { setProtocol(protocol); return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getFromPort() != null) sb.append("FromPort: " + getFromPort() + ","); if (getToPort() != null) sb.append("ToPort: " + getToPort() + ","); if (getIpRange() != null) sb.append("IpRange: " + getIpRange() + ","); if (getProtocol() != null) sb.append("Protocol: " + getProtocol()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof IpPermission == false) return false; IpPermission other = (IpPermission) obj; if (other.getFromPort() == null ^ this.getFromPort() == null) return false; if (other.getFromPort() != null && other.getFromPort().equals(this.getFromPort()) == false) return false; if (other.getToPort() == null ^ this.getToPort() == null) return false; if (other.getToPort() != null && other.getToPort().equals(this.getToPort()) == false) return false; if (other.getIpRange() == null ^ this.getIpRange() == null) return false; if (other.getIpRange() != null && other.getIpRange().equals(this.getIpRange()) == false) return false; if (other.getProtocol() == null ^ this.getProtocol() == null) return false; if (other.getProtocol() != null && other.getProtocol().equals(this.getProtocol()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getFromPort() == null) ? 0 : getFromPort().hashCode()); hashCode = prime * hashCode + ((getToPort() == null) ? 0 : getToPort().hashCode()); hashCode = prime * hashCode + ((getIpRange() == null) ? 0 : getIpRange().hashCode()); hashCode = prime * hashCode + ((getProtocol() == null) ? 0 : getProtocol().hashCode()); return hashCode; } @Override public IpPermission clone() { try { return (IpPermission) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
dump247/aws-sdk-java
aws-java-sdk-gamelift/src/main/java/com/amazonaws/services/gamelift/model/IpPermission.java
Java
apache-2.0
11,474
package com.ktvme.util.email; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * <p>邮件配置</p> * Created by [email protected] on 2017/11/10. */ @Data @AllArgsConstructor @NoArgsConstructor public class EmailConfig { private String smtp = "mail.star-net.cn"; private String from = "[email protected]"; private String user = "kmmo"; private String password = "starnet.&56"; private String to = "[email protected]"; private String cc; }
zheng-zy/zCore
src/main/java/com/ktvme/util/email/EmailConfig.java
Java
apache-2.0
520
/* * $Id: ContentTypeHandlerManagerTest.java 676195 2008-07-12 15:55:58Z mrdon $ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.struts2.rest; import com.mockobjects.dynamic.C; import com.mockobjects.dynamic.Mock; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.config.entities.ActionConfig; import com.opensymphony.xwork2.inject.Container; import junit.framework.TestCase; import org.apache.struts2.ServletActionContext; import org.apache.struts2.rest.handler.ContentTypeHandler; import org.apache.struts2.rest.handler.FormUrlEncodedHandler; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import static javax.servlet.http.HttpServletResponse.SC_NOT_MODIFIED; import static javax.servlet.http.HttpServletResponse.SC_OK; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; public class ContentTypeHandlerManagerTest extends TestCase { private DefaultContentTypeHandlerManager mgr; private MockHttpServletResponse mockResponse; private MockHttpServletRequest mockRequest; @Override public void setUp() { mgr = new DefaultContentTypeHandlerManager(); mockResponse = new MockHttpServletResponse(); mockRequest = new MockHttpServletRequest(); mockRequest.setMethod("GET"); ActionContext.setContext(new ActionContext(new HashMap())); ServletActionContext.setRequest(mockRequest); ServletActionContext.setResponse(mockResponse); } @Override public void tearDown() { mockRequest = null; mockRequest = null; mgr = null; } public void testHandleResultOK() throws IOException { String obj = "mystring"; ContentTypeHandler handler = new ContentTypeHandler() { public void toObject(Reader in, Object target) {} public String fromObject(Object obj, String resultCode, Writer stream) throws IOException { stream.write(obj.toString()); return resultCode; } public String getContentType() { return "foo"; } public String getExtension() { return "foo"; } }; mgr.handlersByExtension.put("xml", handler); mgr.defaultExtension = "xml"; mgr.handleResult(new ActionConfig.Builder("", "", "").build(), new DefaultHttpHeaders().withStatus(SC_OK), obj); assertEquals(obj.getBytes().length, mockResponse.getContentLength()); } public void testHandleResultNotModified() throws IOException { Mock mockHandlerXml = new Mock(ContentTypeHandler.class); mockHandlerXml.matchAndReturn("getExtension", "xml"); mgr.handlersByExtension.put("xml", (ContentTypeHandler) mockHandlerXml.proxy()); mgr.handleResult(null, new DefaultHttpHeaders().withStatus(SC_NOT_MODIFIED), new Object()); assertEquals(0, mockResponse.getContentLength()); } public void testHandlerOverride() { Mock mockHandlerXml = new Mock(ContentTypeHandler.class); mockHandlerXml.matchAndReturn("getExtension", "xml"); mockHandlerXml.matchAndReturn("getContentType", "application/xml"); mockHandlerXml.matchAndReturn("toString", "xml"); Mock mockHandlerJson = new Mock(ContentTypeHandler.class); mockHandlerJson.matchAndReturn("getExtension", "json"); mockHandlerJson.matchAndReturn("getContentType", "application/javascript"); mockHandlerJson.matchAndReturn("toString", "json"); Mock mockHandlerXmlOverride = new Mock(ContentTypeHandler.class); mockHandlerXmlOverride.matchAndReturn("getExtension", "xml"); mockHandlerXmlOverride.matchAndReturn("toString", "xmlOverride"); mockHandlerXmlOverride.matchAndReturn("getContentType", "application/xml"); Mock mockContainer = new Mock(Container.class); mockContainer.matchAndReturn("getInstance", C.args(C.eq(ContentTypeHandler.class), C.eq("xmlOverride")), mockHandlerXmlOverride.proxy()); mockContainer.matchAndReturn("getInstance", C.args(C.eq(ContentTypeHandler.class), C.eq("xml")), mockHandlerXml.proxy()); mockContainer.matchAndReturn("getInstance", C.args(C.eq(ContentTypeHandler.class), C.eq("json")), mockHandlerJson.proxy()); mockContainer.expectAndReturn("getInstanceNames", C.args(C.eq(ContentTypeHandler.class)), new HashSet(Arrays.asList("xml", "xmlOverride", "json"))); mockContainer.matchAndReturn("getInstance", C.args(C.eq(String.class), C.eq(ContentTypeHandlerManager.STRUTS_REST_HANDLER_OVERRIDE_PREFIX+"xml")), "xmlOverride"); mockContainer.expectAndReturn("getInstance", C.args(C.eq(String.class), C.eq(ContentTypeHandlerManager.STRUTS_REST_HANDLER_OVERRIDE_PREFIX+"json")), null); DefaultContentTypeHandlerManager mgr = new DefaultContentTypeHandlerManager(); mgr.setContainer((Container) mockContainer.proxy()); Map<String,ContentTypeHandler> handlers = mgr.handlersByExtension; assertNotNull(handlers); assertEquals(2, handlers.size()); assertEquals(mockHandlerXmlOverride.proxy(), handlers.get("xml")); assertEquals(mockHandlerJson.proxy(), handlers.get("json")); } /** Assert that the request content-type and differ from the response content type */ public void HandleRequestContentType() throws IOException { Mock mockHandlerForm = new Mock(ContentTypeHandler.class); mockHandlerForm.matchAndReturn("getExtension", null); mockHandlerForm.matchAndReturn("getContentType", "application/x-www-form-urlencoded"); mockHandlerForm.matchAndReturn("toString", "x-www-form-urlencoded"); Mock mockHandlerJson = new Mock(ContentTypeHandler.class); mockHandlerJson.matchAndReturn("getExtension", "json"); mockHandlerJson.matchAndReturn("getContentType", "application/javascript"); mockHandlerJson.matchAndReturn("toString", "json"); Mock mockContainer = new Mock(Container.class); mockContainer.matchAndReturn("getInstance", C.args(C.eq(ContentTypeHandler.class), C.eq("x-www-form-urlencoded")), mockHandlerForm.proxy()); mockContainer.expectAndReturn("getInstanceNames", C.args(C.eq(ContentTypeHandler.class)), new HashSet(Arrays.asList("x-www-form-urlencoded", "json"))); mockRequest.setContentType(FormUrlEncodedHandler.CONTENT_TYPE); mockRequest.setContent("a=1&b=2".getBytes("UTF-8")); ContentTypeHandler handler = mgr.getHandlerForRequest(mockRequest); assertEquals("x-www-form-urlencoded", toString()); } }
yuzhongyousida/struts-2.3.1.2
src/plugins/rest/src/test/java/org/apache/struts2/rest/ContentTypeHandlerManagerTest.java
Java
apache-2.0
7,541
package com.nsysmon.server.services; import com.nsysmon.server.storage.ScalarMetaData; import com.nsysmon.server.util.AOption; import com.nsysmon.server.util.json.ListWrapper; /** * @author arno */ public interface AdminService { ListWrapper<String> getMonitoredApplicationNames(); AOption<ScalarMetaData> get(String name); }
dritonshoshi/n-sysmon
n-sysmon-server/src/main/java/com/nsysmon/server/services/AdminService.java
Java
apache-2.0
340
package com.triangleleft.flashcards.di.vocabular; import com.triangleleft.flashcards.di.main.MainPageComponent; import com.triangleleft.flashcards.di.scope.FragmentScope; import com.triangleleft.flashcards.ui.vocabular.VocabularyWordFragment; import com.triangleleft.flashcards.ui.vocabular.VocabularyWordPresenter; import dagger.Component; @FragmentScope @Component(dependencies = MainPageComponent.class) public interface VocabularyWordComponent extends MainPageComponent { VocabularyWordPresenter vocabularWordPresenter(); void inject(VocabularyWordFragment vocabularyWordFragment); }
TriangleLeft/Flashcards
app/src/main/java/com/triangleleft/flashcards/di/vocabular/VocabularyWordComponent.java
Java
apache-2.0
601
package com.seeyoui.kensite.framework.websocket.hndler; import java.io.IOException; import java.util.ArrayList; import org.springframework.stereotype.Component; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.WebSocketMessage; import org.springframework.web.socket.WebSocketSession; import com.seeyoui.kensite.common.constants.StringConstant; @Component public class SystemWebSocketHandler implements WebSocketHandler { private static final ArrayList<WebSocketSession> users; static { users = new ArrayList<>(); } @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { users.add(session); String userName = (String) session.getAttributes().get(StringConstant.WEBSOCKET_USERNAME); if(userName!= null){ //查询未读消息 // int count = webSocketService.getUnReadNews((String) session.getAttributes().get(Constants.WEBSOCKET_USERNAME)); // session.sendMessage(new TextMessage(count + "")); } } @Override public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception { TextMessage textMessage = new TextMessage(message.getPayload().toString()); sendMessageToUsers(textMessage); } @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { if(session.isOpen()){ session.close(); } users.remove(session); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { users.remove(session); } @Override public boolean supportsPartialMessages() { return false; } /** * 给所有在线用户发送消息 * * @param message */ public void sendMessageToUsers(TextMessage message) { for (WebSocketSession user : users) { try { if (user.isOpen()) { user.sendMessage(message); } } catch (IOException e) { e.printStackTrace(); } } } /** * 给某个用户发送消息 * * @param userName * @param message */ public void sendMessageToUser(String userName, TextMessage message) { for (WebSocketSession user : users) { if (user.getAttributes().get(StringConstant.WEBSOCKET_USERNAME).equals(userName)) { try { if (user.isOpen()) { user.sendMessage(message); } } catch (IOException e) { e.printStackTrace(); } break; } } } }
seeyoui/kensite_cms
src/main/java/com/seeyoui/kensite/framework/websocket/hndler/SystemWebSocketHandler.java
Java
apache-2.0
3,031
/* * Copyright 2022 Red Hat * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.hal.core.runtime; /** * Result constants for operations on runtime resources such as server groups, hosts or servers. Not used in DMR operations, but * for the various GWT events. */ public enum Result { SUCCESS, ERROR, TIMEOUT }
michpetrov/hal.next
core/src/main/java/org/jboss/hal/core/runtime/Result.java
Java
apache-2.0
858
/* * Copyright (c) 2005-2008, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.mediation.initializer.utils; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; import java.util.Map; import java.util.HashMap; public class ConfigurationHolder { private static ConfigurationHolder ourInstance = new ConfigurationHolder(); private BundleContext bundleContext; private Map<Integer, ServiceRegistration> synapseRegistrations = new HashMap<Integer, ServiceRegistration>(); public static ConfigurationHolder getInstance() { return ourInstance; } private ConfigurationHolder() { } public BundleContext getBundleContext() { return bundleContext; } public void setBundleContext(BundleContext bundleContext) { this.bundleContext = bundleContext; } public void addSynapseRegistration(int tenanId, ServiceRegistration serviceRegistration) { synapseRegistrations.put(tenanId, serviceRegistration); } public ServiceRegistration getSynapseRegistration(int tenantId) { return synapseRegistrations.get(tenantId); } }
maheshika/carbon-mediation
components/mediation-initializer/org.wso2.carbon.mediation.initializer/src/main/java/org/wso2/carbon/mediation/initializer/utils/ConfigurationHolder.java
Java
apache-2.0
1,797
/******************************************************************************* * Copyright 2014 IUH.CyberSoft Team (http://cyberso.wordpress.com/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package vn.cybersoft.summerms.utils; import java.security.MessageDigest; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; /** * EnCryption and Decryption the data transfer between client-server */ public class SimpleCrypto { public static String encrypt(String seed, String cleartext) throws Exception { if (seed != null) { byte[] rawKey = getRawKey(seed.getBytes()); byte[] result = encrypt(rawKey, cleartext.getBytes()); return toHex(result); } return cleartext; } public static String decrypt(String seed, String encrypted) throws Exception { if (seed != null) { byte[] rawKey = getRawKey(seed.getBytes()); byte[] enc = toByte(encrypted); byte[] result = decrypt(rawKey, enc); return new String(result); } return encrypted; } private static byte[] getRawKey(byte[] seed) throws Exception { // KeyGenerator kgen = KeyGenerator.getInstance("AES"); // SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); // sr.setSeed(seed); // kgen.init(128, sr); // 192 and 256 bits may not be available // SecretKey skey = kgen.generateKey(); // byte[] raw = skey.getEncoded(); // return raw; MessageDigest md = MessageDigest.getInstance("MD5"); return md.digest(seed); } private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(clear); return encrypted; } private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] decrypted = cipher.doFinal(encrypted); return decrypted; } public static String toHex(String txt) { return toHex(txt.getBytes()); } public static String fromHex(String hex) { return new String(toByte(hex)); } public static byte[] toByte(String hexString) { int len = hexString.length() / 2; byte[] result = new byte[len]; for (int i = 0; i < len; i++) result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue(); return result; } public static String toHex(byte[] buf) { if (buf == null) return ""; StringBuffer result = new StringBuffer(2 * buf.length); for (int i = 0; i < buf.length; i++) { appendHex(result, buf[i]); } return result.toString(); } private final static String HEX = "0123456789ABCDEF"; private static void appendHex(StringBuffer sb, byte b) { sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f)); } }
CyberSoftTeam/SummerMobileSecurity
SummerMobileSecurity/src/vn/cybersoft/summerms/utils/SimpleCrypto.java
Java
apache-2.0
3,494
package declarations.interfaces.members; interface Member { void member(); }
dwtj/boa-datagen
src/test/resources/jlssrc/interfaces/members/Member.java
Java
apache-2.0
81
package com.sequenceiq.cloudbreak.shell.customization; import org.springframework.shell.plugin.HistoryFileNameProvider; import org.springframework.stereotype.Component; /** * Specifies the name of the CloudBreak command log. Later this log can be used * to re-execute the commands with either the --cmdfile option at startup * or with the script --file command. */ @Component public class CloudbreakHistory implements HistoryFileNameProvider { @Override public String getHistoryFileName() { return "cloud-break.cbh"; } @Override public String getProviderName() { return "CloudbreakShell"; } }
sequenceiq/cloudbreak
shell/src/main/java/com/sequenceiq/cloudbreak/shell/customization/CloudbreakHistory.java
Java
apache-2.0
641
package com.gh4a.loader; import android.content.Context; import com.gh4a.Gh4Application; import org.eclipse.egit.github.core.Notification; import org.eclipse.egit.github.core.client.PageIterator; import org.eclipse.egit.github.core.service.NotificationService; import java.io.IOException; public class HasNotificationsLoader extends BaseLoader<Boolean> { public HasNotificationsLoader(Context context) { super(context); } @Override public Boolean doLoadInBackground() throws IOException { NotificationService notificationService = (NotificationService) Gh4Application.get().getService(Gh4Application.NOTIFICATION_SERVICE); PageIterator<Notification> notifications = notificationService.pageNotifications(1, false, false); return notifications.hasNext() && !notifications.next().isEmpty(); } }
edyesed/gh4a
app/src/main/java/com/gh4a/loader/HasNotificationsLoader.java
Java
apache-2.0
868
/** Copyright 2008 University of Rochester 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 edu.ur.ir.person.service; import org.springframework.context.ApplicationContext; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.testng.annotations.Test; import edu.ur.ir.person.ContributorType; import edu.ur.ir.person.ContributorTypeService; import edu.ur.ir.repository.service.test.helper.ContextHolder; /** * Test the service methods for contributor service * * @author Nathan Sarr * */ @Test(groups = { "baseTests" }, enabled = true) public class DefaultContributorTypeServiceTest { ApplicationContext ctx = ContextHolder.getApplicationContext(); // Check the repositories PlatformTransactionManager tm = (PlatformTransactionManager) ctx.getBean("transactionManager"); TransactionDefinition td = new DefaultTransactionDefinition( TransactionDefinition.PROPAGATION_REQUIRED); /** contributor type data access */ ContributorTypeService contributorTypeService = (ContributorTypeService) ctx .getBean("contributorTypeService"); /** * Test getting contributor information */ public void testGetContributorType() { TransactionStatus ts = tm.getTransaction(td); // create a contributor type ContributorType contributorType1 = new ContributorType("contributorType1"); contributorType1.setUniqueSystemCode("AUTHOR"); contributorTypeService.save(contributorType1); tm.commit(ts); ts = tm.getTransaction(td); ContributorType other = contributorTypeService.getByUniqueSystemCode(contributorType1.getUniqueSystemCode()); assert other.equals(contributorType1) : " other = " + other + " should equalcontributorType 1 = " + contributorType1; contributorTypeService.delete(other); tm.commit(ts); } }
nate-rcl/irplus
ir_service/test/edu/ur/ir/person/service/DefaultContributorTypeServiceTest.java
Java
apache-2.0
2,594
package com.bagri.tools.vvm.ui; import java.awt.GridLayout; import java.util.logging.Logger; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.JTabbedPane; import com.bagri.tools.vvm.event.ApplicationEvent; import com.bagri.tools.vvm.event.EventBus; import com.bagri.tools.vvm.model.Schema; import com.bagri.tools.vvm.model.SchemaManagement; import com.bagri.tools.vvm.service.SchemaManagementService; public class SchemaPanel extends JPanel { private static final Logger LOGGER = Logger.getLogger(SchemaPanel.class.getName()); private final SchemaManagementService schemaService; private final EventBus eventBus; private final Schema schema; private JTabbedPane tabbedPane; //private XTable grid; public SchemaPanel(SchemaManagementService schemaService, EventBus eventBus, Schema schema) { super(new GridLayout(1, 1)); this.schema = schema; this.schemaService = schemaService; this.eventBus = eventBus; tabbedPane = new JTabbedPane(); tabbedPane.addTab(SchemaManagement.SCHEMA_MANAGEMENT, createSchemaInfoPanel()); tabbedPane.addTab(SchemaManagement.DOCUMENT_MANAGEMENT, createSchemaDocumentsPanel()); tabbedPane.addTab(SchemaManagement.QUERY_MANAGEMENT, createSchemaQueryPanel()); tabbedPane.addTab(SchemaManagement.SCHEMA_MONITORING, createSchemaMonitoringPanel()); add(tabbedPane); tabbedPane.setBorder(BorderFactory.createEmptyBorder()); setBorder(BorderFactory.createEmptyBorder()); } private JPanel createSchemaInfoPanel() { //JPanel panel = new SchemaCapacityPanel(schema.getSchemaName(), schemaService, eventBus); JPanel panel = new SchemaManagementPanel(schema.getSchemaName(), schemaService, eventBus); return panel; } private JPanel createSchemaDocumentsPanel() { JPanel panel = new SchemaDocumentPanel(schema, schemaService, eventBus); return panel; } private JPanel createSchemaMonitoringPanel() { JPanel panel = new SchemaMonitoringPanel(schema.getSchemaName(), schemaService, eventBus); return panel; } private JPanel createSchemaQueryPanel() { JPanel panel = new SchemaQueryPanel(schema, schemaService, eventBus); return panel; } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); // if (!enabled) { // grid.clearSelection(); // grid.getTableHeader().setEnabled(false); // grid.setEnabled(false); // for (Component c : toolBar.getComponents()) { // c.setEnabled(false); // } // toolBar.setEnabled(false); // for (Component c : tabbedPane.getComponents()) { // c.setEnabled(false); // } // tabbedPane.setEnabled(false); // } } @Override public void invalidate() { super.invalidate(); // if (!grid.isLoaded()) { // grid.reload(); // } } }
dsukhoroslov/bagri
bagri-tools/bagri-tools-vvmp/src/main/java/com/bagri/tools/vvm/ui/SchemaPanel.java
Java
apache-2.0
3,069
package pv.com.pvcloudgo.vc.adapter; import android.content.Context; import android.graphics.Point; import android.os.Build; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.animation.OvershootInterpolator; import android.widget.BaseAdapter; import android.widget.ImageView; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import java.io.File; import java.util.ArrayList; import pv.com.pvcloudgo.R; /** * 主页面中GridView的适配器 * * @author hanj */ public class GridImgAdapter extends BaseAdapter { public static String NULL_IMG_PREFIX="NULL_IMG_PREFIX"; private Context context; private ArrayList<String> imagePathList = null; final int mGridWidth; // HashMap<String,Bitmap> mImages; public GridImgAdapter(Context context, ArrayList<String> imagePathList, int column) { this.context = context; this.imagePathList = imagePathList; int width = 0; WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { Point size = new Point(); wm.getDefaultDisplay().getSize(size); width = size.x; } else { width = wm.getDefaultDisplay().getWidth(); } mGridWidth = width / column; // mImages=new HashMap<>(); } @Override public int getCount() { return imagePathList == null ? 0 : imagePathList.size(); } @Override public Object getItem(int position) { return imagePathList.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(final int position, View convertView, ViewGroup parent) { final String filePath = (String) getItem(position); final ViewHolder holder; if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.item_grid_img, null); holder = new ViewHolder(); holder.imageView = (ImageView) convertView.findViewById(R.id.main_gridView_item_photo); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.imageView.setScaleX(0); holder.imageView.setScaleY(0); holder.imageView.setTag(filePath); if (filePath.equals(NULL_IMG_PREFIX)) { Picasso.with(context).load(R.drawable.empty_photo).resize(mGridWidth, mGridWidth) .centerCrop().into(holder.imageView, new Callback() { @Override public void onSuccess() { holder.imageView.animate() .scaleX(1.f).scaleY(1.f) .setInterpolator(new OvershootInterpolator()) .setDuration(400) .setStartDelay(200) .start(); } @Override public void onError() { } }); } else{ Picasso.with(context).load(new File(filePath)).resize(mGridWidth, mGridWidth) .centerCrop().placeholder(R.drawable.empty_photo).into(holder.imageView, new Callback() { @Override public void onSuccess() { holder.imageView.animate() .scaleX(1.f).scaleY(1.f) .setInterpolator(new OvershootInterpolator()) .setDuration(400) .setStartDelay(200) .start(); } @Override public void onError() { } }); // new Thread(new Runnable() { // @Override // public void run() { // try { // mImages.put("img" + position, Picasso.with(context).load(new File(filePath)).get()); // } catch (IOException e) { // e.printStackTrace(); // } // } // }).start(); } return convertView; } private class ViewHolder { ImageView imageView; } public void bind(ArrayList<String> imagePathList) { if (imagePathList == null) return; this.imagePathList = imagePathList; notifyDataSetChanged(); // mImages.clear(); } // public Bitmap getDrawable(int position){ // return mImages.get("img"+position); // } }
weiwenqiang/GitHub
ShoppingCart/PVCloudGroupn-master/app/src/main/java/pv/com/pvcloudgo/vc/adapter/GridImgAdapter.java
Java
apache-2.0
4,749
/* * Copyright 2004 - 2009 University of Cardiff. * * 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.trianacode.taskgraph.tool; import java.io.IOException; /** * Class Description Here... * * @author Andrew Harrison * @version $Revision:$ */ public class ToolException extends IOException { public ToolException() { } public ToolException(String s) { super(s); } }
CSCSI/Triana
triana-core/src/main/java/org/trianacode/taskgraph/tool/ToolException.java
Java
apache-2.0
925
/* * Copyright © 2018 Mercateo AG (http://www.mercateo.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.factcast.store.pgsql.internal.catchup.paged; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import java.util.concurrent.atomic.AtomicLong; import org.factcast.core.subscription.SubscriptionRequestTO; import org.factcast.store.pgsql.PgConfigurationProperties; import org.factcast.store.pgsql.internal.PgConstants; import org.factcast.store.pgsql.internal.catchup.PgCatchUpFetchPage; import org.factcast.store.pgsql.internal.rowmapper.PgIdFactExtractor; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; @ExtendWith(MockitoExtension.class) public class PgCatchUpFetchPageTest { @Mock private JdbcTemplate jdbc; @Mock private PgConfigurationProperties properties; @Mock private SubscriptionRequestTO req; private PgCatchUpFetchPage uut; @Test void testFetchIdFacts() { uut = new PgCatchUpFetchPage(jdbc, properties.getPageSize(), req, 12); uut.fetchIdFacts(new AtomicLong()); verify(jdbc).query(eq(PgConstants.SELECT_ID_FROM_CATCHUP), any( PreparedStatementSetter.class), any(PgIdFactExtractor.class)); } }
uweschaefer/factcast
factcast-store-pgsql/src/test/java/org/factcast/store/pgsql/internal/catchup/paged/PgCatchUpFetchPageTest.java
Java
apache-2.0
2,044