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
package au.com.sensis.sapi.responsemodel; import java.util.List; public class CategoryGroup { private String name; private List<CategoryGroup> children; private List<Category> categories; public String getName() { return name; } public void setName(String name) { this.name = name; } public List<CategoryGroup> getChildren() { return children; } public void setChildren(List<CategoryGroup> children) { this.children = children; } public List<Category> getCategories() { return categories; } public void setCategories(List<Category> categories) { this.categories = categories; } }
ShardPhoenix/SapiClient
src/au/com/sensis/sapi/responsemodel/CategoryGroup.java
Java
apache-2.0
698
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: http://plantuml.com * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2017, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * 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 h; import java.util.Arrays; import java.util.List; import smetana.core.__ptr__; //2 84j0pyfjr7xbsnzkzlwsc5tin public interface colorsegs_t extends __ptr__ { public static List<String> DEFINITION = Arrays.asList( "typedef struct", "{", "int numc", "char* base", "colorseg_t* segs", "}", "colorsegs_t"); } // typedef struct { // int numc; /* number of used segments in segs; may include segs with t == 0 */ // char* base; /* storage of color names */ // colorseg_t* segs; /* array of segments; real segments always followed by a sentinel */ // } colorsegs_t;
Banno/sbt-plantuml-plugin
src/main/java/h/colorsegs_t.java
Java
apache-2.0
2,276
/** * BaseServiceImpl.java */ package com.canzs.lhjz.base.impl; import java.io.Serializable; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate3.HibernateTemplate; import com.canzs.lhjz.base.IBaseService; import com.canzs.lhjz.base.ex.ServiceRuntimeException; import com.canzs.lhjz.component.MessageUtil; /** * 业务逻辑层基类. * * @creation 2013年12月24日 上午11:12:13 * @modification 2013年12月24日 上午11:12:13 * @company Canzs * @author xiweicheng * @version 1.0 * */ public abstract class BaseServiceImpl implements IBaseService { @Autowired protected HibernateTemplate hibernateTemplate; @Autowired protected CommonDao commonDao; @Autowired protected MessageUtil messageUtil; @Override public Serializable save(Object entity) { return hibernateTemplate.save(entity); } @Override public void delete(Object entity) { hibernateTemplate.delete(entity); } @Override public void update(Object entity) { hibernateTemplate.update(entity); } @Override public <T> T get(Class<T> entityClass, Serializable id) { return hibernateTemplate.get(entityClass, id); } @Override public <T> T load(Class<T> entityClass, Serializable id) { return hibernateTemplate.load(entityClass, id); } @Override public List<?> load(Object exampleEntity) { return hibernateTemplate.findByExample(exampleEntity); } @Override public Object findOneByExample(Object example) { List<?> list = hibernateTemplate.findByExample(example); return list.size() > 0 ? list.get(0) : null; } @SuppressWarnings("unchecked") @Override public <T> T findOneByExample(Object example, Class<T> clazz) { List<?> list = hibernateTemplate.findByExample(example); return (T) (list.size() > 0 ? list.get(0) : null); } /** * 当为false时抛出运行时异常. * * @author xiweicheng * @creation 2013年12月30日 下午5:29:14 * @modification 2013年12月30日 下午5:29:14 * @param when * @param exMsg */ protected void throwRuntimeExceptionWhenFalse(boolean when, String exMsg) { if (!when) { throw new ServiceRuntimeException(exMsg); } } /** * 当为真时抛出运行时异常. * * @author xiweicheng * @creation 2013年12月30日 下午5:29:14 * @modification 2013年12月30日 下午5:29:14 * @param when * @param exMsg */ protected void throwRuntimeExceptionWhenTrue(boolean when, String exMsg) { if (when) { throw new ServiceRuntimeException(exMsg); } } /** * 当Object为null时抛出运行时异常. * * @author xiweicheng * @creation 2013年12月30日 下午5:29:14 * @modification 2013年12月30日 下午5:29:14 * @param when * @param exMsg */ protected void throwRuntimeExceptionWhenNull(Object object, String exMsg) { if (object == null) { throw new ServiceRuntimeException(exMsg); } } /** * 抛出运行时异常. * * @author xiweicheng * @creation 2013年12月30日 下午5:29:14 * @modification 2013年12月30日 下午5:29:14 * @param exMsg */ protected void throwRuntimeException(String exMsg) { throw new ServiceRuntimeException(exMsg); } }
czs/lhjz
src/main/java/com/canzs/lhjz/base/impl/BaseServiceImpl.java
Java
apache-2.0
3,188
package com.sequenceiq.it.cloudbreak.testcase.oldinfo; import org.testng.Assert; import org.testng.annotations.Test; import com.sequenceiq.cloudbreak.api.endpoint.v4.util.requests.RepoConfigValidationV4Request; import com.sequenceiq.it.cloudbreak.RepositoryConfigs; import com.sequenceiq.it.cloudbreak.CloudbreakClient; import com.sequenceiq.it.cloudbreak.CloudbreakTest; public class RepositoryConfigsTests extends CloudbreakTest { private static final String VALID_AMBARI_BASE_URL = "http://public-repo-1.hortonworks.com/ambari/centos7/2.x/updates/2.6.1.3"; private static final String VALID_AMBARI_GPGKEY_URL = "http://public-repo-1.hortonworks.com/ambari/centos7/RPM-GPG-KEY/RPM-GPG-KEY-Jenkins"; private static final String VALID_MPACK_URL = "http://private-repo-1.hortonworks.com/HDP/centos7/2.x/updates/2.6.4.5-2/HDP-2.6.4.5-2.xml"; private static final String VALID_STACK_BASE_URL = "http://public-repo-1.hortonworks.com/HDP/centos6/2.x/updates/2.5.5.0/"; private static final String VALID_UTIL_BASE_URL = "http://public-repo-1.hortonworks.com/HDP-UTILS-1.1.0.22/repos/centos7"; private static final String VALID_VERSION_DEF_FILE_URL = "http://public-repo-1.hortonworks.com/HDP/centos7/2.x/updates/2.6.4.0/HDP-2.6.4.0-91.xml"; private static final String INVALID_URL = "www.google.com"; @Test public void testValidAmbariBaseUrl() throws Exception { given(CloudbreakClient.created()); given(RepositoryConfigs.request(createRepoConfigValidationReqest(VALID_AMBARI_BASE_URL, "", "", "", "", ""))); when(RepositoryConfigs.post()); then(RepositoryConfigs.assertThis( (repositoryConfigs, t) -> Assert.assertTrue(repositoryConfigs.getRepoConfigsResponse().getAmbariBaseUrl())) ); } @Test public void testValidAmbariGpgKeyUrl() throws Exception { given(CloudbreakClient.created()); given(RepositoryConfigs.request(createRepoConfigValidationReqest("", VALID_AMBARI_GPGKEY_URL, "", "", "", ""))); when(RepositoryConfigs.post()); then(RepositoryConfigs.assertThis( (repositoryConfigs, t) -> Assert.assertTrue(repositoryConfigs.getRepoConfigsResponse().getAmbariGpgKeyUrl())) ); } @Test() public void testValidMpackUrl() throws Exception { given(CloudbreakClient.created()); given(RepositoryConfigs.request(createRepoConfigValidationReqest("", "", VALID_MPACK_URL, "", "", ""))); when(RepositoryConfigs.post()); then(RepositoryConfigs.assertThis( (repositoryConfigs, t) -> Assert.assertTrue(repositoryConfigs.getRepoConfigsResponse().getMpackUrl())) ); } @Test public void testValidStackBaseUrl() throws Exception { given(CloudbreakClient.created()); given(RepositoryConfigs.request(createRepoConfigValidationReqest("", "", "", VALID_STACK_BASE_URL, "", ""))); when(RepositoryConfigs.post()); then(RepositoryConfigs.assertThis( (repositoryConfigs, t) -> Assert.assertTrue(repositoryConfigs.getRepoConfigsResponse().getStackBaseURL())) ); } @Test public void testValidUtilBaseUrl() throws Exception { given(CloudbreakClient.created()); given(RepositoryConfigs.request(createRepoConfigValidationReqest("", "", "", "", VALID_UTIL_BASE_URL, ""))); when(RepositoryConfigs.post()); then(RepositoryConfigs.assertThis( (repositoryConfigs, t) -> Assert.assertTrue(repositoryConfigs.getRepoConfigsResponse().getUtilsBaseURL())) ); } @Test public void testValidVersionDefFileUrl() throws Exception { given(CloudbreakClient.created()); given(RepositoryConfigs.request(createRepoConfigValidationReqest("", "", "", "", "", VALID_VERSION_DEF_FILE_URL))); when(RepositoryConfigs.post()); then(RepositoryConfigs.assertThis( (repositoryConfigs, t) -> Assert.assertTrue(repositoryConfigs.getRepoConfigsResponse().getVersionDefinitionFileUrl())) ); } @Test public void testValidRepoConfigsAll() throws Exception { given(CloudbreakClient.created()); given(RepositoryConfigs.request(createRepoConfigValidationReqest(VALID_AMBARI_BASE_URL, VALID_AMBARI_GPGKEY_URL, VALID_MPACK_URL, VALID_STACK_BASE_URL, VALID_UTIL_BASE_URL, VALID_VERSION_DEF_FILE_URL))); when(RepositoryConfigs.post()); then(RepositoryConfigs.assertAllTrue()); } @Test public void testInvalidRepoConfigsAllEmpty() throws Exception { given(CloudbreakClient.created()); given(RepositoryConfigs.request(createRepoConfigValidationReqest("", "", "", "", "", ""))); when(RepositoryConfigs.post()); then(RepositoryConfigs.assertAllNull()); } @Test public void testInvalidRepoConfigsAllInvalid() throws Exception { given(CloudbreakClient.created()); given(RepositoryConfigs.request(createRepoConfigValidationReqest("a", "a", "a", "a", "a", "a"))); when(RepositoryConfigs.post()); then(RepositoryConfigs.assertAllFalse()); } @Test public void testInvalidRepoConfigsAllNotAvailable() throws Exception { given(CloudbreakClient.created()); given(RepositoryConfigs.request(createRepoConfigValidationReqest(INVALID_URL, INVALID_URL, INVALID_URL, INVALID_URL, INVALID_URL, INVALID_URL))); when(RepositoryConfigs.post()); then(RepositoryConfigs.assertAllFalse()); } private RepoConfigValidationV4Request createRepoConfigValidationReqest(String ambariBaseUrl, String ambariGpgKeyUrl, String mPackUrl, String stackBaseUrl, String utilsBaseUrl, String versionDefinitionFileUrl) { RepoConfigValidationV4Request repoConfigValidationV4Request = new RepoConfigValidationV4Request(); repoConfigValidationV4Request.setAmbariBaseUrl(ambariBaseUrl); repoConfigValidationV4Request.setAmbariGpgKeyUrl(ambariGpgKeyUrl); repoConfigValidationV4Request.setMpackUrl(mPackUrl); repoConfigValidationV4Request.setStackBaseURL(stackBaseUrl); repoConfigValidationV4Request.setUtilsBaseURL(utilsBaseUrl); repoConfigValidationV4Request.setVersionDefinitionFileUrl(versionDefinitionFileUrl); return repoConfigValidationV4Request; } }
hortonworks/cloudbreak
integration-test/src/main/java/com/sequenceiq/it/cloudbreak/testcase/oldinfo/RepositoryConfigsTests.java
Java
apache-2.0
6,476
package simmk.event; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.Timer; import java.util.Observable; public class Pulse extends Observable implements ActionListener { Timer timer; static int counter = 0; public Pulse(int delay) { timer = new Timer(delay, this); } public void start() { System.out.println("Starting timer"); timer.start(); } public void stop() { timer.stop(); } @Override public void actionPerformed(ActionEvent ae) { setChanged(); this.notifyObservers(ae); } }
marckirschner/Springy
src/simmk/event/Pulse.java
Java
apache-2.0
625
package com.anybeen.mark.imageeditor.view; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.RadialGradient; import android.graphics.Rect; import android.graphics.Shader; import android.os.Build; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import com.anybeen.mark.yinjiimageeditorlibrary.R; //0xFF000000,0xFF9900FF, 0xFF0000FF, 0xFF00FF00, // 0xFF00FFFF, 0xFFFF0000,0xFFFF00FF,0xFFFF6600, 0xFFFFFF00, 0xFFFFFFFF,0xFF000000 public class ColorSeekBar extends View { private int mBackgroundColor = 0xffffffff; private int[] mColors = new int[] {0xFF000000, 0xFFF44336, 0xFF9C27B0, 0xFF3F51B5, 0xFF009688, 0xFFFFEB3B, 0xFFFF9800, 0xFF795548, 0xFF607D8B, 0xFF607D8B}; private int c0,c1, mAlpha, mRed, mGreen, mBlue; private float x,y; private OnColorChangeListener mOnColorChangeLister; private Context mContext; private boolean mIsShowAlphaBar = false; private Bitmap mTransparentBitmap; private boolean mMovingColorBar; private boolean mMovingAlphaBar; private Rect mColorRect; private int mThumbHeight = 20; private int mBarHeight = 2; private LinearGradient mColorGradient; private Paint mColorRectPaint; private int realLeft; private int realRight; private int realTop; private int realBottom; private int mBarWidth; private int mMaxValue; private Rect mAlphaRect; private int mColorBarValue; private int mAlphaBarValue; private float mThumbRadius; private int mBarMargin = 5; private int mPaddingSize; private int mViewWidth; private int mViewHeight; public ColorSeekBar(Context context) { super(context); init(context, null, 0, 0); } public ColorSeekBar(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs, 0, 0); } public ColorSeekBar(Context context, AttributeSet attrs, int defStyleAttr){ super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr, 0); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public ColorSeekBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context, attrs, defStyleAttr, defStyleRes); } protected void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes){ applyStyle(context, attrs, defStyleAttr, defStyleRes); } public void applyStyle(int resId){ applyStyle(getContext(), null, 0, resId); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); mViewWidth = widthMeasureSpec; mViewHeight = heightMeasureSpec; int speMode = MeasureSpec.getMode(heightMeasureSpec); if(speMode == MeasureSpec.AT_MOST){ if(mIsShowAlphaBar){ setMeasuredDimension(mViewWidth,mThumbHeight * 2 + mBarHeight * 2 + mBarMargin); }else{ setMeasuredDimension(mViewWidth,mThumbHeight + mBarHeight); } } } protected void applyStyle(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes){ mContext = context; //get attributes TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ColorSeekBar, defStyleAttr, defStyleRes); int colorsId = a.getResourceId(R.styleable.ColorSeekBar_colors, 0); mMaxValue = a.getInteger(R.styleable.ColorSeekBar_maxValue,100); mColorBarValue = a.getInteger(R.styleable.ColorSeekBar_colorBarValue,0); mAlphaBarValue = a.getInteger(R.styleable.ColorSeekBar_alphaBarValue,0); mIsShowAlphaBar = a.getBoolean(R.styleable.ColorSeekBar_showAlphaBar, false); mBackgroundColor = a.getColor(R.styleable.ColorSeekBar_bgColor, Color.TRANSPARENT); mBarHeight = (int)a.getDimension(R.styleable.ColorSeekBar_barHeight,(float)dp2px(4)); mThumbHeight = (int)a.getDimension(R.styleable.ColorSeekBar_thumbHeight,(float)dp2px(30)); mBarMargin = (int)a.getDimension(R.styleable.ColorSeekBar_barMargin,(float)dp2px(0)); a.recycle(); if(colorsId != 0) mColors = getColorsById(colorsId); setBackgroundColor(mBackgroundColor); init(); //init color pickColor(mColorBarValue); setAlphaValue(); } /** * * @param id * @return */ private int[] getColorsById(int id){ if(isInEditMode()){ String[] s=mContext.getResources().getStringArray(id); int[] colors = new int[s.length]; for (int j = 0; j < s.length; j++){ colors[j] = Color.parseColor(s[j]); } return colors; }else{ TypedArray typedArray=mContext.getResources().obtainTypedArray(id); int[] colors = new int[typedArray.length()]; for (int j = 0; j < typedArray.length(); j++){ colors[j] = typedArray.getColor(j,Color.BLACK); } typedArray.recycle(); return colors; } } private void init() { //init l r t b realLeft = getPaddingLeft() + mPaddingSize; realRight = getWidth() - getPaddingRight() - mPaddingSize; realTop = getPaddingTop() + mPaddingSize; realBottom = getHeight() - getPaddingBottom() - mPaddingSize; //init size mThumbRadius = mThumbHeight / 2; mPaddingSize = (int)mThumbRadius; mBarWidth = realRight - realLeft; //init rect mColorRect = new Rect(realLeft ,realTop,realRight,realTop + mBarHeight); // 创建LinearGradient并设置渐变颜色数组 // 第一个,第二个参数表示渐变起点 可以设置起点终点在对角等任意位置 // 第三个,第四个参数表示渐变终点 // 第五个参数表示渐变颜色 // 第六个参数可以为空,表示坐标,值为0-1 new float[] {0.25f, 0.5f, 0.75f, 1 } // 如果这是 null 空的,颜色均匀分布,沿梯度线。 // 第七个表示平铺方式 // CLAMP重复最后一个颜色至最后 // MIRROR重复着色的图像水平或垂直方向已镜像方式填充会有翻转效果 // REPEAT重复着色的图像水平或垂直方向 //init paint mColorGradient = new LinearGradient(0, 0, mColorRect.width(), 0, mColors, null, Shader.TileMode.MIRROR); mColorRectPaint = new Paint(); mColorRectPaint.setShader(mColorGradient); mColorRectPaint.setAntiAlias(true); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mTransparentBitmap = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_4444); mTransparentBitmap.eraseColor(Color.TRANSPARENT); } public ColorSeekBar(Context context, float x1, float x2) { super(context); } @Override protected void onDraw(Canvas canvas) { init(); float colorPosition = (float) mColorBarValue / mMaxValue * mBarWidth; Paint colorPaint = new Paint(); colorPaint.setAntiAlias(true); colorPaint.setColor(pickColor(colorPosition)); int[] toAlpha=new int[]{Color.argb(255, mRed, mGreen, mBlue),Color.argb(0, mRed, mGreen, mBlue)}; //clear canvas.drawBitmap(mTransparentBitmap,0,0,null); //draw color bar canvas.drawRect(mColorRect, mColorRectPaint); //draw color bar thumb float thumbX = colorPosition + realLeft; float thumbY = mColorRect.top + mColorRect.height() / 2; canvas.drawCircle(thumbX,thumbY , mBarHeight / 2 + 5, colorPaint); //draw color bar thumb radial gradient shader RadialGradient thumbShader = new RadialGradient(thumbX, thumbY, mThumbRadius, toAlpha, null, Shader.TileMode.MIRROR); Paint thumbGradientPaint = new Paint(); thumbGradientPaint.setAntiAlias(true); thumbGradientPaint.setShader(thumbShader); canvas.drawCircle(thumbX, thumbY, mThumbHeight / 2, thumbGradientPaint); if(mIsShowAlphaBar){ //init rect int top = (int)(mThumbHeight+ mThumbRadius + mBarHeight + mBarMargin); mAlphaRect = new Rect(realLeft,top,realRight,top + mBarHeight); //draw alpha bar Paint alphaBarPaint = new Paint(); alphaBarPaint.setAntiAlias(true); LinearGradient alphaBarShader = new LinearGradient(0, 0, mAlphaRect.width(), 0, toAlpha, null, Shader.TileMode.MIRROR); alphaBarPaint.setShader(alphaBarShader); canvas.drawRect(mAlphaRect,alphaBarPaint); //draw alpha bar thumb float alphaPosition = (float) mAlphaBarValue / 255 * mBarWidth; float alphaThumbX = alphaPosition + realLeft; float alphaThumbY = mAlphaRect.top + mAlphaRect.height() / 2; canvas.drawCircle(alphaThumbX, alphaThumbY, mBarHeight / 2 + 5, colorPaint); //draw alpha bar thumb radial gradient shader RadialGradient alphaThumbShader = new RadialGradient(alphaThumbX, alphaThumbY, mThumbRadius, toAlpha, null, Shader.TileMode.MIRROR); Paint alphaThumbGradientPaint = new Paint(); alphaThumbGradientPaint.setAntiAlias(true); alphaThumbGradientPaint.setShader(alphaThumbShader); canvas.drawCircle(alphaThumbX,alphaThumbY, mThumbHeight/2, alphaThumbGradientPaint); } super.onDraw(canvas); } @Override public boolean onTouchEvent(MotionEvent event) { x = event.getX(); y = event.getY(); switch(event.getAction()){ case MotionEvent.ACTION_DOWN: if(isOnBar(mColorRect, x, y)){ mMovingColorBar = true; }else if(mIsShowAlphaBar){ if(isOnBar(mAlphaRect, x, y)){ mMovingAlphaBar = true; } } break; case MotionEvent.ACTION_MOVE: if(mMovingColorBar){ float value = (x - realLeft) / mBarWidth * mMaxValue; mColorBarValue =(int)value ; if (mColorBarValue < 0) mColorBarValue = 0; if (mColorBarValue > mMaxValue) mColorBarValue = mMaxValue; }else if(mIsShowAlphaBar){ if(mMovingAlphaBar){ float value = (x - realLeft) / mBarWidth * 255; mAlphaBarValue = (int)value; if (mAlphaBarValue < 0 ) mAlphaBarValue = 0; if (mAlphaBarValue > 255 ) mAlphaBarValue = 255; setAlphaValue(); } } if(mOnColorChangeLister != null && (mMovingAlphaBar || mMovingColorBar)) mOnColorChangeLister.onColorChangeListener(mColorBarValue, mAlphaBarValue,getColor()); invalidate(); break; case MotionEvent.ACTION_UP: mMovingColorBar = false; mMovingAlphaBar = false; break; } return true; } /** * * @param r * @param x * @param y * @return whether MotionEvent is performing on bar or not */ private boolean isOnBar(Rect r, float x, float y){ if(r.left - mThumbRadius < x && x < r.right + mThumbRadius && r.top - mThumbRadius < y && y < r.bottom + mThumbRadius){ return true; }else{ return false; } } /** * * @param position * @return color */ private int pickColor(float position) { float unit = position / mBarWidth; if (unit <= 0.0) return mColors[0]; if (unit >= 1) return mColors[mColors.length - 1]; float colorPosition = unit * (mColors.length - 1); int i = (int)colorPosition; colorPosition -= i; c0 = mColors[i]; c1 = mColors[i+1]; // mAlpha = mix(Color.alpha(c0), Color.alpha(c1), colorPosition); mRed = mix(Color.red(c0), Color.red(c1), colorPosition); mGreen = mix(Color.green(c0), Color.green(c1), colorPosition); mBlue = mix(Color.blue(c0), Color.blue(c1), colorPosition); return Color.rgb( mRed, mGreen, mBlue); } /** * * @param start * @param end * @param position  * @return */ private int mix(int start, int end, float position) { return start + Math.round(position * (end - start)); } public int getColor() { if(mIsShowAlphaBar) return Color.argb(mAlpha, mRed, mGreen, mBlue); return Color.rgb( mRed, mGreen, mBlue); } public int getAlphaValue(){ return mAlpha; } /** * @return color with alpha value */ public int getColorWithAlpha(){ return Color.argb(mAlpha, mRed, mGreen, mBlue); } public interface OnColorChangeListener { /** * @param colorBarValue between 0-maxValue * @param alphaValue between 0-255 * @param color return the color contains alpha value whether showAlphaBar is true or without alpha value */ public void onColorChangeListener(int colorBarValue, int alphaValue, int color); } /** * @param onColorChangeListener */ public void setOnColorChangeListener(OnColorChangeListener onColorChangeListener){ this.mOnColorChangeLister = onColorChangeListener; } public int dp2px(float dpValue) { final float scale = mContext.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** * Set colors by resource id. The resource's type must be color * @param resId */ public void setColors(int resId){ setColors(getColorsById(resId)); } public void setColors(int[] colors){ mColors = colors; invalidate(); setAlphaValue(); if(mOnColorChangeLister != null) mOnColorChangeLister.onColorChangeListener(mColorBarValue, mAlphaBarValue,getColor()); } public int[] getColors(){ return mColors; } public boolean isShowAlphaBar(){ return mIsShowAlphaBar; } private void refreshLayoutParams(){ mThumbHeight = mThumbHeight < 2? 2:mThumbHeight; mBarHeight = mBarHeight < 2? 2:mBarHeight; int singleHeight = mThumbHeight + mBarHeight; int doubleHeight = mThumbHeight *2 + mBarHeight * 2 + mBarMargin; if(getLayoutParams().height == -2) { if(mIsShowAlphaBar){ getLayoutParams().height = doubleHeight; setLayoutParams(getLayoutParams()); }else{ getLayoutParams().height = singleHeight ; setLayoutParams(getLayoutParams()); } }else if (getLayoutParams().height >= 0){ if(mIsShowAlphaBar){ getLayoutParams().height = doubleHeight; setLayoutParams(getLayoutParams()); }else{ getLayoutParams().height = singleHeight; setLayoutParams(getLayoutParams()); } } } public void setShowAlphaBar(boolean show){ mIsShowAlphaBar = show; refreshLayoutParams(); invalidate(); if(mOnColorChangeLister != null) mOnColorChangeLister.onColorChangeListener(mColorBarValue, mAlphaBarValue,getColor()); } /** * @param dp */ public void setBarHeight(float dp){ mBarHeight = dp2px(dp); refreshLayoutParams(); invalidate(); } /** * @param px */ public void setBarHeightPx(int px){ mBarHeight = px; refreshLayoutParams(); invalidate(); } private void setAlphaValue(){ mAlpha = 255 - mAlphaBarValue; } public void setAlphaBarValue(int value) { this.mAlphaBarValue = value; setAlphaValue(); invalidate(); } public int getMaxValue() { return mMaxValue; } public void setMaxValue(int value) { this.mMaxValue = value; invalidate(); } /** * set margin between bars * @param mBarMargin */ public void setBarMargin(float mBarMargin) { this.mBarMargin = dp2px(mBarMargin); refreshLayoutParams(); invalidate(); } /** * set margin between bars * @param mBarMargin */ public void setBarMarginPx(int mBarMargin) { this.mBarMargin = mBarMargin; refreshLayoutParams(); invalidate(); } /** * Set the value of color bar, if out of bounds , it will be 0 or maxValue; * @param value */ public void setColorBarValue(int value) { this.mColorBarValue = value; invalidate(); if(mOnColorChangeLister != null) mOnColorChangeLister.onColorChangeListener(mColorBarValue, mAlphaBarValue,getColor()); } /** * set thumb's height by dpi * @param dp */ public void setThumbHeight(float dp) { this.mThumbHeight = dp2px(dp); refreshLayoutParams(); invalidate(); } /** * set thumb's height by pixels * @param px */ public void setThumbHeightPx(int px) { this.mThumbHeight = px; refreshLayoutParams(); invalidate(); } public int getBarHeight() { return mBarHeight; } public int getThumbHeight() { return mThumbHeight; } public int getBarMargin() { return mBarMargin; } public float getColorPosition() { return mColorBarValue; } }
dyzs/YinjiImageEditor
YinjiImageEditorLibrary/src/main/java/com/anybeen/mark/imageeditor/view/ColorSeekBar.java
Java
apache-2.0
15,834
/******************************************************************************* * Copyright 2017 General Electric Company * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.ge.predix.cloudfoundry.client; import org.apache.commons.lang3.StringUtils; import org.cloudfoundry.client.CloudFoundryClient; import org.cloudfoundry.operations.CloudFoundryOperations; import org.cloudfoundry.operations.DefaultCloudFoundryOperations; import org.cloudfoundry.reactor.ConnectionContext; import org.cloudfoundry.reactor.DefaultConnectionContext; import org.cloudfoundry.reactor.ProxyConfiguration; import org.cloudfoundry.reactor.TokenProvider; import org.cloudfoundry.reactor.client.ReactorCloudFoundryClient; import org.cloudfoundry.reactor.tokenprovider.PasswordGrantTokenProvider; public final class CloudFoundryConfiguration { private CloudFoundryConfiguration() { throw new AssertionError(); } public static ConnectionContext connectionContext(final String apiHost, final String proxyHost, final Integer proxyPort) { DefaultConnectionContext.Builder connectionContext = DefaultConnectionContext.builder() .apiHost(apiHost) .skipSslValidation(false); if (StringUtils.isNotEmpty(proxyHost)) { ProxyConfiguration.Builder proxyConfiguration = ProxyConfiguration.builder() .host(proxyHost) .port(proxyPort); connectionContext.proxyConfiguration(proxyConfiguration.build()); } return connectionContext.build(); } public static PasswordGrantTokenProvider tokenProvider(final String password, final String username) { return PasswordGrantTokenProvider.builder() .password(password) .username(username) .build(); } public static CloudFoundryClient cloudFoundryClient(final ConnectionContext connectionContext, final TokenProvider tokenProvider) { return ReactorCloudFoundryClient.builder() .connectionContext(connectionContext) .tokenProvider(tokenProvider) .build(); } public static CloudFoundryOperations cloudFoundryOperations(final CloudFoundryClient cloudFoundryClient, final String organizationName, final String spaceName) { return DefaultCloudFoundryOperations.builder() .cloudFoundryClient(cloudFoundryClient) .organization(organizationName) .space(spaceName) .build(); } }
predix/acs
acs-integration-tests/src/test/java/com/ge/predix/cloudfoundry/client/CloudFoundryConfiguration.java
Java
apache-2.0
3,181
package org.gaixie.jibu.json; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; /* Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * A JSONTokener takes a source string and extracts characters and tokens from * it. It is used by the JSONObject and JSONArray constructors to parse * JSON source strings. * @author JSON.org * @version 2008-09-18 */ public class JSONTokener { private int index; private Reader reader; private char lastChar; private boolean useLastChar; /** * Construct a JSONTokener from a string. * * @param reader A reader. */ public JSONTokener(Reader reader) { this.reader = reader.markSupported() ? reader : new BufferedReader(reader); this.useLastChar = false; this.index = 0; } /** * Construct a JSONTokener from a string. * * @param s A source string. */ public JSONTokener(String s) { this(new StringReader(s)); } /** * Back up one character. This provides a sort of lookahead capability, * so that you can test for a digit or letter before attempting to parse * the next number or identifier. */ public void back() throws JSONException { if (useLastChar || index <= 0) { throw new JSONException("Stepping back two steps is not supported"); } index -= 1; useLastChar = true; } /** * Get the hex value of a character (base16). * @param c A character between '0' and '9' or between 'A' and 'F' or * between 'a' and 'f'. * @return An int between 0 and 15, or -1 if c was not a hex digit. */ public static int dehexchar(char c) { if (c >= '0' && c <= '9') { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - ('A' - 10); } if (c >= 'a' && c <= 'f') { return c - ('a' - 10); } return -1; } /** * Determine if the source string still contains characters that next() * can consume. * @return true if not yet at the end of the source. */ public boolean more() throws JSONException { char nextChar = next(); if (nextChar == 0) { return false; } back(); return true; } /** * Get the next character in the source string. * * @return The next character, or 0 if past the end of the source string. */ public char next() throws JSONException { if (this.useLastChar) { this.useLastChar = false; if (this.lastChar != 0) { this.index += 1; } return this.lastChar; } int c; try { c = this.reader.read(); } catch (IOException exc) { throw new JSONException(exc); } if (c <= 0) { // End of stream this.lastChar = 0; return 0; } this.index += 1; this.lastChar = (char) c; return this.lastChar; } /** * Consume the next character, and check that it matches a specified * character. * @param c The character to match. * @return The character. * @throws JSONException if the character does not match. */ public char next(char c) throws JSONException { char n = next(); if (n != c) { throw syntaxError("Expected '" + c + "' and instead saw '" + n + "'"); } return n; } /** * Get the next n characters. * * @param n The number of characters to take. * @return A string of n characters. * @throws JSONException * Substring bounds error if there are not * n characters remaining in the source string. */ public String next(int n) throws JSONException { if (n == 0) { return ""; } char[] buffer = new char[n]; int pos = 0; if (this.useLastChar) { this.useLastChar = false; buffer[0] = this.lastChar; pos = 1; } try { int len; while ((pos < n) && ((len = reader.read(buffer, pos, n - pos)) != -1)) { pos += len; } } catch (IOException exc) { throw new JSONException(exc); } this.index += pos; if (pos < n) { throw syntaxError("Substring bounds error"); } this.lastChar = buffer[n - 1]; return new String(buffer); } /** * Get the next char in the string, skipping whitespace. * @throws JSONException * @return A character, or 0 if there are no more characters. */ public char nextClean() throws JSONException { for (;;) { char c = next(); if (c == 0 || c > ' ') { return c; } } } /** * Return the characters up to the next close quote character. * Backslash processing is done. The formal JSON format does not * allow strings in single quotes, but an implementation is allowed to * accept them. * @param quote The quoting character, either * <code>"</code>&nbsp;<small>(double quote)</small> or * <code>'</code>&nbsp;<small>(single quote)</small>. * @return A String. * @throws JSONException Unterminated string. */ public String nextString(char quote) throws JSONException { char c; StringBuffer sb = new StringBuffer(); for (;;) { c = next(); switch (c) { case 0: case '\n': case '\r': throw syntaxError("Unterminated string"); case '\\': c = next(); switch (c) { case 'b': sb.append('\b'); break; case 't': sb.append('\t'); break; case 'n': sb.append('\n'); break; case 'f': sb.append('\f'); break; case 'r': sb.append('\r'); break; case 'u': sb.append((char)Integer.parseInt(next(4), 16)); break; case '"': case '\'': case '\\': case '/': sb.append(c); break; default: throw syntaxError("Illegal escape."); } break; default: if (c == quote) { return sb.toString(); } sb.append(c); } } } /** * Get the text up but not including the specified character or the * end of line, whichever comes first. * @param d A delimiter character. * @return A string. */ public String nextTo(char d) throws JSONException { StringBuffer sb = new StringBuffer(); for (;;) { char c = next(); if (c == d || c == 0 || c == '\n' || c == '\r') { if (c != 0) { back(); } return sb.toString().trim(); } sb.append(c); } } /** * Get the text up but not including one of the specified delimiter * characters or the end of line, whichever comes first. * @param delimiters A set of delimiter characters. * @return A string, trimmed. */ public String nextTo(String delimiters) throws JSONException { char c; StringBuffer sb = new StringBuffer(); for (;;) { c = next(); if (delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r') { if (c != 0) { back(); } return sb.toString().trim(); } sb.append(c); } } /** * Get the next value. The value can be a Boolean, Double, Integer, * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. * @throws JSONException If syntax error. * * @return An object. */ public Object nextValue() throws JSONException { char c = nextClean(); String s; switch (c) { case '"': case '\'': return nextString(c); case '{': back(); return new JSONObject(this); case '[': case '(': back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = next(); } back(); s = sb.toString().trim(); if (s.equals("")) { throw syntaxError("Missing value"); } return JSONObject.stringToValue(s); } /** * Skip characters until the next character is the requested character. * If the requested character is not found, no characters are skipped. * @param to A character to skip to. * @return The requested character, or zero if the requested character * is not found. */ public char skipTo(char to) throws JSONException { char c; try { int startIndex = this.index; reader.mark(Integer.MAX_VALUE); do { c = next(); if (c == 0) { reader.reset(); this.index = startIndex; return c; } } while (c != to); } catch (IOException exc) { throw new JSONException(exc); } back(); return c; } /** * Make a JSONException to signal a syntax error. * * @param message The error message. * @return A JSONException object, suitable for throwing */ public JSONException syntaxError(String message) { return new JSONException(message + toString()); } /** * Make a printable string of this JSONTokener. * * @return " at character [this.index]" */ public String toString() { return " at character " + index; } }
cloudscode/jibu
plugins/jibu-json/src/main/java/org/gaixie/jibu/json/JSONTokener.java
Java
apache-2.0
12,025
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.psi.impl.java.stubs; import com.intellij.lang.ASTNode; import com.intellij.lang.LighterAST; import com.intellij.lang.LighterASTNode; import com.intellij.psi.JavaTokenType; import com.intellij.psi.PsiParameter; import com.intellij.psi.impl.cache.RecordUtil; import com.intellij.psi.impl.cache.TypeInfo; import com.intellij.psi.impl.java.stubs.impl.PsiParameterStubImpl; import com.intellij.psi.impl.source.PsiParameterImpl; import com.intellij.psi.impl.source.tree.JavaElementType; import com.intellij.psi.impl.source.tree.LightTreeUtil; import com.intellij.psi.impl.source.tree.java.ParameterElement; import com.intellij.psi.stubs.IndexSink; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import javax.annotation.Nonnull; import java.io.IOException; /** * @author max */ public class JavaParameterElementType extends JavaStubElementType<PsiParameterStub, PsiParameter> { public JavaParameterElementType() { super("PARAMETER"); } @Nonnull @Override public ASTNode createCompositeNode() { return new ParameterElement(JavaElementType.PARAMETER); } @Override public PsiParameter createPsi(@Nonnull PsiParameterStub stub) { return getPsiFactory(stub).createParameter(stub); } @Override public PsiParameter createPsi(@Nonnull ASTNode node) { return new PsiParameterImpl(node); } @Nonnull @Override public PsiParameterStub createStub(@Nonnull LighterAST tree, @Nonnull LighterASTNode node, @Nonnull StubElement parentStub) { TypeInfo typeInfo = TypeInfo.create(tree, node, parentStub); LighterASTNode id = LightTreeUtil.requiredChildOfType(tree, node, JavaTokenType.IDENTIFIER); String name = RecordUtil.intern(tree.getCharTable(), id); return new PsiParameterStubImpl(parentStub, name, typeInfo, typeInfo.isEllipsis, false); } @Override public void serialize(@Nonnull PsiParameterStub stub, @Nonnull StubOutputStream dataStream) throws IOException { dataStream.writeName(stub.getName()); TypeInfo.writeTYPE(dataStream, stub.getType()); dataStream.writeByte(((PsiParameterStubImpl) stub).getFlags()); } @Nonnull @Override public PsiParameterStub deserialize(@Nonnull StubInputStream dataStream, StubElement parentStub) throws IOException { String name = dataStream.readNameString(); if(name == null) throw new IOException("corrupted indices"); TypeInfo type = TypeInfo.readTYPE(dataStream); byte flags = dataStream.readByte(); return new PsiParameterStubImpl(parentStub, name, type, flags); } @Override public void indexStub(@Nonnull PsiParameterStub stub, @Nonnull IndexSink sink) { } }
consulo/consulo-java
java-psi-impl/src/main/java/com/intellij/psi/impl/java/stubs/JavaParameterElementType.java
Java
apache-2.0
2,814
package net.safedata.springboot.training.d02.s04.dto; import net.safedata.springboot.training.d02.s04.model.Product; import java.io.Serializable; import java.util.Objects; /** * A DTO (Data Transfer Object) used to serialize / deserialize {@link Product} objects * * @author bogdan.solga */ public class ProductDTO implements Serializable { private static final long serialVersionUID = 1L; private final int id; private final String productName; public ProductDTO(final int id, final String productName) { this.id = id; this.productName = productName; } public int getId() { return id; } public String getProductName() { return productName; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ProductDTO)) return false; ProductDTO that = (ProductDTO) o; return id == that.id && Objects.equals(productName, that.productName); } @Override public int hashCode() { return Objects.hash(id, productName); } }
bogdansolga/spring-boot-training
d02/d02s04-exception-handling/src/main/java/net/safedata/springboot/training/d02/s04/dto/ProductDTO.java
Java
apache-2.0
1,096
package com.oldbai.android.app.hebiace; /** * Created by BaiGuoyong on 9/5/2017. */ public interface BasePresenter { void start(); }
Oldbai/Hebiace
app/src/main/java/com/oldbai/android/app/hebiace/BasePresenter.java
Java
apache-2.0
143
package utils.CacheType; import java.util.Objects; public enum CacheType { vjUsage("vjusage", true, "vjUsage"), spectratype("spectratype", true, "spectratype"), spectratypeV("spectratypev", true, "spectratypeV"), annotation("annotation", true, "annotation"), quantileStats("quantilestats", true, "quantileStats"), rarefaction("rarefaction", false, "rarefaction"), summary("summary", false, "basicStats"); private final String type; private final Boolean single; private final String cacheFileName; CacheType(String type, Boolean single, String cacheFileName) { this.type = type; this.single = single; this.cacheFileName = cacheFileName; } public String getType() { return this.type; } public Boolean getSingle() { return this.single; } public String getCacheFileName() { return this.cacheFileName; } public static CacheType findByType(String type) { type = type.toLowerCase(); for (CacheType cache: CacheType.values()) { if (Objects.equals(cache.type, type)) { return cache; } } throw new IllegalArgumentException("Unknown cache type " + type); } }
antigenomics/vdjviz
app/utils/CacheType/CacheType.java
Java
apache-2.0
1,259
package io.joynr.jeeintegration.context; /* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * 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 java.lang.annotation.Annotation; import java.util.HashMap; import java.util.Map; import javax.enterprise.context.ContextNotActiveException; import javax.enterprise.context.spi.Context; import javax.enterprise.context.spi.Contextual; import javax.enterprise.context.spi.CreationalContext; import io.joynr.jeeintegration.api.JoynrJeeMessageScoped; /** * The {@link Context} which holds {@Link JoynrJeeMessageScoped} {@link Contextual contextual instances} for the * duration of a joynr message being processed. */ public class JoynrJeeMessageContext implements Context { private static JoynrJeeMessageContext instance; private ThreadLocal<Map<Contextual<?>, Object>> contextualStore = new ThreadLocal<>(); @Override public Class<? extends Annotation> getScope() { return JoynrJeeMessageScoped.class; } @Override public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) { T instance = get(contextual); if (instance == null) { instance = contextual.create(creationalContext); if (instance != null) { contextualStore.get().put(contextual, instance); } } return instance; } @SuppressWarnings("unchecked") @Override public <T> T get(Contextual<T> contextual) { Map<Contextual<?>, Object> store = contextualStore.get(); if (store == null) { throw new ContextNotActiveException(); } return (T) store.get(contextual); } @Override public boolean isActive() { return contextualStore.get() != null; } public void activate() { contextualStore.set(new HashMap<>()); } public void deactivate() { if (contextualStore.get() != null) { contextualStore.get().clear(); } contextualStore.remove(); } public synchronized static JoynrJeeMessageContext getInstance() { if (instance == null) { instance = new JoynrJeeMessageContext(); } return instance; } }
clive-jevons/joynr
java/jeeintegration/src/main/java/io/joynr/jeeintegration/context/JoynrJeeMessageContext.java
Java
apache-2.0
2,768
package com.gtm.cpims.dao; import net.sweet.dao.generic.EntityDAO; import com.gtm.cpims.model.BsFinancialiccheckyrFinal; public interface FinancialICCheckYRFinalDAO extends EntityDAO<BsFinancialiccheckyrFinal> { }
YangYongZhi/cpims
src/com/gtm/cpims/dao/FinancialICCheckYRFinalDAO.java
Java
apache-2.0
228
package com.kailash.tutorial.swing.ch25.gui; public class Utils { public static String getFileExtenstion(String fileName) { int pointIndex = fileName.lastIndexOf("."); if (pointIndex == -1) { return null; } else if (pointIndex == fileName.length()) { return null; } else return (fileName.substring(pointIndex + 1)); } }
kvasani/JavaGUI
src/main/java/com/kailash/tutorial/swing/ch25/gui/Utils.java
Java
apache-2.0
398
/* * Copyright 2015 Samppa Saarela * * 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.javersion.store.jdbc; import java.sql.Types; import org.javersion.core.Revision; import com.querydsl.core.types.PathMetadataFactory; import com.querydsl.core.types.dsl.EnumPath; import com.querydsl.core.types.dsl.SimplePath; import com.querydsl.sql.ColumnMetadata; import com.querydsl.sql.RelationalPathBase; public class JVersionParent extends RelationalPathBase<JVersionParent> { public final SimplePath<Revision> parentRevision = createSimple("parentRevision", org.javersion.core.Revision.class); public final SimplePath<org.javersion.core.Revision> revision = createSimple("revision", org.javersion.core.Revision.class); public final EnumPath<VersionStatus> status = createEnum("status", VersionStatus.class); public JVersionParent(RelationalPathBase<?> table) { super(JVersionParent.class, table.getMetadata(), table.getSchemaName(), table.getTableName()); table.getColumns().forEach(path -> addMetadata(path, table.getMetadata(path))); } public JVersionParent(String repositoryName) { this("PUBLIC", repositoryName + "_VERSION_PARENT"); } public JVersionParent(String schema, String table) { super(JVersionParent.class, PathMetadataFactory.forVariable(table), schema, table); addMetadata(revision, ColumnMetadata.named("REVISION").withIndex(1).ofType(Types.VARCHAR).withSize(32).notNull()); addMetadata(parentRevision, ColumnMetadata.named("PARENT_REVISION").withIndex(2).ofType(Types.VARCHAR).withSize(32).notNull()); addMetadata(status, ColumnMetadata.named("STATUS").withIndex(3).ofType(Types.INTEGER).withSize(1).notNull()); } }
ssaarela/javersion
javersion-jdbc/src/main/java/org/javersion/store/jdbc/JVersionParent.java
Java
apache-2.0
2,251
package life.catalogue.importer; import life.catalogue.api.model.*; import life.catalogue.api.vocab.Users; import life.catalogue.common.lang.InterruptedRuntimeException; import life.catalogue.common.tax.AuthorshipNormalizer; import life.catalogue.config.ImporterConfig; import life.catalogue.dao.Partitioner; import life.catalogue.db.mapper.*; import life.catalogue.importer.neo.NeoDb; import life.catalogue.importer.neo.NeoDbUtils; import life.catalogue.importer.neo.model.Labels; import life.catalogue.importer.neo.model.NeoName; import life.catalogue.importer.neo.model.NeoUsage; import life.catalogue.importer.neo.model.RelType; import life.catalogue.importer.neo.traverse.StartEndHandler; import life.catalogue.importer.neo.traverse.TreeWalker; import org.apache.ibatis.session.ExecutorType; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Transaction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.function.Supplier; import static life.catalogue.common.lang.Exceptions.interruptIfCancelled; /** * */ public class PgImport implements Callable<Boolean> { private static final Logger LOG = LoggerFactory.getLogger(PgImport.class); private final NeoDb store; private final int batchSize; private final SqlSessionFactory sessionFactory; private final AuthorshipNormalizer aNormalizer; private final Dataset dataset; private final Map<Integer, Integer> verbatimKeys = new HashMap<>(); private final Set<String> proParteIds = new HashSet<>(); private final AtomicInteger nCounter = new AtomicInteger(0); private final AtomicInteger tCounter = new AtomicInteger(0); private final AtomicInteger sCounter = new AtomicInteger(0); private final AtomicInteger rCounter = new AtomicInteger(0); private final AtomicInteger diCounter = new AtomicInteger(0); private final AtomicInteger deCounter = new AtomicInteger(0); private final AtomicInteger mCounter = new AtomicInteger(0); private final AtomicInteger vCounter = new AtomicInteger(0); private final AtomicInteger tmCounter = new AtomicInteger(0); public PgImport(int datasetKey, NeoDb store, SqlSessionFactory sessionFactory, AuthorshipNormalizer aNormalizer, ImporterConfig cfg) { this.dataset = store.getDataset(); this.dataset.setKey(datasetKey); this.aNormalizer = aNormalizer; this.store = store; this.batchSize = cfg.batchSize; this.sessionFactory = sessionFactory; } @Override public Boolean call() throws InterruptedException, InterruptedRuntimeException { Partitioner.partition(sessionFactory, dataset.getKey()); insertVerbatim(); insertReferences(); insertNames(); insertNameRelations(); insertTypeMaterial(); insertUsages(); Partitioner.indexAndAttach(sessionFactory, dataset.getKey()); updateMetadata(); LOG.info("Completed dataset {} insert with {} verbatim records, " + "{} names, {} taxa, {} synonyms, {} references, {} vernaculars, {} distributions, {} descriptions and {} media items", dataset.getKey(), verbatimKeys.size(), nCounter, tCounter, sCounter, rCounter, vCounter, diCounter, deCounter, mCounter); return true; } private void updateMetadata() { try (SqlSession session = sessionFactory.openSession(false)) { LOG.info("Updating dataset metadata for {}: {}", dataset.getKey(), dataset.getTitle()); DatasetMapper mapper = session.getMapper(DatasetMapper.class); Dataset old = mapper.get(dataset.getKey()); updateMetadata(old, dataset); mapper.update(old); session.commit(); } } /** * Updates the given dataset d with the provided metadata update, * retaining managed properties like keys and settings */ public static Dataset updateMetadata(Dataset d, Dataset update) { copyIfNotNull(update::getAlias, d::setAlias); copyIfNotNull(update::getAuthorsAndEditors, d::setAuthorsAndEditors); copyIfNotNull(update::getCompleteness, d::setCompleteness); copyIfNotNull(update::getConfidence, d::setConfidence); copyIfNotNull(update::getContact, d::setContact); copyIfNotNull(update::getDescription, d::setDescription); copyIfNotNull(update::getGroup, d::setGroup); copyIfNotNull(update::getLicense, d::setLicense); copyIfNotNull(update::getOrganisations, d::setOrganisations); copyIfNotNull(update::getReleased, d::setReleased); copyIfNotNull(update::getTitle, d::setTitle); copyIfNotNull(update::getType, d::setType); copyIfNotNull(update::getVersion, d::setVersion); copyIfNotNull(update::getWebsite, d::setWebsite); return d; } private static <T> void copyIfNotNull(Supplier<T> getter, Consumer<T> setter) { T val = getter.get(); if (val != null) { setter.accept(val); } } private void insertVerbatim() throws InterruptedException { try (final SqlSession session = sessionFactory.openSession(ExecutorType.BATCH, false)) { VerbatimRecordMapper mapper = session.getMapper(VerbatimRecordMapper.class); int counter = 0; Map<Integer, VerbatimRecord> batchCache = new HashMap<>(); for (VerbatimRecord v : store.verbatimList()) { int storeKey = v.getId(); v.setId(null); v.setDatasetKey(dataset.getKey()); mapper.create(v); batchCache.put(storeKey, v); if (++counter % batchSize == 0) { commitVerbatimBatch(session, batchCache); LOG.debug("Inserted {} verbatim records so far", counter); } } commitVerbatimBatch(session, batchCache); LOG.info("Inserted {} verbatim records", counter); } } private void commitVerbatimBatch(SqlSession session, Map<Integer, VerbatimRecord> batchCache) { interruptIfCancelled(); session.commit(); // we only get the new keys after we committed in batch mode!!! for (Map.Entry<Integer, VerbatimRecord> e : batchCache.entrySet()) { verbatimKeys.put(e.getKey(), e.getValue().getId()); } batchCache.clear(); } private <T extends VerbatimEntity & UserManaged & DatasetScoped> T updateVerbatimUserEntity(T ent) { ent.setDatasetKey(dataset.getKey()); return updateUser(updateVerbatimEntity(ent)); } private <T extends VerbatimEntity> T updateVerbatimEntity(T ent) { if (ent != null && ent.getVerbatimKey() != null) { ent.setVerbatimKey(verbatimKeys.get(ent.getVerbatimKey())); } return ent; } private static <T extends UserManaged> T updateUser(T ent) { if (ent != null) { ent.setCreatedBy(Users.IMPORTER); ent.setModifiedBy(Users.IMPORTER); } return ent; } private <T extends Referenced> T updateReferenceKey(T obj){ if (obj.getReferenceId() != null) { obj.setReferenceId(store.references().tmpIdUpdate(obj.getReferenceId())); } return obj; } private void updateReferenceKey(String refID, Consumer<String> setter){ if (refID != null) { setter.accept(store.references().tmpIdUpdate(refID)); } } private void updateReferenceKey(List<String> refIDs){ if (refIDs != null) { refIDs.replaceAll(r -> store.references().tmpIdUpdate(r)); } } private void insertReferences() throws InterruptedException { try (final SqlSession session = sessionFactory.openSession(ExecutorType.BATCH, false)) { ReferenceMapper mapper = session.getMapper(ReferenceMapper.class); int counter = 0; // update all tmp ids to nice ones store.references().updateTmpIds(); for (Reference r : store.references()) { r.setDatasetKey(dataset.getKey()); updateVerbatimUserEntity(r); updateUser(r); mapper.create(r); rCounter.incrementAndGet(); if (counter++ % batchSize == 0) { interruptIfCancelled(); session.commit(); LOG.debug("Inserted {} references", counter); } } session.commit(); LOG.debug("Inserted all {} references", counter); } } /** * Inserts all names, collecting all homotypic name keys for later updates if they havent been inserted already. */ private void insertNames() { try (final SqlSession session = sessionFactory.openSession(ExecutorType.BATCH, false)) { final NameMapper nameMapper = session.getMapper(NameMapper.class); LOG.debug("Inserting all names"); store.names().all().forEach(n -> { n.name.setDatasetKey(dataset.getKey()); updateVerbatimUserEntity(n.name); updateReferenceKey(n.name.getPublishedInId(), n.name::setPublishedInId); // normalize authorship on insert - sth the DAO normally does but we use the mapper directly in batch mode n.name.setAuthorshipNormalized(aNormalizer.normalizeName(n.name)); nameMapper.create(n.name); if (nCounter.incrementAndGet() % batchSize == 0) { interruptIfCancelled(); session.commit(); LOG.debug("Inserted {} other names", nCounter.get()); } }); session.commit(); } LOG.info("Inserted {} name in total", nCounter.get()); } /** * Go through all neo4j relations and convert them to name acts if the rel type matches */ private void insertNameRelations() { for (RelType rt : RelType.values()) { if (!rt.isNameRel()) continue; final AtomicInteger counter = new AtomicInteger(0); try (final SqlSession session = sessionFactory.openSession(ExecutorType.BATCH, false)) { final NameRelationMapper nameRelationMapper = session.getMapper(NameRelationMapper.class); LOG.debug("Inserting all {} relations", rt); try (Transaction tx = store.getNeo().beginTx()) { store.iterRelations(rt).stream().forEach(rel -> { NameRelation nr = store.toRelation(rel); updateReferenceKey(nr.getPublishedInId(), nr::setPublishedInId); nameRelationMapper.create(updateUser(nr)); if (counter.incrementAndGet() % batchSize == 0) { interruptIfCancelled(); session.commit(); } }); } session.commit(); } LOG.info("Inserted {} {} relations", counter.get(), rt); } } private void insertTypeMaterial() { try (final SqlSession session = sessionFactory.openSession(ExecutorType.BATCH, false)) { final TypeMaterialMapper tmm = session.getMapper(TypeMaterialMapper.class); LOG.debug("Inserting type material"); // update all tmp ids to nice ones store.typeMaterial().updateTmpIds(); for (TypeMaterial tm : store.typeMaterial()) { updateVerbatimUserEntity(tm); updateReferenceKey(tm); tmm.create(tm); if (tmCounter.incrementAndGet() % batchSize == 0) { interruptIfCancelled(); session.commit(); } } session.commit(); } LOG.info("Inserted {} type material records", tmCounter); } /** * insert taxa/synonyms with all the rest */ private void insertUsages() throws InterruptedException { try (SqlSession session = sessionFactory.openSession(ExecutorType.BATCH,false)) { LOG.info("Inserting remaining names and all taxa"); DescriptionMapper descriptionMapper = session.getMapper(DescriptionMapper.class); DistributionMapper distributionMapper = session.getMapper(DistributionMapper.class); MediaMapper mediaMapper = session.getMapper(MediaMapper.class); TaxonMapper taxonMapper = session.getMapper(TaxonMapper.class); SynonymMapper synMapper = session.getMapper(SynonymMapper.class); VernacularNameMapper vernacularMapper = session.getMapper(VernacularNameMapper.class); // iterate over taxonomic tree in depth first order, keeping postgres parent keys // pro parte synonyms will be visited multiple times, remember their name ids! TreeWalker.walkTree(store.getNeo(), new StartEndHandler() { int counter = 0; Stack<String> parentIds = new Stack<>(); @Override public void start(Node n) { NeoUsage u = store.usages().objByNode(n); NeoName nn = store.nameByUsage(n); updateVerbatimEntity(u); updateVerbatimEntity(nn); // update share props for taxon or synonym NameUsageBase nu = u.usage; nu.setName(nn.name); nu.setDatasetKey(dataset.getKey()); updateReferenceKey(nu.getReferenceIds()); updateUser(nu); if (!parentIds.empty()) { // use parent postgres key from stack, but keep it there nu.setParentId(parentIds.peek()); } else if (u.isSynonym()) { throw new IllegalStateException("Synonym node " + n.getId() + " without accepted taxon found: " + nn.name.getScientificName()); } else if (!n.hasLabel(Labels.ROOT)) { throw new IllegalStateException("Non root node " + n.getId() + " with an accepted taxon without parent found: " + nn.name.getScientificName()); } // insert taxon or synonym if (u.isSynonym()) { if (NeoDbUtils.isProParteSynonym(n)) { if (proParteIds.contains(u.getId())){ // we had that id before, append a random suffix for further pro parte usage UUID ppID = UUID.randomUUID(); u.setId(u.getId() + "-" + ppID); } else { proParteIds.add(u.getId()); } } synMapper.create(u.getSynonym()); sCounter.incrementAndGet(); } else { taxonMapper.create(updateUser(u.getTaxon())); tCounter.incrementAndGet(); Taxon acc = u.getTaxon(); // push new postgres key onto stack for this taxon as we traverse in depth first parentIds.push(acc.getId()); // insert vernacular for (VernacularName vn : u.vernacularNames) { updateVerbatimUserEntity(vn); updateReferenceKey(vn); vernacularMapper.create(vn, acc.getId()); vCounter.incrementAndGet(); } // insert distributions for (Distribution d : u.distributions) { updateVerbatimUserEntity(d); updateReferenceKey(d); distributionMapper.create(d, acc.getId()); diCounter.incrementAndGet(); } // insert descriptions for (Description d : u.descriptions) { updateVerbatimUserEntity(d); updateReferenceKey(d); descriptionMapper.create(d, acc.getId()); deCounter.incrementAndGet(); } // insert media for (Media m : u.media) { updateVerbatimUserEntity(m); updateReferenceKey(m); mediaMapper.create(m, acc.getId()); mCounter.incrementAndGet(); } } // commit in batches if (counter++ % batchSize == 0) { interruptIfCancelled(); session.commit(); LOG.info("Inserted {} names and taxa", counter); } } @Override public void end(Node n) { interruptIfCancelled(); // remove this key from parent queue if its an accepted taxon if (n.hasLabel(Labels.TAXON)) { parentIds.pop(); } } }); session.commit(); LOG.debug("Inserted {} names and {} taxa", nCounter, tCounter); } } }
Sp2000/colplus-backend
colplus-ws/src/main/java/life/catalogue/importer/PgImport.java
Java
apache-2.0
15,868
package com.github.anno4j.schema_parsing.mapping; import com.github.anno4j.Anno4j; import com.github.anno4j.schema.model.rdfs.RDFSClazz; import com.github.anno4j.schema_parsing.building.OWLJavaFileGenerator; import com.github.anno4j.schema_parsing.building.OntGenerationConfig; import com.github.anno4j.schema_parsing.building.OntologyModelBuilder; import com.github.anno4j.schema_parsing.model.BuildableRDFSProperty; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import org.apache.commons.io.IOUtils; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Test for custom mapping from RDF datatypes to Java types. */ public class DatatypeMappingTest { /** * A valid datatype mapper, mapping ex:oddInt to Integer. */ private static class ValidOddIntegerMapper implements DatatypeMapper { @Override public Class<?> mapType(RDFSClazz type) { if(type.getResourceAsString().equals("http://example.de/ont#oddInt")) { return Integer.class; } else { return null; } } } /** * An invalid datatype mapper, mapping ex:oddInt to Thread. */ private static class InvalidOddIntegerMapper implements DatatypeMapper { @Override public Class<?> mapType(RDFSClazz type) { if(type.getResourceAsString().equals("http://example.de/ont#oddInt")) { return Thread.class; } else { return null; } } } private static final String ontologyTtl = "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . " + "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . " + "@prefix ex: <http://example.de/ont#> . " + "ex:A rdf:type rdfs:Class . " + "ex:oddInt rdfs:subClassOf rdfs:Literal . " + "ex:foo rdfs:domain ex:A . " + "ex:foo rdfs:range ex:oddInt . "; @Test public void testValidMapping() throws Exception { Anno4j anno4j = new Anno4j(); OntologyModelBuilder modelBuilder = new OWLJavaFileGenerator(anno4j); modelBuilder.addRDF(IOUtils.toInputStream(ontologyTtl), "http://example.de/ont#", "TURTLE"); modelBuilder.build(); RDFSClazz declaringClass = anno4j.createObject(RDFSClazz.class); // Find the ex:foo property: BuildableRDFSProperty foo = anno4j.findByID(BuildableRDFSProperty.class, "http://example.de/ont#foo"); // Build the generation configuration: OntGenerationConfig config = new OntGenerationConfig(); config.setDatatypeMappers(new ValidOddIntegerMapper()); // Build an adder for ex:foo and check the type of its parameter: MethodSpec adder = foo.buildAdder(declaringClass, config); assertEquals(ClassName.get(Integer.class), adder.parameters.get(0).type); } @Test public void testInvalidMapping() throws Exception { Anno4j anno4j = new Anno4j(); OntologyModelBuilder modelBuilder = new OWLJavaFileGenerator(anno4j); modelBuilder.addRDF(IOUtils.toInputStream(ontologyTtl), "http://example.de/ont#", "TURTLE"); modelBuilder.build(); RDFSClazz declaringClass = anno4j.createObject(RDFSClazz.class); // Find the ex:foo property: BuildableRDFSProperty foo = anno4j.findByID(BuildableRDFSProperty.class, "http://example.de/ont#foo"); // Build the generation configuration: OntGenerationConfig config = new OntGenerationConfig(); config.setDatatypeMappers(new InvalidOddIntegerMapper()); // Exception should be thrown: boolean exceptionThrown = false; try { foo.buildAdder(declaringClass, config); } catch (IllegalMappingException e) { exceptionThrown = true; } assertTrue(exceptionThrown); } }
anno4j/anno4j
anno4j-core/src/test/java/com/github/anno4j/schema_parsing/mapping/DatatypeMappingTest.java
Java
apache-2.0
3,981
/* * Copyright 2017-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.jvm.java.abi; import static org.junit.Assert.assertTrue; import com.facebook.buck.jvm.java.testutil.compiler.CompilerTreeApiTestRunner; import com.google.common.base.Joiner; import org.junit.Test; import org.junit.runner.RunWith; import java.io.IOException; import java.util.List; @RunWith(CompilerTreeApiTestRunner.class) public class DescriptorFactoryTest extends DescriptorAndSignatureFactoryTestBase { private DescriptorFactory descriptorFactory; @Override public void setUp() throws IOException { super.setUp(); descriptorFactory = new DescriptorFactory(elements); } @Test public void testAllTheThings() throws IOException { List<String> errors = getTestErrors( field -> field.desc, method -> method.desc, (t) -> null, descriptorFactory::getDescriptor); assertTrue("Descriptor mismatch!\n\n" + Joiner.on('\n').join(errors), errors.isEmpty()); } }
vschs007/buck
test/com/facebook/buck/jvm/java/abi/DescriptorFactoryTest.java
Java
apache-2.0
1,556
package br.uff.labtempo.osiris.repository; import br.uff.labtempo.omcp.common.exceptions.AbstractRequestException; import br.uff.labtempo.osiris.dao.CompositeOmcpDao; import br.uff.labtempo.osiris.to.virtualsensornet.CompositeVsnTo; import java.net.URI; import java.net.URISyntaxException; import java.util.List; /** * Interface that abstracts Composite DAO implementations * @see CompositeOmcpDao * @author andre.ghigo * @since 1.8 * @version 1.0 */ public interface CompositeRepository { CompositeVsnTo getById(String compositeId) throws AbstractRequestException; List<CompositeVsnTo> getAll() throws AbstractRequestException; URI create(CompositeVsnTo compositeVsnTo) throws AbstractRequestException, URISyntaxException; void update(String compositeId, CompositeVsnTo compositeVsnTo) throws AbstractRequestException; void delete(String compositeId) throws AbstractRequestException; }
aghigo/osiris-web-backend
impl/src/main/java/br/uff/labtempo/osiris/repository/CompositeRepository.java
Java
apache-2.0
917
/** * * Copyright 2016 Fernando Ramirez * * 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.jivesoftware.smackx.muclight.provider; import java.util.HashMap; import org.jivesoftware.smack.provider.ExtensionElementProvider; import org.jivesoftware.smackx.muclight.element.MUCLightElements.ConfigurationsChangeExtension; import org.xmlpull.v1.XmlPullParser; /** * MUC Light configurations change provider class. * * @author Fernando Ramirez * */ public class MUCLightConfigurationsChangeProvider extends ExtensionElementProvider<ConfigurationsChangeExtension> { @Override public ConfigurationsChangeExtension parse(XmlPullParser parser, int initialDepth) throws Exception { String prevVersion = null; String version = null; String roomName = null; String subject = null; HashMap<String, String> customConfigs = null; outerloop: while (true) { int eventType = parser.next(); if (eventType == XmlPullParser.START_TAG) { if (parser.getName().equals("prev-version")) { prevVersion = parser.nextText(); } else if (parser.getName().equals("version")) { version = parser.nextText(); } else if (parser.getName().equals("roomname")) { roomName = parser.nextText(); } else if (parser.getName().equals("subject")) { subject = parser.nextText(); } else { if (customConfigs == null) { customConfigs = new HashMap<>(); } customConfigs.put(parser.getName(), parser.nextText()); } } else if (eventType == XmlPullParser.END_TAG) { if (parser.getDepth() == initialDepth) { break outerloop; } } } return new ConfigurationsChangeExtension(prevVersion, version, roomName, subject, customConfigs); } }
vanitasvitae/smack-omemo
smack-experimental/src/main/java/org/jivesoftware/smackx/muclight/provider/MUCLightConfigurationsChangeProvider.java
Java
apache-2.0
2,555
/* * 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.harmony.test.func.api.java.lang.ClassLoader.findClass.findClass10.findClass1010; import java.lang.reflect.Constructor; import java.net.URL; import java.io.*; import java.util.*; import org.apache.harmony.share.Test; import org.apache.harmony.test.func.share.MyLog; public class findClass1010 extends Test { boolean results[] = new boolean[100]; String logArray[] = new String[100]; int logIndex = 0; void addLog(String s) { if ( logIndex < logArray.length ) logArray[logIndex] = s; logIndex++; } void findClass1010() { MyfindClass1010 myfindClass1010 = new MyfindClass1010(); String foundableName = "org.apache.harmony.test.func.api.java.lang.ClassLoader.findClass.findClass10.findClass1010" + ".ChildfindClass1010" ; Class classObj = null; //-1 try { classObj = myfindClass1010.findClass(foundableName); results[1] = false ; } catch ( ClassNotFoundException e ) { } //-1) return ; } public int test() { logIndex = 0; String texts[] = { "Testcase FAILURE, results[#] = " , "Test P A S S E D" , "Test F A I L E D" , "#### U N E X P E C T E D : " }; int failed = 105; int passed = 104; int unexpected = 106; int toReturn = 0; String toPrint = null; for ( int i = 0; i < results.length; i++ ) results[i] = true; try { addLog("********* Test findClass1010 begins "); findClass1010(); addLog("********* Test findClass1010 results: "); boolean result = true; for ( int i = 1 ; i < results.length ; i++ ) { result &= results[i]; if ( ! results[i] ) addLog(texts[0] + i); } if ( ! result ) { toPrint = texts[2]; toReturn = failed; } if ( result ) { toPrint = texts[1]; toReturn = passed; } } catch (Exception e) { toPrint = texts[3] + e; toReturn = unexpected; } if ( toReturn != passed ) for ( int i = 0; i < logIndex; i++ ) MyLog.toMyLog(logArray[i]); MyLog.toMyLog(toPrint); return toReturn; } public static void main(String args[]) { System.exit(new findClass1010().test()); } } class MyfindClass1010 extends ClassLoader { MyfindClass1010() {super();} public Class findClass(String name) throws ClassNotFoundException { try { return super.findClass(name); } catch ( ClassNotFoundException e ) { throw new ClassNotFoundException( (String) e.toString() ); } } } class ChildfindClass1010 extends ClassLoader { ChildfindClass1010(ClassLoader parent) {super(parent);} }
freeVM/freeVM
enhanced/buildtest/tests/functional/src/test/functional/org/apache/harmony/test/func/api/java/lang/ClassLoader/findClass/findClass10/findClass1010/findClass1010.java
Java
apache-2.0
3,913
/* * 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.ec2.model; import java.io.Serializable; import com.amazonaws.AmazonWebServiceRequest; import com.amazonaws.Request; import com.amazonaws.services.ec2.model.transform.CreateNetworkAclEntryRequestMarshaller; /** * */ public class CreateNetworkAclEntryRequest extends AmazonWebServiceRequest implements Serializable, Cloneable, DryRunSupportedRequest<CreateNetworkAclEntryRequest> { /** * <p> * The ID of the network ACL. * </p> */ private String networkAclId; /** * <p> * The rule number for the entry (for example, 100). ACL entries are * processed in ascending order by rule number. * </p> * <p> * Constraints: Positive integer from 1 to 32766 * </p> */ private Integer ruleNumber; /** * <p> * The protocol. A value of -1 means all protocols. * </p> */ private String protocol; /** * <p> * Indicates whether to allow or deny the traffic that matches the rule. * </p> */ private String ruleAction; /** * <p> * Indicates whether this is an egress rule (rule is applied to traffic * leaving the subnet). * </p> */ private Boolean egress; /** * <p> * The network range to allow or deny, in CIDR notation (for example * <code>172.16.0.0/24</code>). * </p> */ private String cidrBlock; /** * <p> * ICMP protocol: The ICMP type and code. Required if specifying ICMP for * the protocol. * </p> */ private IcmpTypeCode icmpTypeCode; /** * <p> * TCP or UDP protocols: The range of ports the rule applies to. * </p> */ private PortRange portRange; /** * <p> * The ID of the network ACL. * </p> * * @param networkAclId * The ID of the network ACL. */ public void setNetworkAclId(String networkAclId) { this.networkAclId = networkAclId; } /** * <p> * The ID of the network ACL. * </p> * * @return The ID of the network ACL. */ public String getNetworkAclId() { return this.networkAclId; } /** * <p> * The ID of the network ACL. * </p> * * @param networkAclId * The ID of the network ACL. * @return Returns a reference to this object so that method calls can be * chained together. */ public CreateNetworkAclEntryRequest withNetworkAclId(String networkAclId) { setNetworkAclId(networkAclId); return this; } /** * <p> * The rule number for the entry (for example, 100). ACL entries are * processed in ascending order by rule number. * </p> * <p> * Constraints: Positive integer from 1 to 32766 * </p> * * @param ruleNumber * The rule number for the entry (for example, 100). ACL entries are * processed in ascending order by rule number.</p> * <p> * Constraints: Positive integer from 1 to 32766 */ public void setRuleNumber(Integer ruleNumber) { this.ruleNumber = ruleNumber; } /** * <p> * The rule number for the entry (for example, 100). ACL entries are * processed in ascending order by rule number. * </p> * <p> * Constraints: Positive integer from 1 to 32766 * </p> * * @return The rule number for the entry (for example, 100). ACL entries are * processed in ascending order by rule number.</p> * <p> * Constraints: Positive integer from 1 to 32766 */ public Integer getRuleNumber() { return this.ruleNumber; } /** * <p> * The rule number for the entry (for example, 100). ACL entries are * processed in ascending order by rule number. * </p> * <p> * Constraints: Positive integer from 1 to 32766 * </p> * * @param ruleNumber * The rule number for the entry (for example, 100). ACL entries are * processed in ascending order by rule number.</p> * <p> * Constraints: Positive integer from 1 to 32766 * @return Returns a reference to this object so that method calls can be * chained together. */ public CreateNetworkAclEntryRequest withRuleNumber(Integer ruleNumber) { setRuleNumber(ruleNumber); return this; } /** * <p> * The protocol. A value of -1 means all protocols. * </p> * * @param protocol * The protocol. A value of -1 means all protocols. */ public void setProtocol(String protocol) { this.protocol = protocol; } /** * <p> * The protocol. A value of -1 means all protocols. * </p> * * @return The protocol. A value of -1 means all protocols. */ public String getProtocol() { return this.protocol; } /** * <p> * The protocol. A value of -1 means all protocols. * </p> * * @param protocol * The protocol. A value of -1 means all protocols. * @return Returns a reference to this object so that method calls can be * chained together. */ public CreateNetworkAclEntryRequest withProtocol(String protocol) { setProtocol(protocol); return this; } /** * <p> * Indicates whether to allow or deny the traffic that matches the rule. * </p> * * @param ruleAction * Indicates whether to allow or deny the traffic that matches the * rule. * @see RuleAction */ public void setRuleAction(String ruleAction) { this.ruleAction = ruleAction; } /** * <p> * Indicates whether to allow or deny the traffic that matches the rule. * </p> * * @return Indicates whether to allow or deny the traffic that matches the * rule. * @see RuleAction */ public String getRuleAction() { return this.ruleAction; } /** * <p> * Indicates whether to allow or deny the traffic that matches the rule. * </p> * * @param ruleAction * Indicates whether to allow or deny the traffic that matches the * rule. * @return Returns a reference to this object so that method calls can be * chained together. * @see RuleAction */ public CreateNetworkAclEntryRequest withRuleAction(String ruleAction) { setRuleAction(ruleAction); return this; } /** * <p> * Indicates whether to allow or deny the traffic that matches the rule. * </p> * * @param ruleAction * Indicates whether to allow or deny the traffic that matches the * rule. * @return Returns a reference to this object so that method calls can be * chained together. * @see RuleAction */ public void setRuleAction(RuleAction ruleAction) { this.ruleAction = ruleAction.toString(); } /** * <p> * Indicates whether to allow or deny the traffic that matches the rule. * </p> * * @param ruleAction * Indicates whether to allow or deny the traffic that matches the * rule. * @return Returns a reference to this object so that method calls can be * chained together. * @see RuleAction */ public CreateNetworkAclEntryRequest withRuleAction(RuleAction ruleAction) { setRuleAction(ruleAction); return this; } /** * <p> * Indicates whether this is an egress rule (rule is applied to traffic * leaving the subnet). * </p> * * @param egress * Indicates whether this is an egress rule (rule is applied to * traffic leaving the subnet). */ public void setEgress(Boolean egress) { this.egress = egress; } /** * <p> * Indicates whether this is an egress rule (rule is applied to traffic * leaving the subnet). * </p> * * @return Indicates whether this is an egress rule (rule is applied to * traffic leaving the subnet). */ public Boolean getEgress() { return this.egress; } /** * <p> * Indicates whether this is an egress rule (rule is applied to traffic * leaving the subnet). * </p> * * @param egress * Indicates whether this is an egress rule (rule is applied to * traffic leaving the subnet). * @return Returns a reference to this object so that method calls can be * chained together. */ public CreateNetworkAclEntryRequest withEgress(Boolean egress) { setEgress(egress); return this; } /** * <p> * Indicates whether this is an egress rule (rule is applied to traffic * leaving the subnet). * </p> * * @return Indicates whether this is an egress rule (rule is applied to * traffic leaving the subnet). */ public Boolean isEgress() { return this.egress; } /** * <p> * The network range to allow or deny, in CIDR notation (for example * <code>172.16.0.0/24</code>). * </p> * * @param cidrBlock * The network range to allow or deny, in CIDR notation (for example * <code>172.16.0.0/24</code>). */ public void setCidrBlock(String cidrBlock) { this.cidrBlock = cidrBlock; } /** * <p> * The network range to allow or deny, in CIDR notation (for example * <code>172.16.0.0/24</code>). * </p> * * @return The network range to allow or deny, in CIDR notation (for example * <code>172.16.0.0/24</code>). */ public String getCidrBlock() { return this.cidrBlock; } /** * <p> * The network range to allow or deny, in CIDR notation (for example * <code>172.16.0.0/24</code>). * </p> * * @param cidrBlock * The network range to allow or deny, in CIDR notation (for example * <code>172.16.0.0/24</code>). * @return Returns a reference to this object so that method calls can be * chained together. */ public CreateNetworkAclEntryRequest withCidrBlock(String cidrBlock) { setCidrBlock(cidrBlock); return this; } /** * <p> * ICMP protocol: The ICMP type and code. Required if specifying ICMP for * the protocol. * </p> * * @param icmpTypeCode * ICMP protocol: The ICMP type and code. Required if specifying ICMP * for the protocol. */ public void setIcmpTypeCode(IcmpTypeCode icmpTypeCode) { this.icmpTypeCode = icmpTypeCode; } /** * <p> * ICMP protocol: The ICMP type and code. Required if specifying ICMP for * the protocol. * </p> * * @return ICMP protocol: The ICMP type and code. Required if specifying * ICMP for the protocol. */ public IcmpTypeCode getIcmpTypeCode() { return this.icmpTypeCode; } /** * <p> * ICMP protocol: The ICMP type and code. Required if specifying ICMP for * the protocol. * </p> * * @param icmpTypeCode * ICMP protocol: The ICMP type and code. Required if specifying ICMP * for the protocol. * @return Returns a reference to this object so that method calls can be * chained together. */ public CreateNetworkAclEntryRequest withIcmpTypeCode( IcmpTypeCode icmpTypeCode) { setIcmpTypeCode(icmpTypeCode); return this; } /** * <p> * TCP or UDP protocols: The range of ports the rule applies to. * </p> * * @param portRange * TCP or UDP protocols: The range of ports the rule applies to. */ public void setPortRange(PortRange portRange) { this.portRange = portRange; } /** * <p> * TCP or UDP protocols: The range of ports the rule applies to. * </p> * * @return TCP or UDP protocols: The range of ports the rule applies to. */ public PortRange getPortRange() { return this.portRange; } /** * <p> * TCP or UDP protocols: The range of ports the rule applies to. * </p> * * @param portRange * TCP or UDP protocols: The range of ports the rule applies to. * @return Returns a reference to this object so that method calls can be * chained together. */ public CreateNetworkAclEntryRequest withPortRange(PortRange portRange) { setPortRange(portRange); return this; } /** * This method is intended for internal use only. Returns the marshaled * request configured with additional parameters to enable operation * dry-run. */ @Override public Request<CreateNetworkAclEntryRequest> getDryRunRequest() { Request<CreateNetworkAclEntryRequest> request = new CreateNetworkAclEntryRequestMarshaller() .marshall(this); request.addParameter("DryRun", Boolean.toString(true)); return request; } /** * 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 (getNetworkAclId() != null) sb.append("NetworkAclId: " + getNetworkAclId() + ","); if (getRuleNumber() != null) sb.append("RuleNumber: " + getRuleNumber() + ","); if (getProtocol() != null) sb.append("Protocol: " + getProtocol() + ","); if (getRuleAction() != null) sb.append("RuleAction: " + getRuleAction() + ","); if (getEgress() != null) sb.append("Egress: " + getEgress() + ","); if (getCidrBlock() != null) sb.append("CidrBlock: " + getCidrBlock() + ","); if (getIcmpTypeCode() != null) sb.append("IcmpTypeCode: " + getIcmpTypeCode() + ","); if (getPortRange() != null) sb.append("PortRange: " + getPortRange()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CreateNetworkAclEntryRequest == false) return false; CreateNetworkAclEntryRequest other = (CreateNetworkAclEntryRequest) obj; if (other.getNetworkAclId() == null ^ this.getNetworkAclId() == null) return false; if (other.getNetworkAclId() != null && other.getNetworkAclId().equals(this.getNetworkAclId()) == false) return false; if (other.getRuleNumber() == null ^ this.getRuleNumber() == null) return false; if (other.getRuleNumber() != null && other.getRuleNumber().equals(this.getRuleNumber()) == false) return false; if (other.getProtocol() == null ^ this.getProtocol() == null) return false; if (other.getProtocol() != null && other.getProtocol().equals(this.getProtocol()) == false) return false; if (other.getRuleAction() == null ^ this.getRuleAction() == null) return false; if (other.getRuleAction() != null && other.getRuleAction().equals(this.getRuleAction()) == false) return false; if (other.getEgress() == null ^ this.getEgress() == null) return false; if (other.getEgress() != null && other.getEgress().equals(this.getEgress()) == false) return false; if (other.getCidrBlock() == null ^ this.getCidrBlock() == null) return false; if (other.getCidrBlock() != null && other.getCidrBlock().equals(this.getCidrBlock()) == false) return false; if (other.getIcmpTypeCode() == null ^ this.getIcmpTypeCode() == null) return false; if (other.getIcmpTypeCode() != null && other.getIcmpTypeCode().equals(this.getIcmpTypeCode()) == false) return false; if (other.getPortRange() == null ^ this.getPortRange() == null) return false; if (other.getPortRange() != null && other.getPortRange().equals(this.getPortRange()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getNetworkAclId() == null) ? 0 : getNetworkAclId() .hashCode()); hashCode = prime * hashCode + ((getRuleNumber() == null) ? 0 : getRuleNumber().hashCode()); hashCode = prime * hashCode + ((getProtocol() == null) ? 0 : getProtocol().hashCode()); hashCode = prime * hashCode + ((getRuleAction() == null) ? 0 : getRuleAction().hashCode()); hashCode = prime * hashCode + ((getEgress() == null) ? 0 : getEgress().hashCode()); hashCode = prime * hashCode + ((getCidrBlock() == null) ? 0 : getCidrBlock().hashCode()); hashCode = prime * hashCode + ((getIcmpTypeCode() == null) ? 0 : getIcmpTypeCode() .hashCode()); hashCode = prime * hashCode + ((getPortRange() == null) ? 0 : getPortRange().hashCode()); return hashCode; } @Override public CreateNetworkAclEntryRequest clone() { return (CreateNetworkAclEntryRequest) super.clone(); } }
dump247/aws-sdk-java
aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/CreateNetworkAclEntryRequest.java
Java
apache-2.0
18,765
package com.nexradnow.android.model; import java.io.Serializable; import java.util.List; import java.util.Map; /** * Created by hobsonm on 9/16/15. */ public class NexradUpdate implements Serializable { protected Map<NexradStation,List<NexradProduct>> updateProduct; protected LatLongCoordinates centerPoint; public NexradUpdate(Map<NexradStation, List<NexradProduct>> updateProduct, LatLongCoordinates centerPoint) { this.updateProduct = updateProduct; this.centerPoint = centerPoint; } public Map<NexradStation, List<NexradProduct>> getUpdateProduct() { return updateProduct; } public void setUpdateProduct(Map<NexradStation, List<NexradProduct>> updateProduct) { this.updateProduct = updateProduct; } public LatLongCoordinates getCenterPoint() { return centerPoint; } public void setCenterPoint(LatLongCoordinates centerPoint) { this.centerPoint = centerPoint; } }
SierraCharlie/nexradNow-android
app/src/main/java/com/nexradnow/android/model/NexradUpdate.java
Java
apache-2.0
973
package com.bitmonlab.osiris.commons.map.model.geojson; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotBlank; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection="Metadata") public class MetaData { @NotNull @NotBlank @Id private String appId; @NotNull @NotBlank private String osmChecksum; @NotNull @NotBlank private String routingChecksum; private Double minlat; private Double minlon; private Double maxlat; private Double maxlon; public String getOSMChecksum() { return osmChecksum; } public void setOSMChecksum(String chkSum) { this.osmChecksum = chkSum; } public Double getMinlat() { return minlat; } public void setMinlat(Double minlat) { this.minlat = minlat; } public Double getMinlon() { return minlon; } public void setMinlon(Double minlon) { this.minlon = minlon; } public Double getMaxlat() { return maxlat; } public void setMaxlat(Double maxlat) { this.maxlat = maxlat; } public Double getMaxlon() { return maxlon; } public void setMaxlon(Double maxlon) { this.maxlon = maxlon; } public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getRoutingChecksum() { return routingChecksum; } public void setRoutingChecksum(String routingChecksum) { this.routingChecksum = routingChecksum; } }
osiris-indoor/osiris
osiris-map-commons/src/main/java/com/bitmonlab/osiris/commons/map/model/geojson/MetaData.java
Java
apache-2.0
1,589
/** * 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.tools; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.tools.util.DistCpUtils; import org.apache.hadoop.security.Credentials; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; import java.lang.reflect.Constructor; import java.net.URI; import java.util.Set; import com.google.common.collect.Sets; /** * The CopyListing abstraction is responsible for how the list of * sources and targets is constructed, for DistCp's copy function. * The copy-listing should be a SequenceFile<Text, CopyListingFileStatus>, * located at the path specified to buildListing(), * each entry being a pair of (Source relative path, source file status), * all the paths being fully qualified. */ public abstract class CopyListing extends Configured { private Credentials credentials; static final Log LOG = LogFactory.getLog(DistCp.class); /** * Build listing function creates the input listing that distcp uses to * perform the copy. * * The build listing is a sequence file that has relative path of a file in the key * and the file status information of the source file in the value * * For instance if the source path is /tmp/data and the traversed path is * /tmp/data/dir1/dir2/file1, then the sequence file would contain * * key: /dir1/dir2/file1 and value: FileStatus(/tmp/data/dir1/dir2/file1) * * File would also contain directory entries. Meaning, if /tmp/data/dir1/dir2/file1 * is the only file under /tmp/data, the resulting sequence file would contain the * following entries * * key: /dir1 and value: FileStatus(/tmp/data/dir1) * key: /dir1/dir2 and value: FileStatus(/tmp/data/dir1/dir2) * key: /dir1/dir2/file1 and value: FileStatus(/tmp/data/dir1/dir2/file1) * * Cases requiring special handling: * If source path is a file (/tmp/file1), contents of the file will be as follows * * TARGET DOES NOT EXIST: Key-"", Value-FileStatus(/tmp/file1) * TARGET IS FILE : Key-"", Value-FileStatus(/tmp/file1) * TARGET IS DIR : Key-"/file1", Value-FileStatus(/tmp/file1) * * @param pathToListFile - Output file where the listing would be stored * @param options - Input options to distcp * @throws IOException - Exception if any */ public final void buildListing(Path pathToListFile, DistCpOptions options) throws IOException { validatePaths(options); doBuildListing(pathToListFile, options); Configuration config = getConf(); config.set(DistCpConstants.CONF_LABEL_LISTING_FILE_PATH, pathToListFile.toString()); config.setLong(DistCpConstants.CONF_LABEL_TOTAL_BYTES_TO_BE_COPIED, getBytesToCopy()); config.setLong(DistCpConstants.CONF_LABEL_TOTAL_NUMBER_OF_RECORDS, getNumberOfPaths()); validateFinalListing(pathToListFile, options); LOG.info("Number of paths in the copy list: " + this.getNumberOfPaths()); } /** * Validate input and output paths * * @param options - Input options * @throws InvalidInputException: If inputs are invalid * @throws IOException: any Exception with FS */ protected abstract void validatePaths(DistCpOptions options) throws IOException, InvalidInputException; /** * The interface to be implemented by sub-classes, to create the source/target file listing. * @param pathToListFile Path on HDFS where the listing file is written. * @param options Input Options for DistCp (indicating source/target paths.) * @throws IOException: Thrown on failure to create the listing file. */ protected abstract void doBuildListing(Path pathToListFile, DistCpOptions options) throws IOException; /** * Return the total bytes that distCp should copy for the source paths * This doesn't consider whether file is same should be skipped during copy * * @return total bytes to copy */ protected abstract long getBytesToCopy(); /** * Return the total number of paths to distcp, includes directories as well * This doesn't consider whether file/dir is already present and should be skipped during copy * * @return Total number of paths to distcp */ protected abstract long getNumberOfPaths(); /** * Validate the final resulting path listing. Checks if there are duplicate * entries. If preserving ACLs, checks that file system can support ACLs. * If preserving XAttrs, checks that file system can support XAttrs. * * @param pathToListFile - path listing build by doBuildListing * @param options - Input options to distcp * @throws IOException - Any issues while checking for duplicates and throws * @throws DuplicateFileException - if there are duplicates */ private void validateFinalListing(Path pathToListFile, DistCpOptions options) throws DuplicateFileException, IOException { Configuration config = getConf(); FileSystem fs = pathToListFile.getFileSystem(config); Path sortedList = DistCpUtils.sortListing(fs, config, pathToListFile); SequenceFile.Reader reader = new SequenceFile.Reader( config, SequenceFile.Reader.file(sortedList)); try { Text lastKey = new Text("*"); //source relative path can never hold * CopyListingFileStatus lastFileStatus = new CopyListingFileStatus(); Text currentKey = new Text(); Set<URI> aclSupportCheckFsSet = Sets.newHashSet(); Set<URI> xAttrSupportCheckFsSet = Sets.newHashSet(); long idx = 0; while (reader.next(currentKey)) { if (currentKey.equals(lastKey)) { CopyListingFileStatus currentFileStatus = new CopyListingFileStatus(); reader.getCurrentValue(currentFileStatus); throw new DuplicateFileException("File " + lastFileStatus.getPath() + " and " + currentFileStatus.getPath() + " would cause duplicates. Aborting"); } reader.getCurrentValue(lastFileStatus); if (options.shouldPreserve(DistCpOptions.FileAttribute.ACL)) { FileSystem lastFs = lastFileStatus.getPath().getFileSystem(config); URI lastFsUri = lastFs.getUri(); if (!aclSupportCheckFsSet.contains(lastFsUri)) { DistCpUtils.checkFileSystemAclSupport(lastFs); aclSupportCheckFsSet.add(lastFsUri); } } if (options.shouldPreserve(DistCpOptions.FileAttribute.XATTR)) { FileSystem lastFs = lastFileStatus.getPath().getFileSystem(config); URI lastFsUri = lastFs.getUri(); if (!xAttrSupportCheckFsSet.contains(lastFsUri)) { DistCpUtils.checkFileSystemXAttrSupport(lastFs); xAttrSupportCheckFsSet.add(lastFsUri); } } lastKey.set(currentKey); if (options.shouldUseDiff() && LOG.isDebugEnabled()) { LOG.debug("Copy list entry " + idx + ": " + lastFileStatus.getPath().toUri().getPath()); idx++; } } } finally { IOUtils.closeStream(reader); } } /** * Protected constructor, to initialize configuration. * @param configuration The input configuration, * with which the source/target FileSystems may be accessed. * @param credentials - Credentials object on which the FS delegation tokens are cached.If null * delegation token caching is skipped */ protected CopyListing(Configuration configuration, Credentials credentials) { setConf(configuration); setCredentials(credentials); } /** * set Credentials store, on which FS delegatin token will be cached * @param credentials - Credentials object */ protected void setCredentials(Credentials credentials) { this.credentials = credentials; } /** * get credentials to update the delegation tokens for accessed FS objects * @return Credentials object */ protected Credentials getCredentials() { return credentials; } /** * Public Factory method with which the appropriate CopyListing implementation may be retrieved. * @param configuration The input configuration. * @param credentials Credentials object on which the FS delegation tokens are cached * @param options The input Options, to help choose the appropriate CopyListing Implementation. * @return An instance of the appropriate CopyListing implementation. * @throws java.io.IOException - Exception if any */ public static CopyListing getCopyListing(Configuration configuration, Credentials credentials, DistCpOptions options) throws IOException { String copyListingClassName = configuration.get(DistCpConstants. CONF_LABEL_COPY_LISTING_CLASS, ""); Class<? extends CopyListing> copyListingClass; try { if (! copyListingClassName.isEmpty()) { copyListingClass = configuration.getClass(DistCpConstants. CONF_LABEL_COPY_LISTING_CLASS, GlobbedCopyListing.class, CopyListing.class); } else { if (options.getSourceFileListing() == null) { copyListingClass = GlobbedCopyListing.class; } else { copyListingClass = FileBasedCopyListing.class; } } copyListingClassName = copyListingClass.getName(); Constructor<? extends CopyListing> constructor = copyListingClass. getDeclaredConstructor(Configuration.class, Credentials.class); return constructor.newInstance(configuration, credentials); } catch (Exception e) { throw new IOException("Unable to instantiate " + copyListingClassName, e); } } static class DuplicateFileException extends RuntimeException { public DuplicateFileException(String message) { super(message); } } static class InvalidInputException extends RuntimeException { public InvalidInputException(String message) { super(message); } } public static class AclsNotSupportedException extends RuntimeException { public AclsNotSupportedException(String message) { super(message); } } public static class XAttrsNotSupportedException extends RuntimeException { public XAttrsNotSupportedException(String message) { super(message); } } }
wankunde/cloudera_hadoop
hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListing.java
Java
apache-2.0
11,392
/** * 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.atlas.repository; import org.apache.atlas.AtlasException; public interface ITenantRegisterationListener { /** * Callback to register the Atlas bootstrap types for tenant in MT environment. */ public void registerBootstrapTypes() throws AtlasException; }
jnhagelberg/incubator-atlas
common/src/main/java/org/apache/atlas/repository/ITenantRegisterationListener.java
Java
apache-2.0
1,100
/* * Copyright 2014-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.python; import com.facebook.buck.cxx.CxxPlatform; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.rules.RuleKeyAppendable; import com.facebook.buck.rules.RuleKeyObjectSink; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.util.HumanReadableException; import com.facebook.buck.util.immutables.BuckStyleImmutable; import com.google.common.base.Optional; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import org.immutables.value.Value; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.Set; @Value.Immutable(builder = false) @BuckStyleImmutable abstract class AbstractPythonPackageComponents implements RuleKeyAppendable { private static final PythonPackageComponents EMPTY = PythonPackageComponents.of( /* modules */ ImmutableMap.<Path, SourcePath>of(), /* resources */ ImmutableMap.<Path, SourcePath>of(), /* nativeLibraries */ ImmutableMap.<Path, SourcePath>of(), /* prebuiltLibraries */ ImmutableSet.<SourcePath>of(), /* zipSafe */ Optional.<Boolean>absent()); // Python modules as map of their module name to location of the source. @Value.Parameter public abstract Map<Path, SourcePath> getModules(); // Resources to include in the package. @Value.Parameter public abstract Map<Path, SourcePath> getResources(); // Native libraries to include in the package. @Value.Parameter public abstract Map<Path, SourcePath> getNativeLibraries(); // Pre-built python libraries (eggs, wheels). Note that source distributions // will not work! @Value.Parameter public abstract Set<SourcePath> getPrebuiltLibraries(); @Value.Parameter public abstract Optional<Boolean> isZipSafe(); @Override public final void appendToRuleKey(RuleKeyObjectSink sink) { // Hash all the input components here so we can detect changes in both input file content // and module name mappings. // TODO(andrewjcg): Change the types of these fields from Map to SortedMap so that we don't // have to do all this weird stuff to ensure the key is stable. Please update // getInputsToCompareToOutput() as well once this is fixed. for (ImmutableMap.Entry<String, Map<Path, SourcePath>> part : ImmutableMap.of( "module", getModules(), "resource", getResources(), "nativeLibraries", getNativeLibraries()).entrySet()) { for (Path name : ImmutableSortedSet.copyOf(part.getValue().keySet())) { sink.setReflectively(part.getKey() + ":" + name, part.getValue().get(name)); } } } /** * @return whether there are any native libraries included in these components. */ public boolean hasNativeCode(CxxPlatform cxxPlatform) { for (Path module : getModules().keySet()) { if (module.toString().endsWith(cxxPlatform.getSharedLibraryExtension())) { return true; } } return false; } public static PythonPackageComponents of() { return EMPTY; } /** * A helper class to construct a PythonPackageComponents instance which * throws human readable error messages on duplicates. */ public static class Builder { // A description of the entity that is building this PythonPackageComponents instance. private final BuildTarget owner; // The actual maps holding the components. private final ImmutableMap.Builder<Path, SourcePath> modules = ImmutableMap.builder(); private final ImmutableMap.Builder<Path, SourcePath> resources = ImmutableMap.builder(); private final ImmutableMap.Builder<Path, SourcePath> nativeLibraries = ImmutableMap.builder(); private final ImmutableSet.Builder<SourcePath> prebuiltLibraries = ImmutableSet.builder(); private Optional<Boolean> zipSafe = Optional.absent(); // Bookkeeping used to for error handling in the presence of duplicate // entries. These data structures map the components named above to the // entities that provided them. private final Map<Path, BuildTarget> moduleSources = new HashMap<>(); private final Map<Path, BuildTarget> resourceSources = new HashMap<>(); private final Map<Path, BuildTarget> nativeLibrarySources = new HashMap<>(); public Builder(BuildTarget owner) { this.owner = owner; } private HumanReadableException createDuplicateError( String type, Path destination, BuildTarget sourceA, BuildTarget sourceB) { return new HumanReadableException( "%s: found duplicate entries for %s %s when creating python package (%s and %s)", owner, type, destination, sourceA, sourceB); } private Builder add( String type, ImmutableMap.Builder<Path, SourcePath> builder, Map<Path, BuildTarget> sourceDescs, Path destination, SourcePath source, BuildTarget sourceDesc) { BuildTarget existing = sourceDescs.get(destination); if (existing != null) { throw createDuplicateError(type, destination, sourceDesc, existing); } builder.put(destination, source); sourceDescs.put(destination, sourceDesc); return this; } private Builder add( String type, ImmutableMap.Builder<Path, SourcePath> builder, Map<Path, BuildTarget> sourceDescs, Map<Path, SourcePath> toAdd, BuildTarget sourceDesc) { for (Map.Entry<Path, SourcePath> ent : toAdd.entrySet()) { add(type, builder, sourceDescs, ent.getKey(), ent.getValue(), sourceDesc); } return this; } public Builder addModule(Path destination, SourcePath source, BuildTarget from) { return add("module", modules, moduleSources, destination, source, from); } public Builder addModules(Map<Path, SourcePath> sources, BuildTarget from) { return add("module", modules, moduleSources, sources, from); } public Builder addResources(Map<Path, SourcePath> sources, BuildTarget from) { return add("resource", resources, resourceSources, sources, from); } public Builder addNativeLibraries(Path destination, SourcePath source, BuildTarget from) { return add( "native library", nativeLibraries, nativeLibrarySources, destination, source, from); } public Builder addNativeLibraries(Map<Path, SourcePath> sources, BuildTarget from) { return add("native library", nativeLibraries, nativeLibrarySources, sources, from); } public Builder addPrebuiltLibraries(Set<SourcePath> sources) { prebuiltLibraries.addAll(sources); return this; } public Builder addComponent(PythonPackageComponents other, BuildTarget from) { addModules(other.getModules(), from); addResources(other.getResources(), from); addNativeLibraries(other.getNativeLibraries(), from); addPrebuiltLibraries(other.getPrebuiltLibraries()); addZipSafe(other.isZipSafe()); return this; } public Builder addZipSafe(Optional<Boolean> zipSafe) { if (!this.zipSafe.isPresent() && !zipSafe.isPresent()) { return this; } this.zipSafe = Optional.of(this.zipSafe.or(true) && zipSafe.or(true)); return this; } public PythonPackageComponents build() { return PythonPackageComponents.of( modules.build(), resources.build(), nativeLibraries.build(), prebuiltLibraries.build(), zipSafe); } } }
janicduplessis/buck
src/com/facebook/buck/python/AbstractPythonPackageComponents.java
Java
apache-2.0
8,220
package com.orientechnologies.orient.server.distributed; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.orientechnologies.orient.core.db.ODatabaseSession; import com.orientechnologies.orient.core.db.OrientDB; import com.orientechnologies.orient.core.db.OrientDBConfig; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.index.OIndex; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.OElement; import com.orientechnologies.orient.core.sql.executor.OResultSet; import com.orientechnologies.orient.setup.SetupConfig; import com.orientechnologies.orient.setup.TestSetup; import com.orientechnologies.orient.setup.TestSetupUtil; import com.orientechnologies.orient.setup.configs.SimpleDServerConfig; import org.junit.After; import org.junit.Before; import org.junit.Test; public class UniqueCompositeIndexDistributedIT { private TestSetup setup; private SetupConfig config; private String server0, server1, server2; private OrientDB remote; private ODatabaseSession session; @Before public void before() throws Exception { config = new SimpleDServerConfig(); server0 = SimpleDServerConfig.SERVER0; server1 = SimpleDServerConfig.SERVER1; server2 = SimpleDServerConfig.SERVER2; setup = TestSetupUtil.create(config); setup.setup(); remote = setup.createRemote(server0, "root", "test", OrientDBConfig.defaultConfig()); remote.execute("create database test plocal users(admin identified by 'admin' role admin)"); session = remote.open("test", "admin", "admin"); OClass clazz = session.createClass("Test"); clazz.createProperty("test", OType.STRING); clazz.createProperty("testa", OType.STRING); OIndex idx = clazz.createIndex("cu", OClass.INDEX_TYPE.UNIQUE, "test", "testa"); } @Test public void test() { OElement doc = session.newElement("test"); doc.setProperty("test", "1"); doc.setProperty("testa", "2"); doc = session.save(doc); session.begin(); session.delete(doc.getIdentity()); OElement doc1 = session.newElement("test"); doc1.setProperty("test", "1"); doc1.setProperty("testa", "2"); doc1 = session.save(doc1); session.commit(); try (OResultSet res = session.query("select from test")) { assertTrue(res.hasNext()); assertEquals(res.next().getIdentity().get(), doc1.getIdentity()); } } @Test public void testUniqueInQuorum() throws InterruptedException { OElement doc = session.newElement("test"); doc.setProperty("test", "1"); doc.setProperty("testa", "2"); doc = session.save(doc); session.begin(); session.delete(doc.getIdentity()); setup.shutdownServer(SimpleDServerConfig.SERVER2); Thread.sleep(1000); OElement doc1 = session.newElement("test"); doc1.setProperty("test", "1"); doc1.setProperty("testa", "2"); doc1 = session.save(doc1); session.commit(); try (OResultSet res = session.query("select from test")) { assertTrue(res.hasNext()); assertEquals(res.next().getIdentity().get(), doc1.getIdentity()); } setup.startServer(SimpleDServerConfig.SERVER2); } @After public void after() throws InterruptedException { try { session.activateOnCurrentThread(); session.close(); remote.drop("test"); remote.close(); } finally { setup.teardown(); ODatabaseDocumentTx.closeAll(); } } }
orientechnologies/orientdb
distributed/src/test/java/com/orientechnologies/orient/server/distributed/UniqueCompositeIndexDistributedIT.java
Java
apache-2.0
3,613
package ru.job4j.loop; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * Class MaxTest тестирует метод класса Counter. * @author Goureev Ilya (mailto:ill-jah@yandex.ru) * @version 1 * @since 2017-04-08 */ public class CounterTest { /** * Тестирует метод add(). */ @Test public void testAdd() { int start = 0, finish = 10, expected = 30; Counter counter = new Counter(); int result = counter.add(start, finish); assertThat(result, is(expected)); } }
multiscripter/job4j
junior/pack1_trainee/p1_syntax/ch5_cycles/src/test/java/ru/job4j/loop/CounterTest.java
Java
apache-2.0
609
package net.argius.stew.ui.console; import java.io.*; import java.sql.*; import java.util.Map.Entry; import java.util.*; import net.argius.stew.*; /** * The Connector Editor for console mode. */ public final class ConnectorMapEditor { private static final ResourceManager res = ResourceManager.getInstance(ConnectorMapEditor.class); private static final String[] PROP_KEYS = {"name", "classpath", "driver", "url", "user", "password", "readonly", "rollback"}; private final ConnectorMap map; private ConnectorMap oldContent; private ConnectorMapEditor() throws IOException { ConnectorMap m; try { m = ConnectorConfiguration.load(); } catch (FileNotFoundException ex) { printMessage("main.notice.filenotexists"); printLine(String.format("(%s)", ex.getMessage())); m = new ConnectorMap(); } this.oldContent = m; this.map = new ConnectorMap(this.oldContent); } /** * Processes to input properties. * @param id * @param props * @return true if the configuration was changed, otherwise false. */ private static boolean proceedInputProperties(String id, Properties props) { while (true) { printMessage("property.start1"); printMessage("property.start2"); for (String key : PROP_KEYS) { String value = props.getProperty(key); print(res.get("property.input", key, value)); String input = getInput(""); if (input != null && input.length() > 0) { props.setProperty(key, input); } } for (String key : PROP_KEYS) { printLine(key + "=" + props.getProperty(key)); } if (confirmYes("property.tryconnect.confirm")) { try { Connector c = new Connector(id, props); c.getConnection(); printMessage("property.tryconnect.succeeded"); } catch (SQLException ex) { printMessage("property.tryconnect.failed", ex.getMessage()); } } if (confirmYes("property.update.confirm")) { return true; } if (!confirmYes("property.retry.confirm")) { printMessage("property.update.cancel"); return false; } } } /** * Adds a Connector. * @param id */ private void proceedAdd(String id) { if (map.containsKey(id)) { printMessage("proc.alreadyexists", id); return; } Properties props = new Properties(); // setting default for (String key : PROP_KEYS) { props.setProperty(key, ""); } if (proceedInputProperties(id, props)) { map.put(id, new Connector(id, props)); printMessage("proc.added", id); } } /** * Modifies a Connector. * @param id */ private void proceedModify(String id) { if (!map.containsKey(id)) { printMessage("proc.notexists", id); return; } Properties props = map.getConnector(id).toProperties(); if (proceedInputProperties(id, props)) { map.put(id, new Connector(id, props)); printMessage("proc.modified", id); } } /** * Deletes a Connector. * @param id */ private void proceedRemove(String id) { Connector connector = map.getConnector(id); printLine("ID[" + id + "]:" + connector.getName()); if (confirmYes("proc.remove.confirm")) { map.remove(id); printMessage("proc.remove.finished"); } else { printMessage("proc.remove.canceled"); } printLine(map); } /** * Copies from a Connector to another. * @param src * @param dst */ private void proceedCopy(String src, String dst) { if (!map.containsKey(src)) { printMessage("proc.notexists", src); printMessage("proc.copy.canceled"); return; } if (map.containsKey(dst)) { printMessage("proc.alreadyexists", dst); printMessage("proc.copy.canceled"); return; } map.put(dst, new Connector(dst, map.getConnector(src))); printMessage("proc.copy.finished"); } /** * Displays all of the Connectors. */ private void proceedDisplayIds() { for (Entry<String, Connector> entry : map.entrySet()) { String id = entry.getKey(); printLine(String.format("%10s : %s", id, map.getConnector(id).getName())); } } /** * Displays the Connector info specified by ID. * @param id */ private void proceedDisplayDetail(String id) { if (!map.containsKey(id)) { printMessage("proc.notexists", id); return; } Properties props = map.getConnector(id).toProperties(); for (String key : PROP_KEYS) { printLine(String.format("%10s : %s", key, props.getProperty(key))); } } /** * Saves the configuration to a file. * @throws IOException */ private void proceedSave() throws IOException { if (map.equals(oldContent)) { printMessage("proc.nomodification"); } else if (confirmYes("proc.save.confirm")) { ConnectorConfiguration.save(map); oldContent = new ConnectorMap(map); printMessage("proc.save.finished"); } else { printMessage("proc.save.canceled"); } } /** * Loads from file. * @throws IOException */ private void proceedLoad() throws IOException { ConnectorMap m = ConnectorConfiguration.load(); if (m.equals(oldContent) && m.equals(map)) { printMessage("proc.nomodification"); return; } printMessage("proc.load.confirm1"); if (confirmYes("proc.load.confirm2")) { map.clear(); map.putAll(ConnectorConfiguration.load()); printMessage("proc.load.finished"); } else { printMessage("proc.load.canceled"); } } /** * Returns the input string from STDIN. * @param messageId * @param args * @return */ private static String getInput(String messageId, Object... args) { if (messageId.length() > 0) { print(res.get(messageId, args)); } print(res.get("proc.prompt")); Scanner scanner = new Scanner(System.in); if (scanner.hasNextLine()) { return scanner.nextLine(); } return ""; } /** * Returns the result to confirm Yes or No as boolean. * @param messageId * @return */ private static boolean confirmYes(String messageId) { if (messageId.length() > 0) { print(res.get(messageId)); } print("(y/N)"); return getInput("").equalsIgnoreCase("y"); } private static void print(Object o) { System.out.print(o); } private static void printLine() { System.out.println(); } private static void printLine(Object o) { System.out.println(o); } private static void printMessage(String messageId, Object... args) { printLine(res.get(messageId, args)); } /** * Invokes this editor. */ static void invoke() { printLine(); printMessage("main.start"); printLine(); try { ConnectorMapEditor editor = new ConnectorMapEditor(); while (true) { Parameter p = new Parameter(getInput("main.wait")); final String command = p.at(0); final String id = p.at(1); if (command.equalsIgnoreCase("help")) { printMessage("help"); } else if (command.equalsIgnoreCase("a")) { editor.proceedAdd(id); } else if (command.equalsIgnoreCase("m")) { editor.proceedModify(id); } else if (command.equalsIgnoreCase("r")) { editor.proceedRemove(id); } else if (command.equalsIgnoreCase("copy")) { editor.proceedCopy(id, p.at(2)); } else if (command.equalsIgnoreCase("disp")) { if (id.length() == 0) { editor.proceedDisplayIds(); } else { editor.proceedDisplayDetail(id); } } else if (command.equalsIgnoreCase("save")) { editor.proceedSave(); } else if (command.equalsIgnoreCase("load")) { editor.proceedLoad(); } else if (command.equalsIgnoreCase("exit")) { if (editor.map.equals(editor.oldContent)) { break; } else if (confirmYes("proc.exit.confirm")) { break; } } printLine(); } } catch (Throwable th) { th.printStackTrace(); } printLine(); printMessage("main.end"); } /** * @param args */ public static void main(String... args) { System.out.println("Stew " + Bootstrap.getVersion()); invoke(); } }
argius/Stew4
src/net/argius/stew/ui/console/ConnectorMapEditor.java
Java
apache-2.0
9,689
package org.valuereporter.sla; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Component; import org.valuereporter.ValuereporterInputException; import org.valuereporter.helper.StatusType; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.List; /** * @author <a href="mailto:bard.lind@gmail.com">Bard Lind</a> */ @Component public class SlaDao { private static final Logger log = LoggerFactory.getLogger(SlaDao.class); private JdbcTemplate jdbcTemplate; @Autowired public SlaDao(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public List<UsageStatistics> findUsage(String prefix, String methodFilter, DateTime start, DateTime end) { String sql = "select ok.prefix, ok.methodName, oi.duration,oi.startTime, oi.count, oi.max, oi.min, oi.mean, oi.median, oi.stdDev, oi.p95, oi.p98, oi.p99 \n" + " from ObservedInterval oi, ObservedKeys ok \n" + " where oi.startTime >= ? and oi.startTime <= ? and ok.prefix= ? and ok.methodName= ? and ok.id = oi.observedKeysId \n" + " order by oi.startTime asc"; // end = new DateTime(1411557199907L).plusDays(1); Timestamp endTime = null; Timestamp startTime = null; if (end == null) { end = new DateTime(); } if (start == null) { start = end.minusDays(7); } endTime = new Timestamp(end.getMillis()); startTime = new Timestamp(start.getMillis()); Object[] parameters = new Object[] {startTime, endTime,prefix,methodFilter}; List<UsageStatistics> usageStatisticses = jdbcTemplate.query(sql, parameters, new RowMapper<UsageStatistics>() { @Override public UsageStatistics mapRow(ResultSet resultSet, int i) throws SQLException { UsageStatistics usageStatistics = new UsageStatistics( resultSet.getString(1), resultSet.getString(2), resultSet.getLong(3), resultSet.getTimestamp(4).getTime(), resultSet.getLong(5), resultSet.getLong(6), resultSet.getLong(7), resultSet.getDouble(8), resultSet.getDouble(9), resultSet.getDouble(10), resultSet.getDouble(11), resultSet.getDouble(12), resultSet.getDouble(13)); return usageStatistics; } }); return usageStatisticses; } public List<SlaStatistics> findSlaStatistics(String prefix, String methodName, DateTime start, DateTime end){ String sql = "select oi.startTime,oi.duration, oi.count, oi.max, oi.min, oi.mean, oi.p95 \n" + " from ObservedInterval oi, ObservedKeys ok \n" + " where oi.startTime >= ? and oi.startTime <= ? and ok.prefix= ? and ok.methodName= ? and ok.id = oi.observedKeysId \n" + " order by oi.startTime desc"; if (isInValid(prefix) || isInValid(methodName) || isInValidDate(start) || isInValidDate(end)) { log.trace("Invalid values for one of prefix {}, methodName {}, start {}, end {}. Will throw exception.", prefix, methodName, start, end); throw new ValuereporterInputException("Invalid data for prefix " + prefix + ", methodName " + methodName + ",startDate " + start + ", or endDate " +end, StatusType.data_error); } Timestamp endTime = new Timestamp(end.getMillis()); Timestamp startTime = new Timestamp(start.getMillis()); Object[] parameters = new Object[] {startTime, endTime,prefix,methodName}; List<SlaStatistics> slaStatisticses = jdbcTemplate.query(sql, parameters, new RowMapper<SlaStatistics>() { @Override public SlaStatistics mapRow(ResultSet resultSet, int i) throws SQLException { SlaStatistics slaStatistics = new SlaStatistics( resultSet.getTimestamp(1).getTime(), resultSet.getLong(2), resultSet.getLong(3), resultSet.getDouble(4), resultSet.getDouble(5), resultSet.getDouble(6), resultSet.getDouble(7)); return slaStatistics; } }); return slaStatisticses; } boolean isValidDate(DateTime date) { return (date != null); } boolean isInValidDate(DateTime date) { return !isValidDate(date); } boolean isValid(String value) { return (value != null && !value.trim().isEmpty()); } boolean isInValid(String value) { return !isValid(value); } }
altran/Valuereporter
src/main/java/org/valuereporter/sla/SlaDao.java
Java
apache-2.0
5,160
package org.springframework.cloud.netflix.zuul.filters; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.TestRestTemplate; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.cloud.netflix.zuul.RoutesEndpoint; import org.springframework.cloud.netflix.zuul.ZuulProxyConfiguration; import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator; import org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import com.netflix.zuul.context.RequestContext; import static junit.framework.TestCase.assertFalse; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = SampleCustomZuulProxyApplication.class) @WebAppConfiguration @IntegrationTest({ "server.port: 0", "server.contextPath: /app" }) @DirtiesContext public class CustomHostRoutingFilterTests { @Value("${local.server.port}") private int port; @Autowired private DiscoveryClientRouteLocator routes; @Autowired private RoutesEndpoint endpoint; @Before public void setTestRequestcontext() { RequestContext context = new RequestContext(); RequestContext.testSetCurrentContext(context); } @Test public void getOnSelfViaCustomHostRoutingFilter() { this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/app"); this.endpoint.reset(); ResponseEntity<String> result = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/app/self/get/1", String.class); assertEquals(HttpStatus.OK, result.getStatusCode()); assertEquals("Get 1", result.getBody()); } @Test public void postOnSelfViaCustomHostRoutingFilter() { this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/app"); this.endpoint.reset(); MultiValueMap<String, Object> params = new LinkedMultiValueMap<>(); params.add("id", "2"); ResponseEntity<String> result = new TestRestTemplate().postForEntity( "http://localhost:" + this.port + "/app/self/post", params, String.class); assertEquals(HttpStatus.OK, result.getStatusCode()); assertEquals("Post 2", result.getBody()); } @Test public void putOnSelfViaCustomHostRoutingFilter() { this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/app"); this.endpoint.reset(); ResponseEntity<String> result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/app/self/put/3", HttpMethod.PUT, new HttpEntity<>((Void) null), String.class); assertEquals(HttpStatus.OK, result.getStatusCode()); assertEquals("Put 3", result.getBody()); } @Test public void patchOnSelfViaCustomHostRoutingFilter() { this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/app"); this.endpoint.reset(); MultiValueMap<String, Object> params = new LinkedMultiValueMap<>(); params.add("patch", "5"); ResponseEntity<String> result = new TestRestTemplate().exchange( "http://localhost:" + this.port + "/app/self/patch/4", HttpMethod.PATCH, new HttpEntity<>(params), String.class); assertEquals(HttpStatus.OK, result.getStatusCode()); assertEquals("Patch 45", result.getBody()); } @Test public void getOnSelfIgnoredHeaders() { this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/app"); this.endpoint.reset(); ResponseEntity<String> result = new TestRestTemplate().getForEntity( "http://localhost:" + this.port + "/app/self/get/1", String.class); assertEquals(HttpStatus.OK, result.getStatusCode()); assertTrue(result.getHeaders().containsKey("X-NotIgnored")); assertFalse(result.getHeaders().containsKey("X-Ignored")); } @Test public void getOnSelfWithSessionCookie() { this.routes.addRoute("/self/**", "http://localhost:" + this.port + "/app"); this.endpoint.reset(); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> result1 = restTemplate.getForEntity( "http://localhost:" + this.port + "/app/self/cookie/1", String.class); ResponseEntity<String> result2 = restTemplate.getForEntity( "http://localhost:" + this.port + "/app/self/cookie/2", String.class); assertEquals("SetCookie 1", result1.getBody()); assertEquals("GetCookie 1", result2.getBody()); } } @Configuration @EnableAutoConfiguration @RestController class SampleCustomZuulProxyApplication { @RequestMapping(value = "/get/{id}", method = RequestMethod.GET) public String get(@PathVariable String id, HttpServletResponse response) { response.setHeader("X-Ignored", "foo"); response.setHeader("X-NotIgnored", "bar"); return "Get " + id; } @RequestMapping(value = "/cookie/{id}", method = RequestMethod.GET) public String getWithCookie(@PathVariable String id, HttpSession session) { Object testCookie = session.getAttribute("testCookie"); if (testCookie != null) { return "GetCookie " + testCookie; } session.setAttribute("testCookie", id); return "SetCookie " + id; } @RequestMapping(value = "/post", method = RequestMethod.POST) public String post(@RequestParam("id") String id) { return "Post " + id; } @RequestMapping(value = "/put/{id}", method = RequestMethod.PUT) public String put(@PathVariable String id) { return "Put " + id; } @RequestMapping(value = "/patch/{id}", method = RequestMethod.PATCH) public String patch(@PathVariable String id, @RequestParam("patch") String patch) { return "Patch " + id + patch; } public static void main(String[] args) { SpringApplication.run(SampleCustomZuulProxyApplication.class, args); } @Configuration @EnableZuulProxy protected static class CustomZuulProxyConfig extends ZuulProxyConfiguration { @Bean @Override public SimpleHostRoutingFilter simpleHostRoutingFilter( ProxyRequestHelper helper, ZuulProperties zuulProperties) { return new CustomHostRoutingFilter(helper, zuulProperties); } private class CustomHostRoutingFilter extends SimpleHostRoutingFilter { public CustomHostRoutingFilter(ProxyRequestHelper helper, ZuulProperties zuulProperties) { super(helper, zuulProperties); } @Override public Object run() { super.addIgnoredHeaders("X-Ignored"); return super.run(); } @Override protected CloseableHttpClient newClient() { // Custom client with cookie support. // In practice, we would want a custom cookie store using a multimap with // a user key. return HttpClients.custom().setConnectionManager(newConnectionManager()) .setDefaultCookieStore(new BasicCookieStore()) .setDefaultRequestConfig(RequestConfig.custom() .setCookieSpec(CookieSpecs.DEFAULT).build()) .build(); } } } }
daniellavoie/spring-cloud-netflix
spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/zuul/filters/CustomHostRoutingFilterTests.java
Java
apache-2.0
8,405
package org.jerlang.erts.emulator.op; import static org.junit.Assert.assertEquals; import org.jerlang.FunctionSignature; import org.jerlang.erts.Erlang; import org.jerlang.exception.ThrowException; import org.jerlang.type.Atom; import org.jerlang.type.Boolean; import org.jerlang.type.Fun; import org.jerlang.type.Integer; import org.jerlang.type.List; import org.jerlang.type.Map; import org.jerlang.type.Term; import org.junit.Test; public class IsFunctionTest extends AbstractOpTest { private FunctionSignature fs1 = new FunctionSignature("m", "f", 1); private List params1 = List.of(new Fun(null, null)); private List params2 = List.of(new Map()); private List params3 = List.of(new Fun(fs1, null), Integer.of(1)); private List params4 = List.of(new Fun(fs1, null), Integer.of(2)); private List params5 = List.of(new Map(), Integer.of(1)); public IsFunctionTest() { super("is_fun.beam"); } @Test public void test1() throws ThrowException { Term result1 = Erlang.apply(Atom.of("is_fun"), Atom.of("is_fun1"), params1); assertEquals(Boolean.am_true, result1); Term result2 = Erlang.apply(Atom.of("is_fun"), Atom.of("is_fun1"), params2); assertEquals(Boolean.am_false, result2); } @Test public void test2() throws ThrowException { Term result3 = Erlang.apply(Atom.of("is_fun"), Atom.of("is_fun2"), params3); assertEquals(Boolean.am_true, result3); Term result4 = Erlang.apply(Atom.of("is_fun"), Atom.of("is_fun2"), params4); assertEquals(Boolean.am_false, result4); Term result5 = Erlang.apply(Atom.of("is_fun"), Atom.of("is_fun2"), params5); assertEquals(Boolean.am_false, result5); } }
jerlang/jerlang
src/test/java/org/jerlang/erts/emulator/op/IsFunctionTest.java
Java
apache-2.0
1,745
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2008-2022 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.codehaus.griffon.runtime.core.env; import griffon.core.env.Environment; import griffon.core.env.Metadata; import javax.inject.Inject; import javax.inject.Provider; /** * @author Andres Almiray * @since 2.2.0 */ public class EnvironmentProvider implements Provider<Environment> { @Inject private Metadata metadata; private static boolean isBlank(String value) { return value == null || value.trim().length() == 0; } @Override public Environment get() { String envName = System.getProperty(Environment.KEY); if (metadata != null && isBlank(envName)) { envName = metadata.getEnvironment(); } if (isBlank(envName)) { return Environment.DEVELOPMENT; } Environment env = Environment.resolveEnvironment(envName); if (env == null) { try { env = Environment.valueOf(envName.toUpperCase()); } catch (IllegalArgumentException e) { // ignore } } if (env == null) { env = Environment.CUSTOM; env.setName(envName); } return env; } }
griffon/griffon
subprojects/griffon-core-impl/src/main/java/org/codehaus/griffon/runtime/core/env/EnvironmentProvider.java
Java
apache-2.0
1,843
package com.jukusoft.rpg.core.asset; /** * Created by Justin on 29.11.2016. */ public interface AssetCleanUpListener { /** * cleanUp asset * * @param assetID local unique asset ID * @param asset instance of asset */ public void cleanUp (final long assetID, final Asset asset); }
JuKu/rpg-2dgame-engine
rpg-core/src/main/java/com/jukusoft/rpg/core/asset/AssetCleanUpListener.java
Java
apache-2.0
315
package edu.uw.zookeeper.protocol.client; import java.lang.ref.Reference; import java.util.Iterator; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicReference; import org.apache.logging.log4j.Logger; import com.google.common.base.MoreObjects; import com.google.common.collect.Queues; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import edu.uw.zookeeper.common.Actors; import edu.uw.zookeeper.common.Automaton; import edu.uw.zookeeper.common.Promise; import edu.uw.zookeeper.common.PromiseTask; import edu.uw.zookeeper.common.TimeValue; import edu.uw.zookeeper.net.Connection; import edu.uw.zookeeper.protocol.Message; import edu.uw.zookeeper.protocol.ConnectMessage; import edu.uw.zookeeper.protocol.Operation; import edu.uw.zookeeper.protocol.ProtocolConnection; import edu.uw.zookeeper.protocol.proto.OpCodeXid; public abstract class PendingQueueClientExecutor< I extends Operation.Request, O extends Operation.ProtocolResponse<?>, T extends PendingQueueClientExecutor.RequestTask<I,O>, C extends ProtocolConnection<? super Message.ClientSession, ? extends Operation.Response,?,?,?>, V extends PendingQueueClientExecutor.PendingTask> extends AbstractConnectionClientExecutor<I,O,T,C,V> { protected final Pending<O,V,C> pending; protected PendingQueueClientExecutor( Logger logger, ListenableFuture<ConnectMessage.Response> session, C connection, TimeValue timeOut, ScheduledExecutorService scheduler) { super(session, connection, timeOut, scheduler); this.pending = Pending.<O,V,C>create(connection, this, logger); } protected PendingQueueClientExecutor( Logger logger, ListenableFuture<ConnectMessage.Response> session, C connection, Listeners listeners, TimeOutServer<Operation.Response> timer, AtomicReference<Throwable> failure) { super(session, connection, listeners, timer, failure); this.pending = Pending.<O,V,C>create(connection, this, logger); } @Override public void handleConnectionRead(Operation.Response message) { super.handleConnectionRead(message); pending.handleConnectionRead(message); } @Override public void handleConnectionState(Automaton.Transition<Connection.State> event) { super.handleConnectionState(event); pending.handleConnectionState(event); } @Override protected void doStop() { pending.stop(); super.doStop(); } protected Executor executor() { return connection; } public static class PendingTask extends PromiseTask<Reference<? extends Message.ClientRequest<?>>, Message.ServerResponse<?>> implements Operation.RequestId, FutureCallback<Message.ClientRequest<?>> { public static PendingTask create( Reference<? extends Message.ClientRequest<?>> task, Promise<Message.ServerResponse<?>> delegate) { return new PendingTask(task, delegate); } protected final int xid; public PendingTask( Reference<? extends Message.ClientRequest<?>> task, Promise<Message.ServerResponse<?>> delegate) { super(task, delegate); this.xid = task().get().xid(); } @Override public int xid() { return xid; } public Message.ClientRequest<?> getRequest() { return task().get(); } @Override public void onSuccess(Message.ClientRequest<?> result) { } @Override public void onFailure(Throwable t) { setException(t); } @Override protected MoreObjects.ToStringHelper toStringHelper(MoreObjects.ToStringHelper toString) { return super.toStringHelper(toString.add("xid", xid)); } } public static class PendingPromiseTask extends PendingTask { public static PendingPromiseTask create( Promise<Message.ServerResponse<?>> promise, Reference<? extends Message.ClientRequest<?>> task, Promise<Message.ServerResponse<?>> delegate) { return new PendingPromiseTask(promise, task, delegate); } protected final Promise<Message.ServerResponse<?>> promise; public PendingPromiseTask( Promise<Message.ServerResponse<?>> promise, Reference<? extends Message.ClientRequest<?>> task, Promise<Message.ServerResponse<?>> delegate) { super(task, delegate); this.promise = promise; } public Promise<Message.ServerResponse<?>> getPromise() { return promise; } } public static class Pending< O extends Operation.ProtocolResponse<?>, T extends PendingTask, C extends ProtocolConnection<? super Message.ClientSession, ? extends Operation.Response,?,?,?>> extends Actors.ExecutedPeekingQueuedActor<T> implements Connection.Listener<Operation.Response> { public static <O extends Operation.ProtocolResponse<?>,T extends PendingTask,C extends ProtocolConnection<? super Message.ClientSession, ? extends Operation.Response,?,?,?>> Pending<O,T,C> create( C connection, FutureCallback<? super T> callback, Logger logger) { return new Pending<O,T,C>(connection, callback, Queues.<T>newConcurrentLinkedQueue(), logger); } protected final FutureCallback<? super T> callback; protected final C connection; protected Pending( C connection, FutureCallback<? super T> callback, Queue<T> mailbox, Logger logger) { super(connection, mailbox, logger); this.callback = callback; this.connection = connection; } @Override protected synchronized boolean doSend(T message) { // we use synchronized to preserve queue/send ordering // task needs to be in the queue before calling write if (! mailbox.offer(message)) { return false; } try { if (! message.isDone()) { // mark pings as done on send because ZooKeeper doesn't care about their ordering if (message.xid() == OpCodeXid.PING.xid()) { message.set(null); } Message.ClientRequest<?> request = message.getRequest(); if (request != null) { ListenableFuture<? extends Message.ClientRequest<?>> writeFuture = connection.write(request); Futures.addCallback(writeFuture, message); } } } catch (Throwable t) { message.onFailure(t); } if (state() == State.TERMINATED) { message.cancel(true); apply(message); } if (! message.isDone()) { message.addListener(this, executor); } else { run(); } return true; } @Override public void handleConnectionRead(Operation.Response message) { if (message instanceof Message.ServerResponse<?>) { int xid = ((Message.ServerResponse<?>) message).xid(); if (! ((xid == OpCodeXid.PING.xid()) || (xid == OpCodeXid.NOTIFICATION.xid()))) { Iterator<T> tasks = mailbox.iterator(); T task = null; while (tasks.hasNext()) { T next = tasks.next(); if ((next.xid() == xid) && !next.isDone()) { task = next; break; } } if (task != null) { task.set((Message.ServerResponse<?>) message); } else if (state() != State.TERMINATED) { // This could happen if someone submitted a message without // going through us // or, it could be a bug logger.warn("{} xid doesn't match {} ({})", message, mailbox.peek(), this); } } } } @Override public void handleConnectionState(Automaton.Transition<Connection.State> state) { // TODO } public boolean isReady() { T next = mailbox.peek(); return ((next != null) && next.isDone()); } @Override public String toString() { return MoreObjects.toStringHelper(this).addValue(callback).toString(); } @Override protected void doStop() { T task; while ((task = mailbox.peek()) != null) { task.cancel(true); apply(task); } } @Override protected synchronized boolean apply(T input) { if (input.isDone()) { if (mailbox.remove(input)) { callback.onSuccess(input); return true; } } return false; } } public abstract class ForwardingActor extends Actors.ExecutedQueuedActor<T> { protected ForwardingActor(Executor executor, Logger logger) { super(executor, new ConcurrentLinkedQueue<T>(), logger); } public Logger logger() { return logger; } @Override protected void doStop() { PendingQueueClientExecutor.this.doStop(); T request; while ((request = mailbox.poll()) != null) { request.cancel(true); } } @Override public String toString() { return MoreObjects.toStringHelper(this).addValue(PendingQueueClientExecutor.this).toString(); } } }
lisaglendenning/zookeeper-lite
zkclient/src/main/java/edu/uw/zookeeper/protocol/client/PendingQueueClientExecutor.java
Java
apache-2.0
10,634
package com.github.xjtushilei.example; import com.github.xjtushilei.core.Spider; import com.github.xjtushilei.core.pageprocesser.PageProcessor; import com.github.xjtushilei.core.saver.Saver; import com.github.xjtushilei.core.scheduler.PreDefine.RedisScheduler; import com.github.xjtushilei.model.Page; import org.jsoup.nodes.Document; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; /** * Created by shilei on 2017/4/12. */ public class RedisSpider { public static void main(String[] args) { Spider.build() .setScheduler(new RedisScheduler()) //配置个性化的ip等请使用 RedisScheduler(String ip, int port, int MaxActive(建议100)) .setSaver(mySaver) .setProcessor(myPageProcessor) .thread(5) .addUrlSeed("http://news.xjtu.edu.cn") .addRegexRule("+http://news.xjtu.edu.cn/.*") //限制爬取《交大新闻网》以外的其他站点的信息 .run(); } /** * 一个输出到控制台的 存储器。 * 您可以替换这段代码,将爬取到的结果放入到mongodb,mysql等等中! */ static Saver mySaver = new Saver() { @Override public void save(Page page) { Map<Object, Object> map = page.getItems(); map.forEach((k, v) -> System.out.println(k + " : " + v)); } }; /** * 实现自己逻辑的页面解析功能!将标题打印出来。 * <p> * 这里是在一个文件里实现的,若果你的功能比较多,完全可以用新的class文件来生成,并在上面setPageProcessor即可! */ static PageProcessor myPageProcessor = new PageProcessor() { @Override public void process(Page page) { //如果不匹配,则不进行解析! if (!Pattern.matches("http://news.xjtu.edu.cn/info/.*htm", page.getUrlSeed().getUrl())) { return; } Document htmldoc = page.getDocument(); //select返回的是一个数组,所以需要first,相关语法请google“jsoup select语法”和“cssquery” try { String title = htmldoc.select(".d_title").first().text(); //用来存放爬取到的信息,供之后存储!map类型的即可,可以自定义各种嵌套! Map<String, String> items = new HashMap<String, String>(); items.put("title", title); items.put("url", page.getUrlSeed().getUrl()); //放入items中,之后会自动保存(如果你自己实现了下载器,请自己操作它。如下我自定义了自己的下载器,并将它保存到了文本中!)! page.setItems(items); } catch (NullPointerException e) { System.out.println("该页面没有解析到相关东西!跳过"); } } }; }
xjtushilei/ScriptSpider
src/main/java/com/github/xjtushilei/example/RedisSpider.java
Java
apache-2.0
2,988
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.streamsets.pipeline.stage.processor.fieldtypeconverter; import com.streamsets.pipeline.api.ListBeanModel; import com.streamsets.pipeline.api.ConfigDef; import com.streamsets.pipeline.api.ConfigDef.Type; import com.streamsets.pipeline.api.ConfigGroups; import com.streamsets.pipeline.api.GenerateResourceBundle; import com.streamsets.pipeline.api.Processor; import com.streamsets.pipeline.api.StageDef; import com.streamsets.pipeline.configurablestage.DProcessor; import java.util.List; @StageDef( version=1, label="Field Converter", description = "Converts the data type of a field", icon="converter.png" ) @ConfigGroups(Groups.class) @GenerateResourceBundle public class FieldTypeConverterDProcessor extends DProcessor { @ConfigDef( required = false, type = Type.MODEL, defaultValue="", label = "", description = "", displayPosition = 10, group = "TYPE_CONVERSION" ) @ListBeanModel public List<FieldTypeConverterConfig> fieldTypeConverterConfigs; @Override protected Processor createProcessor() { return new FieldTypeConverterProcessor((fieldTypeConverterConfigs)); } }
kiritbasu/datacollector
basic-lib/src/main/java/com/streamsets/pipeline/stage/processor/fieldtypeconverter/FieldTypeConverterDProcessor.java
Java
apache-2.0
1,971
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org) * * 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.jkiss.dbeaver.model.exec; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import java.util.List; /** * Result set table metadata */ public interface DBCEntityMetaData { @Nullable String getCatalogName(); @Nullable String getSchemaName(); /** * Entity name */ @NotNull String getEntityName(); /** * Meta attributes which belongs to this entity */ @NotNull List<? extends DBCAttributeMetaData> getAttributes(); }
ruspl-afed/dbeaver
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/exec/DBCEntityMetaData.java
Java
apache-2.0
1,217
/* * Copyright 2011 Corpuslinguistic working group Humboldt University Berlin. * * 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.corpus_tools.annis.gui.exporter; import com.google.common.eventbus.EventBus; import com.vaadin.ui.UI; import java.io.Writer; import java.util.List; import java.util.Map; import java.util.Set; import org.corpus_tools.annis.api.model.CorpusConfiguration; import org.corpus_tools.annis.api.model.QueryLanguage; /** * * @author Thomas Krause {@literal <krauseto@hu-berlin.de>} */ public interface ExporterPlugin { public Exception convertText(String query, QueryLanguage queryLanguage, int contextLeft, int contextRight, Set<String> corpora, List<String> keys, String args, boolean alignmc, Writer out, EventBus eventBus, Map<String, CorpusConfiguration> corpusConfigs, UI ui); public String getFileEnding(); public String getHelpMessage(); public boolean isAlignable(); public boolean isCancelable(); public boolean needsContext(); }
korpling/ANNIS
src/main/java/org/corpus_tools/annis/gui/exporter/ExporterPlugin.java
Java
apache-2.0
1,516
package de.afinke.blog.camel; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.main.Main; public class CamelRestCaller extends Main { public static void main(String[] args) throws Exception { CamelRestCaller main = new CamelRestCaller(); main.addRouteBuilder(createRouteBuilder()); main.run(args); } static RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() throws Exception { from("timer://foo?fixedRate=true&period=5s") .setHeader(Exchange.HTTP_QUERY, constant("userId=1")) .to("http4://jsonplaceholder.typicode.com/posts") .to("stream:out"); } }; } }
achim86/blog
camel/camel-rest-call/src/main/java/de/afinke/blog/camel/CamelRestCaller.java
Java
apache-2.0
829
package com.juanco.servicio.simple; import com.juanco.servicio.simple.dto.ErrorDto; import com.juanco.servicio.simple.dto.RespuestaAleatorios; import java.util.ArrayList; import java.util.List; import java.util.Random; import javax.jws.WebService; /** * Implementación del servicio simple. * * @author Juan C. Orozco <juanco89@gmail.com> */ @WebService( serviceName = "ServicioSimple", endpointInterface = "com.juanco.servicio.simple.IServicioSimple" ) public class ServicioSimple implements IServicioSimple { @Override public String saludar(String nombre) { return "¡Hola " + nombre + "!"; } @Override public long sumar(int a, int b) { return a + b; } @Override public RespuestaAleatorios generarAleatorios(int cantidad) { RespuestaAleatorios respuesta = new RespuestaAleatorios(); if(cantidad <= 0) { respuesta.setExitosa(false); respuesta.setError(new ErrorDto(1, "Parámetros incorrectos")); return respuesta; } Random rnd = new Random(System.currentTimeMillis()); List<String> aleatorios = new ArrayList<>(); for (int i = 0; i < cantidad; i++) { aleatorios.add( String.valueOf(rnd.nextInt() * 100) ); } respuesta.setExitosa(true); respuesta.setAleatorios(aleatorios); return respuesta; } }
juanco89/cliente-ws-cpp
servicio/src/java/com/juanco/servicio/simple/ServicioSimple.java
Java
apache-2.0
1,458

Dataset Card for "java_10"

More Information needed

Downloads last month
0
Edit dataset card