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
/* Generated By:JavaCC: Do not edit this line. PigScriptParser.java */ package org.apache.pig.tools.pigscript.parser; import java.io.IOException; import java.io.InputStream; import java.util.Stack; import java.util.List; import java.util.ArrayList; import jline.ConsoleReader; public abstract class PigScriptParser implements PigScriptParserConstants { protected boolean mInteractive; protected ConsoleReader mConsoleReader; public void setInteractive(boolean interactive) { mInteractive = interactive; token_source.interactive = interactive; } public int getLineNumber() { return jj_input_stream.getBeginLine(); } public void setConsoleReader(ConsoleReader c) { mConsoleReader = c; token_source.consoleReader = c; } abstract public void prompt(); abstract protected void quit(); abstract protected void printAliases() throws IOException; abstract protected void processFsCommand(String[] cmdTokens) throws IOException; abstract protected void processDescribe(String alias) throws IOException; abstract protected void processExplain(String alias, String script, boolean isVerbose, String format, String target, List<String> params, List<String> files) throws IOException, ParseException; abstract protected void processRegister(String jar) throws IOException; abstract protected void processSet(String key, String value) throws IOException, ParseException; abstract protected void processCat(String path) throws IOException; abstract protected void processCD(String path) throws IOException; abstract protected void processDump(String alias) throws IOException; abstract protected void processKill(String jobid) throws IOException; abstract protected void processLS(String path) throws IOException; abstract protected void processPWD() throws IOException; abstract protected void printHelp(); abstract protected void processMove(String src, String dst) throws IOException; abstract protected void processCopy(String src, String dst) throws IOException; abstract protected void processCopyToLocal(String src, String dst) throws IOException; abstract protected void processCopyFromLocal(String src, String dst) throws IOException; abstract protected void processMkdir(String dir) throws IOException; abstract protected void processPig(String cmd) throws IOException; abstract protected void processRemove(String path, String opt) throws IOException; abstract protected void processIllustrate(String alias) throws IOException; abstract protected void processScript(String script, boolean batch, List<String> params, List<String> files) throws IOException, ParseException; static String unquote(String s) { if (s.charAt(0) == '\u005c'' && s.charAt(s.length()-1) == '\u005c'') return s.substring(1, s.length()-1); else return s; } final public void parse() throws ParseException, IOException { Token t1, t2; String val = null; List<String> cmdTokens = new ArrayList<String>(); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case EOL: jj_consume_token(EOL); prompt(); break; case FS: jj_consume_token(FS); label_1: while (true) { t1 = GetPath(); cmdTokens.add(t1.image); while(true){ try{ t1=GetPath(); cmdTokens.add(t1.image); }catch(ParseException e){ break; } } processFsCommand(cmdTokens.toArray(new String[cmdTokens.size()])); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case CAT: case CD: case COPY: case COPYFROMLOCAL: case COPYTOLOCAL: case DUMP: case DESCRIBE: case ALIASES: case EXPLAIN: case HELP: case KILL: case LS: case MOVE: case MKDIR: case PWD: case QUIT: case REGISTER: case REMOVE: case SET: case RUN: case EXEC: case SCRIPT_DONE: case IDENTIFIER: case PATH: ; break; default: jj_la1[0] = jj_gen; break label_1; } } break; case CAT: jj_consume_token(CAT); label_2: while (true) { t1 = GetPath(); processCat(t1.image); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case CAT: case CD: case COPY: case COPYFROMLOCAL: case COPYTOLOCAL: case DUMP: case DESCRIBE: case ALIASES: case EXPLAIN: case HELP: case KILL: case LS: case MOVE: case MKDIR: case PWD: case QUIT: case REGISTER: case REMOVE: case SET: case RUN: case EXEC: case SCRIPT_DONE: case IDENTIFIER: case PATH: ; break; default: jj_la1[1] = jj_gen; break label_2; } } break; case CD: jj_consume_token(CD); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case CAT: case CD: case COPY: case COPYFROMLOCAL: case COPYTOLOCAL: case DUMP: case DESCRIBE: case ALIASES: case EXPLAIN: case HELP: case KILL: case LS: case MOVE: case MKDIR: case PWD: case QUIT: case REGISTER: case REMOVE: case SET: case RUN: case EXEC: case SCRIPT_DONE: case IDENTIFIER: case PATH: t1 = GetPath(); processCD(t1.image); break; default: jj_la1[2] = jj_gen; processCD(null); } break; case COPY: jj_consume_token(COPY); t1 = GetPath(); t2 = GetPath(); processCopy(t1.image, t2.image); break; case COPYFROMLOCAL: jj_consume_token(COPYFROMLOCAL); t1 = GetPath(); t2 = GetPath(); processCopyFromLocal(t1.image, t2.image); break; case COPYTOLOCAL: jj_consume_token(COPYTOLOCAL); t1 = GetPath(); t2 = GetPath(); processCopyToLocal(t1.image, t2.image); break; case DUMP: jj_consume_token(DUMP); t1 = jj_consume_token(IDENTIFIER); processDump(t1.image); break; case ILLUSTRATE: jj_consume_token(ILLUSTRATE); t1 = jj_consume_token(IDENTIFIER); processIllustrate(t1.image); break; case DESCRIBE: jj_consume_token(DESCRIBE); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENTIFIER: t1 = jj_consume_token(IDENTIFIER); processDescribe(t1.image); break; default: jj_la1[3] = jj_gen; processDescribe(null); } break; case ALIASES: jj_consume_token(ALIASES); printAliases(); break; case EXPLAIN: Explain(); break; case HELP: jj_consume_token(HELP); printHelp(); break; case KILL: jj_consume_token(KILL); t1 = jj_consume_token(IDENTIFIER); processKill(t1.image); break; case LS: jj_consume_token(LS); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case CAT: case CD: case COPY: case COPYFROMLOCAL: case COPYTOLOCAL: case DUMP: case DESCRIBE: case ALIASES: case EXPLAIN: case HELP: case KILL: case LS: case MOVE: case MKDIR: case PWD: case QUIT: case REGISTER: case REMOVE: case SET: case RUN: case EXEC: case SCRIPT_DONE: case IDENTIFIER: case PATH: t1 = GetPath(); processLS(t1.image); break; default: jj_la1[4] = jj_gen; processLS(null); } break; case MOVE: jj_consume_token(MOVE); t1 = GetPath(); t2 = GetPath(); processMove(t1.image, t2.image); break; case MKDIR: jj_consume_token(MKDIR); t1 = GetPath(); processMkdir(t1.image); break; case PIG: t1 = jj_consume_token(PIG); processPig(t1.image); break; case PWD: jj_consume_token(PWD); processPWD(); break; case QUIT: jj_consume_token(QUIT); quit(); break; case REGISTER: jj_consume_token(REGISTER); t1 = GetPath(); processRegister(unquote(t1.image)); break; case RUN: case EXEC: Script(); break; case REMOVE: jj_consume_token(REMOVE); label_3: while (true) { t1 = GetPath(); processRemove(t1.image, null); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case CAT: case CD: case COPY: case COPYFROMLOCAL: case COPYTOLOCAL: case DUMP: case DESCRIBE: case ALIASES: case EXPLAIN: case HELP: case KILL: case LS: case MOVE: case MKDIR: case PWD: case QUIT: case REGISTER: case REMOVE: case SET: case RUN: case EXEC: case SCRIPT_DONE: case IDENTIFIER: case PATH: ; break; default: jj_la1[5] = jj_gen; break label_3; } } break; case REMOVEFORCE: jj_consume_token(REMOVEFORCE); label_4: while (true) { t1 = GetPath(); processRemove(t1.image, "force"); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case CAT: case CD: case COPY: case COPYFROMLOCAL: case COPYTOLOCAL: case DUMP: case DESCRIBE: case ALIASES: case EXPLAIN: case HELP: case KILL: case LS: case MOVE: case MKDIR: case PWD: case QUIT: case REGISTER: case REMOVE: case SET: case RUN: case EXEC: case SCRIPT_DONE: case IDENTIFIER: case PATH: ; break; default: jj_la1[6] = jj_gen; break label_4; } } break; case SCRIPT_DONE: jj_consume_token(SCRIPT_DONE); quit(); break; case SET: jj_consume_token(SET); t1 = GetKey(); t2 = GetValue(); processSet(t1.image, unquote(t2.image)); break; case 0: jj_consume_token(0); quit(); break; case SEMICOLON: jj_consume_token(SEMICOLON); break; default: jj_la1[7] = jj_gen; handle_invalid_command(EOL); prompt(); } } final public void Explain() throws ParseException, IOException { Token t; String alias = null; String script = null; String format="text"; String target=null; boolean isVerbose = true; ArrayList<String> params; ArrayList<String> files; jj_consume_token(EXPLAIN); params = new ArrayList<String>(); files = new ArrayList<String>(); label_5: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PARAM: case PARAM_FILE: case SCRIPT: case DOT: case OUT: case BRIEF: ; break; default: jj_la1[8] = jj_gen; break label_5; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case BRIEF: jj_consume_token(BRIEF); isVerbose = false; break; case DOT: jj_consume_token(DOT); format = "dot"; break; case OUT: jj_consume_token(OUT); t = GetPath(); target = t.image; break; case SCRIPT: jj_consume_token(SCRIPT); t = GetPath(); script = t.image; break; case PARAM: jj_consume_token(PARAM); t = GetPath(); params.add(t.image); break; case PARAM_FILE: jj_consume_token(PARAM_FILE); t = GetPath(); files.add(t.image); break; default: jj_la1[9] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENTIFIER: t = jj_consume_token(IDENTIFIER); alias = t.image; break; default: jj_la1[10] = jj_gen; ; } processExplain(alias, script, isVerbose, format, target, params, files); } final public void Script() throws ParseException, IOException { Token t; String script = null; boolean batch = false; ArrayList<String> params; ArrayList<String> files; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case RUN: jj_consume_token(RUN); batch = false; break; case EXEC: jj_consume_token(EXEC); batch = true; break; default: jj_la1[11] = jj_gen; jj_consume_token(-1); throw new ParseException(); } params = new ArrayList<String>(); files = new ArrayList<String>(); label_6: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PARAM: case PARAM_FILE: ; break; default: jj_la1[12] = jj_gen; break label_6; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PARAM: jj_consume_token(PARAM); t = GetPath(); params.add(t.image); break; case PARAM_FILE: jj_consume_token(PARAM_FILE); t = GetPath(); files.add(t.image); break; default: jj_la1[13] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case CAT: case CD: case COPY: case COPYFROMLOCAL: case COPYTOLOCAL: case DUMP: case DESCRIBE: case ALIASES: case EXPLAIN: case HELP: case KILL: case LS: case MOVE: case MKDIR: case PWD: case QUIT: case REGISTER: case REMOVE: case SET: case RUN: case EXEC: case SCRIPT_DONE: case IDENTIFIER: case PATH: t = GetPath(); script = t.image; break; default: jj_la1[14] = jj_gen; ; } processScript(script, batch, params, files); } final public Token GetPath() throws ParseException { Token t; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENTIFIER: t = jj_consume_token(IDENTIFIER); break; case PATH: t = jj_consume_token(PATH); break; case CAT: case CD: case COPY: case COPYFROMLOCAL: case COPYTOLOCAL: case DUMP: case DESCRIBE: case ALIASES: case EXPLAIN: case HELP: case KILL: case LS: case MOVE: case MKDIR: case PWD: case QUIT: case REGISTER: case REMOVE: case SET: case RUN: case EXEC: case SCRIPT_DONE: t = GetReserved(); break; default: jj_la1[15] = jj_gen; jj_consume_token(-1); throw new ParseException(); } {if (true) return t;} throw new Error("Missing return statement in function"); } final public Token GetKey() throws ParseException { Token t; t = GetPath(); {if (true) return t;} throw new Error("Missing return statement in function"); } final public Token GetValue() throws ParseException { Token t; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case CAT: case CD: case COPY: case COPYFROMLOCAL: case COPYTOLOCAL: case DUMP: case DESCRIBE: case ALIASES: case EXPLAIN: case HELP: case KILL: case LS: case MOVE: case MKDIR: case PWD: case QUIT: case REGISTER: case REMOVE: case SET: case RUN: case EXEC: case SCRIPT_DONE: case IDENTIFIER: case PATH: t = GetPath(); break; case QUOTEDSTRING: t = jj_consume_token(QUOTEDSTRING); break; default: jj_la1[16] = jj_gen; jj_consume_token(-1); throw new ParseException(); } {if (true) return t;} throw new Error("Missing return statement in function"); } final public Token GetReserved() throws ParseException { Token t; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case CAT: t = jj_consume_token(CAT); break; case CD: t = jj_consume_token(CD); break; case COPY: t = jj_consume_token(COPY); break; case COPYFROMLOCAL: t = jj_consume_token(COPYFROMLOCAL); break; case COPYTOLOCAL: t = jj_consume_token(COPYTOLOCAL); break; case DUMP: t = jj_consume_token(DUMP); break; case DESCRIBE: t = jj_consume_token(DESCRIBE); break; case ALIASES: t = jj_consume_token(ALIASES); break; case EXPLAIN: t = jj_consume_token(EXPLAIN); break; case HELP: t = jj_consume_token(HELP); break; case KILL: t = jj_consume_token(KILL); break; case LS: t = jj_consume_token(LS); break; case MOVE: t = jj_consume_token(MOVE); break; case MKDIR: t = jj_consume_token(MKDIR); break; case PWD: t = jj_consume_token(PWD); break; case QUIT: t = jj_consume_token(QUIT); break; case REGISTER: t = jj_consume_token(REGISTER); break; case REMOVE: t = jj_consume_token(REMOVE); break; case SET: t = jj_consume_token(SET); break; case SCRIPT_DONE: t = jj_consume_token(SCRIPT_DONE); break; case RUN: t = jj_consume_token(RUN); break; case EXEC: t = jj_consume_token(EXEC); break; default: jj_la1[17] = jj_gen; jj_consume_token(-1); throw new ParseException(); } {if (true) return t;} throw new Error("Missing return statement in function"); } void handle_invalid_command(int kind) throws ParseException { throw generateParseException(); } /** Generated Token Manager. */ public PigScriptParserTokenManager token_source; JavaCharStream jj_input_stream; /** Current token. */ public Token token; /** Next token. */ public Token jj_nt; private int jj_ntk; private int jj_gen; final private int[] jj_la1 = new int[18]; static private int[] jj_la1_0; static private int[] jj_la1_1; static private int[] jj_la1_2; static private int[] jj_la1_3; static { jj_la1_init_0(); jj_la1_init_1(); jj_la1_init_2(); jj_la1_init_3(); } private static void jj_la1_init_0() { jj_la1_0 = new int[] {0x35ffff40,0x35ffff40,0x35ffff40,0x0,0x35ffff40,0x35ffff40,0x35ffff40,0x3fffffc1,0xc0000000,0xc0000000,0x0,0x30000000,0xc0000000,0xc0000000,0x35ffff40,0x35ffff40,0x35ffff40,0x35ffff40,}; } private static void jj_la1_init_1() { jj_la1_1 = new int[] {0x10,0x10,0x10,0x0,0x10,0x10,0x10,0x10,0xf,0xf,0x0,0x0,0x0,0x0,0x10,0x10,0x10,0x10,}; } private static void jj_la1_init_2() { jj_la1_2 = new int[] {0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xb0000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,}; } private static void jj_la1_init_3() { jj_la1_3 = new int[] {0x180,0x180,0x180,0x80,0x180,0x180,0x180,0x0,0x0,0x0,0x80,0x0,0x0,0x0,0x180,0x180,0x380,0x0,}; } /** Constructor with InputStream. */ public PigScriptParser(java.io.InputStream stream) { this(stream, null); } /** Constructor with InputStream and supplied encoding */ public PigScriptParser(java.io.InputStream stream, String encoding) { try { jj_input_stream = new JavaCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } token_source = new PigScriptParserTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 18; i++) jj_la1[i] = -1; } /** Reinitialise. */ public void ReInit(java.io.InputStream stream) { ReInit(stream, null); } /** Reinitialise. */ public void ReInit(java.io.InputStream stream, String encoding) { try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 18; i++) jj_la1[i] = -1; } /** Constructor. */ public PigScriptParser(java.io.Reader stream) { jj_input_stream = new JavaCharStream(stream, 1, 1); token_source = new PigScriptParserTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 18; i++) jj_la1[i] = -1; } /** Reinitialise. */ public void ReInit(java.io.Reader stream) { jj_input_stream.ReInit(stream, 1, 1); token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 18; i++) jj_la1[i] = -1; } /** Constructor with generated Token Manager. */ public PigScriptParser(PigScriptParserTokenManager tm) { token_source = tm; token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 18; i++) jj_la1[i] = -1; } /** Reinitialise. */ public void ReInit(PigScriptParserTokenManager tm) { token_source = tm; token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 18; i++) jj_la1[i] = -1; } private Token jj_consume_token(int kind) throws ParseException { Token oldToken; if ((oldToken = token).next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; if (token.kind == kind) { jj_gen++; return token; } token = oldToken; jj_kind = kind; throw generateParseException(); } /** Get the next Token. */ final public Token getNextToken() { if (token.next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; jj_gen++; return token; } /** Get the specific Token. */ final public Token getToken(int index) { Token t = token; for (int i = 0; i < index; i++) { if (t.next != null) t = t.next; else t = t.next = token_source.getNextToken(); } return t; } private int jj_ntk() { if ((jj_nt=token.next) == null) return (jj_ntk = (token.next=token_source.getNextToken()).kind); else return (jj_ntk = jj_nt.kind); } private java.util.List jj_expentries = new java.util.ArrayList(); private int[] jj_expentry; private int jj_kind = -1; /** Generate ParseException. */ public ParseException generateParseException() { jj_expentries.clear(); boolean[] la1tokens = new boolean[106]; if (jj_kind >= 0) { la1tokens[jj_kind] = true; jj_kind = -1; } for (int i = 0; i < 18; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { if ((jj_la1_0[i] & (1<<j)) != 0) { la1tokens[j] = true; } if ((jj_la1_1[i] & (1<<j)) != 0) { la1tokens[32+j] = true; } if ((jj_la1_2[i] & (1<<j)) != 0) { la1tokens[64+j] = true; } if ((jj_la1_3[i] & (1<<j)) != 0) { la1tokens[96+j] = true; } } } } for (int i = 0; i < 106; i++) { if (la1tokens[i]) { jj_expentry = new int[1]; jj_expentry[0] = i; jj_expentries.add(jj_expentry); } } int[][] exptokseq = new int[jj_expentries.size()][]; for (int i = 0; i < jj_expentries.size(); i++) { exptokseq[i] = (int[])jj_expentries.get(i); } return new ParseException(token, exptokseq, tokenImage); } /** Enable tracing. */ final public void enable_tracing() { } /** Disable tracing. */ final public void disable_tracing() { } }
hirohanin/pig7hadoop21
src-gen/org/apache/pig/tools/pigscript/parser/PigScriptParser.java
Java
apache-2.0
24,545
/** * Copyright (C) 2014 android10.org. All rights reserved. * @author Fernando Cejas (the android10 coder) */ package com.fernandocejas.android10.sample.presentation.view; import com.fernandocejas.android10.sample.presentation.db.Room; import java.util.Collection; public interface RoomListView extends LoadDataView { void renderRoomList(Collection<Room> roomListModelCollection); void viewRoom(Room roomListModel); }
didouard/beelee
presentation/src/main/java/com/fernandocejas/android10/sample/presentation/view/RoomListView.java
Java
apache-2.0
429
package cn.org.eshow.webapp.action; import cn.org.eshow.bean.query.PhotoCommentQuery; import cn.org.eshow.common.CommonVar; import cn.org.eshow.common.page.Page; import cn.org.eshow.model.Photo; import cn.org.eshow.model.PhotoComment; import cn.org.eshow.service.PhotoCommentManager; import cn.org.eshow.service.PhotoManager; import cn.org.eshow.util.CommonUtil; import cn.org.eshow.util.PageUtil; import org.apache.struts2.convention.annotation.AllowedMethods; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.Results; import org.springframework.beans.factory.annotation.Autowired; import java.util.Date; import java.util.List; /** * 照片评论Action */ @Results({ @Result(name = "input", location = "add"), @Result(name = "list", type = "redirect", location = ""), @Result(name = "success", type = "redirect", location = "view/${id}"), @Result(name = "redirect", type = "redirect", location = "${redirect}") }) @AllowedMethods({"list", "search", "delete", "view", "update", "save"}) public class PhotoCommentAction extends BaseAction { private static final long serialVersionUID = 1L; @Autowired private PhotoCommentManager photoCommentManager; @Autowired private PhotoManager photoManager; private List<PhotoComment> photoComments; private PhotoComment photoComment; private PhotoCommentQuery query; private Integer photoId; /** * * @return */ public String list() { photoComments = photoCommentManager.list(query); return LIST; } /** * * @return */ public String search() { Page<PhotoComment> page = photoCommentManager.search(query); photoComments = page.getDataList(); saveRequest("page", PageUtil.conversion(page)); return LIST; } /** * * @return */ public String delete() { PhotoComment old = photoCommentManager.get(id); if (old != null) { if (old.getPhoto().getUser().equals(getSessionUser()) || old.getUser().equals(getSessionUser())) { Photo photo = old.getPhoto(); photo.setCommentSize(photo.getCommentSize() - CommonVar.STEP); photoManager.save(photo); photoCommentManager.remove(id); saveMessage("删除成功"); } else { saveMessage("无权删除"); } } return LIST; } /** * * @return */ public String view() { if (id != null) { photoComment = photoCommentManager.get(id); } else { photoComment = new PhotoComment(); } return NONE; } /** * * @return * @throws Exception */ public String update() throws Exception { PhotoComment old = photoCommentManager.get(id); old.setContent(photoComment.getContent()); photoCommentManager.save(old); saveMessage("修改成功"); return SUCCESS; } /** * * @return * @throws Exception */ public String save() throws Exception { photoComment.setAddTime(new Date()); photoComment.setUser(getSessionUser()); Photo photo = photoManager.get(photoId); photo.setCommentSize(CommonUtil.count(photo.getCommentSize())); photoComment.setPhoto(photo); photoCommentManager.save(photoComment); saveMessage("添加成功"); id = photoId; return SUCCESS; } public List<PhotoComment> getPhotoComments() { return photoComments; } public void setPhotoComments(List<PhotoComment> photoComments) { this.photoComments = photoComments; } public PhotoComment getPhotoComment() { return photoComment; } public void setPhotoComment(PhotoComment photoComment) { this.photoComment = photoComment; } public PhotoCommentQuery getQuery() { return query; } public void setQuery(PhotoCommentQuery query) { this.query = query; } public Integer getPhotoId() { return photoId; } public void setPhotoId(Integer photoId) { this.photoId = photoId; } }
bangqu/EShow
eshow-www/src/main/java/cn/org/eshow/webapp/action/PhotoCommentAction.java
Java
apache-2.0
3,768
// 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. /** * CreateVolumePermissionOperationType.java * * This file was auto-generated from WSDL * by the Apache Axis2 version: 1.5.6 Built on : Aug 30, 2011 (10:01:01 CEST) */ package com.amazon.ec2; /** * CreateVolumePermissionOperationType bean class */ public class CreateVolumePermissionOperationType implements org.apache.axis2.databinding.ADBBean{ /* This type was generated from the piece of schema that had name = CreateVolumePermissionOperationType Namespace URI = http://ec2.amazonaws.com/doc/2012-08-15/ Namespace Prefix = ns1 */ private static java.lang.String generatePrefix(java.lang.String namespace) { if(namespace.equals("http://ec2.amazonaws.com/doc/2012-08-15/")){ return "ns1"; } return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } /** Whenever a new property is set ensure all others are unset * There can be only one choice and the last one wins */ private void clearAllSettingTrackers() { localAddTracker = false; localRemoveTracker = false; } /** * field for Add */ protected com.amazon.ec2.CreateVolumePermissionListType localAdd ; /* This tracker boolean wil be used to detect whether the user called the set method * for this attribute. It will be used to determine whether to include this field * in the serialized XML */ protected boolean localAddTracker = false ; /** * Auto generated getter method * @return com.amazon.ec2.CreateVolumePermissionListType */ public com.amazon.ec2.CreateVolumePermissionListType getAdd(){ return localAdd; } /** * Auto generated setter method * @param param Add */ public void setAdd(com.amazon.ec2.CreateVolumePermissionListType param){ clearAllSettingTrackers(); if (param != null){ //update the setting tracker localAddTracker = true; } else { localAddTracker = false; } this.localAdd=param; } /** * field for Remove */ protected com.amazon.ec2.CreateVolumePermissionListType localRemove ; /* This tracker boolean wil be used to detect whether the user called the set method * for this attribute. It will be used to determine whether to include this field * in the serialized XML */ protected boolean localRemoveTracker = false ; /** * Auto generated getter method * @return com.amazon.ec2.CreateVolumePermissionListType */ public com.amazon.ec2.CreateVolumePermissionListType getRemove(){ return localRemove; } /** * Auto generated setter method * @param param Remove */ public void setRemove(com.amazon.ec2.CreateVolumePermissionListType param){ clearAllSettingTrackers(); if (param != null){ //update the setting tracker localRemoveTracker = true; } else { localRemoveTracker = false; } this.localRemove=param; } /** * isReaderMTOMAware * @return true if the reader supports MTOM */ public static boolean isReaderMTOMAware(javax.xml.stream.XMLStreamReader reader) { boolean isReaderMTOMAware = false; try{ isReaderMTOMAware = java.lang.Boolean.TRUE.equals(reader.getProperty(org.apache.axiom.om.OMConstants.IS_DATA_HANDLERS_AWARE)); }catch(java.lang.IllegalArgumentException e){ isReaderMTOMAware = false; } return isReaderMTOMAware; } /** * * @param parentQName * @param factory * @return org.apache.axiom.om.OMElement */ public org.apache.axiom.om.OMElement getOMElement ( final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{ org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this,parentQName){ public void serialize(org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { CreateVolumePermissionOperationType.this.serialize(parentQName,factory,xmlWriter); } }; return new org.apache.axiom.om.impl.llom.OMSourcedElementImpl( parentQName,factory,dataSource); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ serialize(parentQName,factory,xmlWriter,false); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter, boolean serializeType) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ java.lang.String prefix = null; java.lang.String namespace = null; prefix = parentQName.getPrefix(); namespace = parentQName.getNamespaceURI(); if ((namespace != null) && (namespace.trim().length() > 0)) { java.lang.String writerPrefix = xmlWriter.getPrefix(namespace); if (writerPrefix != null) { xmlWriter.writeStartElement(namespace, parentQName.getLocalPart()); } else { if (prefix == null) { prefix = generatePrefix(namespace); } xmlWriter.writeStartElement(prefix, parentQName.getLocalPart(), namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } } else { xmlWriter.writeStartElement(parentQName.getLocalPart()); } if (serializeType){ java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://ec2.amazonaws.com/doc/2012-08-15/"); if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){ writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", namespacePrefix+":CreateVolumePermissionOperationType", xmlWriter); } else { writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", "CreateVolumePermissionOperationType", xmlWriter); } } if (localAddTracker){ if (localAdd==null){ throw new org.apache.axis2.databinding.ADBException("add cannot be null!!"); } localAdd.serialize(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/","add"), factory,xmlWriter); } if (localRemoveTracker){ if (localRemove==null){ throw new org.apache.axis2.databinding.ADBException("remove cannot be null!!"); } localRemove.serialize(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/","remove"), factory,xmlWriter); } xmlWriter.writeEndElement(); } /** * Util method to write an attribute with the ns prefix */ private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } xmlWriter.writeAttribute(namespace,attName,attValue); } /** * Util method to write an attribute without the ns prefix */ private void writeAttribute(java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (namespace.equals("")) { xmlWriter.writeAttribute(attName,attValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace,attName,attValue); } } /** * Util method to write an attribute without the ns prefix */ private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName, javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } } /** * method to handle Qnames */ private void writeQName(javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String namespaceURI = qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix = xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { // i.e this is the default namespace xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } private void writeQNames(javax.xml.namespace.QName[] qnames, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (qnames != null) { // we have to store this data until last moment since it is not possible to write any // namespace data after writing the charactor data java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer(); java.lang.String namespaceURI = null; java.lang.String prefix = null; for (int i = 0; i < qnames.length; i++) { if (i > 0) { stringToWrite.append(" "); } namespaceURI = qnames[i].getNamespaceURI(); if (namespaceURI != null) { prefix = xmlWriter.getPrefix(namespaceURI); if ((prefix == null) || (prefix.length() == 0)) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } xmlWriter.writeCharacters(stringToWrite.toString()); } } /** * Register a namespace prefix */ private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) { prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } return prefix; } /** * databinding method to get an XML representation of this object * */ public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException{ java.util.ArrayList elementList = new java.util.ArrayList(); java.util.ArrayList attribList = new java.util.ArrayList(); if (localAddTracker){ elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/", "add")); if (localAdd==null){ throw new org.apache.axis2.databinding.ADBException("add cannot be null!!"); } elementList.add(localAdd); } if (localRemoveTracker){ elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/", "remove")); if (localRemove==null){ throw new org.apache.axis2.databinding.ADBException("remove cannot be null!!"); } elementList.add(localRemove); } return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray()); } /** * Factory class that keeps the parse method */ public static class Factory{ /** * static method to create the object * Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable * If this object is not an element, it is a complex type and the reader is at the event just after the outer start element * Postcondition: If this object is an element, the reader is positioned at its end element * If this object is a complex type, the reader is positioned at the end element of its outer element */ public static CreateVolumePermissionOperationType parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{ CreateVolumePermissionOperationType object = new CreateVolumePermissionOperationType(); int event; java.lang.String nillableValue = null; java.lang.String prefix =""; java.lang.String namespaceuri =""; try { while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){ java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type"); if (fullTypeName!=null){ java.lang.String nsPrefix = null; if (fullTypeName.indexOf(":") > -1){ nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":")); } nsPrefix = nsPrefix==null?"":nsPrefix; java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1); if (!"CreateVolumePermissionOperationType".equals(type)){ //find namespace for the prefix java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix); return (CreateVolumePermissionOperationType)com.amazon.ec2.ExtensionMapper.getTypeObject( nsUri,type,reader); } } } // Note all attributes that were handled. Used to differ normal attributes // from anyAttributes. java.util.Vector handledAttributes = new java.util.Vector(); reader.next(); while(!reader.isEndElement()) { if (reader.isStartElement() ){ if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/","add").equals(reader.getName())){ object.setAdd(com.amazon.ec2.CreateVolumePermissionListType.Factory.parse(reader)); reader.next(); } // End of if for expected property start element else if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2012-08-15/","remove").equals(reader.getName())){ object.setRemove(com.amazon.ec2.CreateVolumePermissionListType.Factory.parse(reader)); reader.next(); } // End of if for expected property start element } else { reader.next(); } } // end of while loop } catch (javax.xml.stream.XMLStreamException e) { throw new java.lang.Exception(e); } return object; } }//end of factory class }
mufaddalq/cloudstack-datera-driver
awsapi/src/com/amazon/ec2/CreateVolumePermissionOperationType.java
Java
apache-2.0
25,068
package com.core.dao; import java.util.List; import java.util.Map; import com.core.entity.Store; /** * @author 1034683568@qq.com * project_name ssm-demo * @date 2015-8-17 * @time 下午2:32:02 */ public interface StoreDao { /** * 返回相应的数据集合 * * @param map * @return */ public List<Store> findStores(Map<String, Object> map); /** * 数据数目 * * @param map * @return */ public Long getTotalStores(Map<String, Object> map); /** * 添加书架 * * @param store * @return */ public int insertStore(Store store); /** * 修改书架信息 * * @param store * @return */ public int updStore(Store store); /** * 删除 这个功能暂时可能不会用到 * * @param id * @return */ public int delStore(String id); /** * 根据id查找 * * @param id * @return */ public Store getStoreById(String id); /** * 找到最优的书架并返回 * * @return */ public Store getOptimalStore(); }
ZHENFENG13/ssm-demo
ssm-demo/src/com/core/dao/StoreDao.java
Java
apache-2.0
1,217
package example.webcrawler; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; /** * Basic web crawler to show case how it works in one domain * * @author Admin * */ public class SimpleWebcrawler { private static int MAX_DEPTH = 2; private List<String> links; private static String DOMAIN; private static boolean searchOtherDomain; public SimpleWebcrawler() { links = new ArrayList<String>(); } /** * This accepts URL and depth to start the crawling in given domain. * * @param URL * <code>String</code> to crawl * @param depth<code>String</code> * depth size for crawling */ public void getPageLinks(String URL, int depth) { if ((!links.contains(URL) && (depth <= MAX_DEPTH) && searchToGivenDomain(URL))) { try { Extracter.printWeb(URL); links.add(URL); Document document = Jsoup.connect(URL).get(); Elements linksOnPage = document.select("a[href]"); depth++; for (Element page : linksOnPage) { getPageLinks(page.attr("abs:href"), depth); } } catch (IOException e) { System.err.println("For '" + URL + "': " + e.getMessage()); } } } private boolean searchToGivenDomain(String URL) { if (searchOtherDomain) { if (URL.startsWith(DOMAIN)) { return true; } else { return false; } } else { return true; } } public static void main(String[] args) { isTrue(args.length == 3, "usage: supply url to fetch"); DOMAIN = args[0]; MAX_DEPTH = Integer.parseInt(args[1]); searchOtherDomain = Boolean.parseBoolean(args[2]); new SimpleWebcrawler().getPageLinks(DOMAIN, 1); } /** * Validates that the value is true * * @param val * <code>boolean</code> object to test * @param msg * <code>Stirng</code> message to output if validation fails */ public static void isTrue(boolean val, String msg) { if (!val) throw new IllegalArgumentException(msg); } }
krishnabitmca/simple-web-crawler
src/main/java/example/webcrawler/SimpleWebcrawler.java
Java
apache-2.0
2,179
package com.blinkfox.learn.mark; import com.github.rjeschke.txtmark.Processor; import java.io.File; import java.io.IOException; import org.pmw.tinylog.Logger; /** * TxtmarkTest. * Created by blinkfox on 2017/5/14. */ public class TxtmarkTest { /** * main方法. * @param args 数组参数. */ public static void main(String[] args) { String result = Processor.process("This is **TXTMARK**"); Logger.info("result:{}", result); try { String fileName = "/Users/blinkfox/Documents/dev/gitrepo/" + "probe/src/main/webapp/doc/interview/Maven相关考题.md"; String html = Processor.process(new File(fileName)); Logger.info("result html:{}", html); } catch (IOException e) { Logger.error(e, "生成html出错!"); } } }
blinkfox/probe
src/main/java/com/blinkfox/learn/mark/TxtmarkTest.java
Java
apache-2.0
855
package com.dm.wallpaper.board.helpers; import android.content.Context; import android.content.res.Configuration; import android.os.Build; import android.support.annotation.Nullable; import android.support.design.widget.CoordinatorLayout; import android.view.View; import com.danimahardhika.android.helpers.core.ContextHelper; import com.dm.wallpaper.board.R; import static com.danimahardhika.android.helpers.core.ViewHelper.getToolbarHeight; import static com.danimahardhika.android.helpers.core.WindowHelper.getStatusBarHeight; import static com.danimahardhika.android.helpers.core.WindowHelper.getNavigationBarHeight; /* * Wallpaper Board * * Copyright (c) 2017 Dani Mahardhika * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class ViewHelper { public static void resetViewBottomPadding(@Nullable View view, boolean scroll) { if (view == null) return; Context context = ContextHelper.getBaseContext(view); int orientation = context.getResources().getConfiguration().orientation; int left = view.getPaddingLeft(); int right = view.getPaddingRight(); int bottom = view.getPaddingTop(); int top = view.getPaddingTop(); int navBar = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { boolean tabletMode = context.getResources().getBoolean(R.bool.android_helpers_tablet_mode); if (tabletMode || orientation == Configuration.ORIENTATION_PORTRAIT) { navBar = getNavigationBarHeight(context); } if (!scroll) { navBar += getStatusBarHeight(context); } } if (!scroll) { navBar += getToolbarHeight(context); } view.setPadding(left, top, right, (bottom + navBar)); } public static void resetViewBottomMargin(@Nullable View view) { if (view == null) return; Context context = ContextHelper.getBaseContext(view); int orientation = context.getResources().getConfiguration().orientation; if (!(view.getLayoutParams() instanceof CoordinatorLayout.LayoutParams)) return; CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) view.getLayoutParams(); int left = params.leftMargin; int right = params.rightMargin; int bottom = params.bottomMargin; int top = params.topMargin; int bottomNavBar = 0; int rightNavBar = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { boolean tabletMode = context.getResources().getBoolean(R.bool.android_helpers_tablet_mode); if (tabletMode || orientation == Configuration.ORIENTATION_PORTRAIT) { bottomNavBar = getNavigationBarHeight(context); } else { rightNavBar = getNavigationBarHeight(context); } } int navBar = getNavigationBarHeight(context); if ((bottom > bottomNavBar) && ((bottom - navBar) > 0)) bottom -= navBar; if ((right > rightNavBar) && ((right - navBar) > 0)) right -= navBar; params.setMargins(left, top, (right + rightNavBar), (bottom + bottomNavBar)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { params.setMarginEnd((right + rightNavBar)); } view.setLayoutParams(params); } }
SikanderKamran/wallpaperboard
library/src/main/java/com/dm/wallpaper/board/helpers/ViewHelper.java
Java
apache-2.0
4,039
/* * Copyright (C) Alexandre Harvey-Tremblay - All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * Written by Alexandre Harvey-Tremblay <ahtremblay@gmail.com>, 2014 */ package com.salesfront.commons.server.implementation; import com.salesfront.commons.server.implementations.XmlValidatorJ; import com.salesfront.commons.server.implementations.XsdSchemaProviderJ; import com.salesfront.commons.shared.Validator; import com.salesfront.commons.shared.exception.request.parameter.SfIllegalParameterException; import com.salesfront.commons.shared.exception.request.parameter.SfNullParameterException; import com.salesfront.commons.shared.exception.request.parameter.SfXmlParsingException; import com.salesfront.commons.shared.reference.Parameter; import com.salesfront.gwtmoney.shared.Currency; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertTrue; /** * Created by ahtremblay on 2015-10-17. */ public class TestValidator { @Test public void test_long(){ Validator validator = new Validator(new XmlValidatorJ(new XsdSchemaProviderJ())); validator.checkParameter(Parameter.startNumber, "1"); validator.checkParameter(Parameter.startNumber, "-1"); validator.checkParameter(Parameter.startNumber, String.valueOf(Long.MAX_VALUE)); validator.checkParameter(Parameter.startNumber, String.valueOf(Long.MIN_VALUE)); boolean r1=false; try { validator.checkParameter(Parameter.startNumber, "a"); } catch (SfIllegalParameterException e){ r1=true; } assertTrue(r1); boolean r2=false; try { validator.checkParameter(Parameter.startNumber, String.valueOf(Long.MAX_VALUE) + 1); } catch (SfIllegalParameterException e){ r2=true; } assertTrue(r2); boolean r3=false; try { validator.checkParameter(Parameter.startNumber, String.valueOf(Long.MIN_VALUE) + 1); } catch (SfIllegalParameterException e){ r3=true; } assertTrue(r3); } @Test public void test1(){ Validator validator = new Validator(new XmlValidatorJ(new XsdSchemaProviderJ())); for(Parameter parameter : Parameter.values()){ List<String> valid = new ArrayList<>(); List<String> invalid = new ArrayList<>(); switch (parameter){ case requestUri: valid.add("domains/emails/sendEmail"); invalid.add("4%s"); break; case timestamp: valid.add("1"); invalid.add("a"); break; case expires: valid.add("5000"); invalid.add("a"); break; case messageSrn: valid.add("srn:sf:mailbox:111111111111111111111111111111:domain:example.com:emailLocalPart:info:message:111111111111111111111111111111"); break; case mailboxSrn: valid.add("srn:sf:mailbox:111111111111111111111111111111:domain:example.com:emailLocalPart:info"); break; case domainSrn: valid.add("srn:sf:domain:111111111111111111111111111111:example.com"); invalid.add("srn:sf:domain:111111111111111111111111111111:EXAMPLE.COM"); break; case requestSrn: valid.add("srn:sf:request:111111111111111111111111111111"); break; case userSrn: valid.add("srn:sf:iam:111111111111111111111111111111:users:111111111111111111111111111111"); break; case rootSrn: valid.add("srn:sf:iam:111111111111111111111111111111:root"); break; case groupSrn: valid.add("srn:sf:iam:111111111111111111111111111111:groups:111111111111111111111111111111"); break; case tokenSrn: valid.add("srn:sf:iam:111111111111111111111111111111:users:111111111111111111111111111111:tokens:111111111111111111111111111111"); break; case credentialSrn: valid.add("srn:sf:iam:111111111111111111111111111111:credentials:info@example.com"); break; case sessionRootSrn: valid.add("srn:sf:iam:session:111111111111111111111111111111:root:111111111111111111111111111111"); break; case sessionUserSrn: valid.add("srn:sf:iam:session:111111111111111111111111111111:users:111111111111111111111111111111:111111111111111111111111111111"); break; case policyXml: valid.add("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<policy \n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xsi:schemaLocation=\"https://www.salesfront.com/schema 20150831/policy.xsd\">\n" + "\n" + " <statement>\n" + " <effect>Allow</effect>\n" + " <action>iam:*</action>\n" + " <resource>srn:sf:system:credential:ahtremblay@gmail.com</resource>\n" + " </statement>\n" + "\n" + "</policy>\n"); break; case recaptchaResponse: valid.add("123"); invalid.add(null); break; case password: valid.add("8124208"); invalid.add(")~lQTX1ZmnO;jeIBt)\"6lb;-d[m2,Y&cA.l8m1<%<@q,[:Rh-PlMg0&92%P;+bP.^:~gFRiRxkwAG~R2M>eba\"J6u%!B(mm0?c(Lt}CqXw1%1|P`p!?;*{g)\"0rAIpuVojei"); break; case oldPassword: valid.add("124"); invalid.add(")~lQTX1ZmnO;jeIBt)\"6lb;-d[m2,Y&cA.l8m1<%<@q,[:Rh-PlMg0&92%P;+bP.^:~gFRiRxkwAG~R2M>eba\"J6u%!B(mm0?c(Lt}CqXw1%1|P`p!?;*{g)\"0rAIpuVojei"); break; case newPassword: valid.add("124"); invalid.add(")~lQTX1ZmnO;jeIBt)\"6lb;-d[m2,Y&cA.l8m1<%<@q,[:Rh-PlMg0&92%P;+bP.^:~gFRiRxkwAG~R2M>eba\"J6u%!B(mm0?c(Lt}CqXw1%1|P`p!?;*{g)\"0rAIpuVojei"); break; case signature: valid.add("2io3jr"); invalid.add(")~lQTX1ZmnO;jeIBt)\"6lb;-d[m2,Y&cA.l8m1<%<@q,[:Rh-PlMg0&92%P;+bP.^:~gFRiRxkwAG~R2M>eba\"J6u%!B(mm0?c(Lt}CqXw1%1|P`p!?;*{g)\"0rAIpuVojei\")~lQTX1ZmnO;jeIBt)\"6lb;-d[m2,Y&cA.l8m1<%<@q,[:Rh-PlMg0&92%P;+bP.^:~gFRiRxkwAG~R2M>eba\"J6u%!B(mm0?c(Lt}CqXw1%1|P`p!?;*{g)\"0rAIpuVojei"); break; case emailLocalPart: valid.add("info"); invalid.add("!)@($@!$* hh++ "); break; case domain: valid.add("salesfront.com"); invalid.add(" ef + "); break; case source: valid.add("system:users:sendEmailForNewUser"); invalid.add("%"); break; case exclusiveStartKey: valid.add("124"); invalid.add(")~lQTX1ZmnO;jeIBt)\"6lb;-d[m2,Y&cA.l8m1<%<@q,[:Rh-PlMg0&92%P;+bP.^:~gFRiRxkwAG~R2M>eba\"J6u%!B(mm0?c(Lt}CqXw1%1|P`p!?;*{g)\"0rAIpuVojei\")~lQTX1ZmnO;jeIBt)\"6lb;-d[m2,Y&cA.l8m1<%<@q,[:Rh-PlMg0&92%P;+bP.^:~gFRiRxkwAG~R2M>eba\"J6u%!B(mm0?c(Lt}CqXw1%1|P`p!?;*{g)\"0rAIpuVojei"); break; case keyId: valid.add("124"); invalid.add(")~lQTX1ZmnO;jeIBt)\"6lb;-d[m2,Y&cA.l8m1<%<@q,[:Rh-PlMg0&92%P;+bP.^:~gFRiRxkwAG~R2M>eba\"J6u%!B(mm0?c(Lt}CqXw1%1|P`p!?;*{g)\"0rAIpuVojei\")~lQTX1ZmnO;jeIBt)\"6lb;-d[m2,Y&cA.l8m1<%<@q,[:Rh-PlMg0&92%P;+bP.^:~gFRiRxkwAG~R2M>eba\"J6u%!B(mm0?c(Lt}CqXw1%1|P`p!?;*{g)\"0rAIpuVojei"); break; case email: valid.add("info@example.com"); break; case secondaryEmail: valid.add("info@example.com"); break; case filename: valid.add("1"); invalid.add(")~lQTX1ZmnO;jeIBt)\"6lb;-d[m2,Y&cA.l8m1<%<@q,[:Rh-PlMg0&92%P;+bP.^:~gFRiRxkwAG~R2M>eba\"J6u%!B(mm0?c(Lt}CqXw1%1|P`p!?;*{g)\"0rAIpuVojei\")~lQTX1ZmnO;jeIBt)\"6lb;-d[m2,Y&cA.l8m1<%<@q,[:Rh-PlMg0&92%P;+bP.^:~gFRiRxkwAG~R2M>eba\"J6u%!B(mm0?c(Lt}CqXw1%1|P`p!?;*{g)\"0rAIpuVojei"); break; case fileSrn: valid.add("srn:sf:file:temporary:111111111111111111111111111111:root:111111111111111111111111111111"); break; case organizationSrn: valid.add("srn:sf:organization:111111111111111111111111111111:111111111111111111111111111111"); break; case accountSrn: valid.add("srn:sf:account:111111111111111111111111111111:111111111111111111111111111111"); break; case accountingEntrySrn: valid.add("srn:sf:account:111111111111111111111111111111:111111111111111111111111111111:accountingEntry:111111111111111111111111111111"); break; case startNumber: valid.add("1"); invalid.add("X"); break; case endNumber: valid.add("1"); invalid.add("X"); break; case mailboxFolderName: valid.add("INBOX"); valid.add("Sent"); valid.add("Sent/Today"); invalid.add("INBOX//test"); invalid.add("Sent Messages"); invalid.add("/inbox"); invalid.add("/"); invalid.add("//"); invalid.add("inbox/"); invalid.add("inbox/inboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinboxinbox"); break; case operation: valid.add("ADD"); invalid.add(""); break; case imapToken: valid.add("1"); invalid.add("1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"); break; case rangeModSeq: valid.add("1"); invalid.add("x"); break; case number: valid.add("1"); invalid.add("x"); break; case emailPartId: valid.add("TEXT"); valid.add("HTML"); valid.add("PLAIN"); valid.add("1.1"); valid.add("1"); valid.add("11"); valid.add("1.2.3"); valid.add("1."); invalid.add(".1"); invalid.add("TEXT!"); invalid.add("1..1"); invalid.add("1...1"); invalid.add("0"); invalid.add("1.a"); invalid.add("|"); invalid.add("1|"); invalid.add("14|13|13"); break; case creditCardPan: valid.add("4556563023432427"); valid.add("4916331780449330"); valid.add("4539766246722845"); valid.add("4532615392139535"); valid.add("4916121391334512"); valid.add("5233636194581095"); valid.add("5135502118270323"); valid.add("5164381026817432"); valid.add("5114283117984801"); valid.add("5453064211260432"); valid.add("6011565197318120"); valid.add("6011342696088798"); valid.add("6011998087303409"); valid.add("6011212825741882"); valid.add("6011038499099574"); valid.add("378630237945637"); valid.add("370685042332387"); valid.add("344008575155427"); valid.add("340509096211452"); valid.add("375521833758404"); invalid.add("4556563023432421"); invalid.add("4916331780449331"); invalid.add("4539766246722841"); invalid.add("4532615392139531"); invalid.add("4916121391334511"); invalid.add("5233636194581015"); invalid.add("5135502118270321"); invalid.add("5164381026817431"); invalid.add("5114283117984802"); invalid.add("5453064211260431"); invalid.add("6011565197318122"); invalid.add("6011342696088791"); invalid.add("6011998087303401"); invalid.add("6011212825741881"); invalid.add("6011038499099571"); invalid.add("378630237945631"); invalid.add("370685042332381"); invalid.add("344008575155421"); invalid.add("340509096211451"); invalid.add("375521833758401"); break; case creditCardExpMMYYYY: valid.add("102023"); invalid.add("102023a"); invalid.add("02023a"); break; case decimal: valid.add("1"); valid.add("1."); valid.add("1.1"); valid.add("0.1"); invalid.add(".1"); invalid.add("1.1."); invalid.add(""); break; case currency: for(Currency currency : Currency.values()) valid.add(currency.name()); break; case phone: valid.add("1"); valid.add("124124"); valid.add("124124;124"); invalid.add("124124;"); invalid.add(";"); invalid.add(";235235"); break; } System.out.print(parameter.name()); for(String v : valid) validator.checkParameter(parameter, v); boolean rn=false; try {validator.checkParameter(parameter, null);} catch (SfNullParameterException e){rn=true;} assertTrue(rn); for(String i : invalid) { boolean ri = false; try { validator.checkParameter(parameter, i); } catch (SfIllegalParameterException | SfXmlParsingException | SfNullParameterException e) { ri = true; } if (!ri) System.out.println("... " + i); assertTrue(ri); } System.out.println("... is valid"); } } }
salesfront/commons
src/test/java/com/salesfront/commons/server/implementation/TestValidator.java
Java
apache-2.0
16,594
package com.bangxuan.utils; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; public class HttpContextUtils { public static HttpServletRequest getHttpServletRequest() { return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); } }
liunianmiyu/51bang
51bang-common/src/main/java/com/bangxuan/utils/HttpContextUtils.java
Java
apache-2.0
413
/* * Copyright (c) 2009-2020, Peter Abeles. All Rights Reserved. * * This file is part of Efficient Java Matrix Library (EJML). * * 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.ejml.dense.row.factory; import org.ejml.EjmlParameters; import org.ejml.data.DMatrixRMaj; import org.ejml.dense.row.decomposition.chol.CholeskyDecompositionCommon_DDRM; import org.ejml.dense.row.decomposition.chol.CholeskyDecompositionInner_DDRM; import org.ejml.dense.row.decomposition.lu.LUDecompositionAlt_DDRM; import org.ejml.dense.row.decomposition.qr.QRColPivDecompositionHouseholderColumn_DDRM; import org.ejml.dense.row.linsol.AdjustableLinearSolver_DDRM; import org.ejml.dense.row.linsol.chol.LinearSolverChol_DDRB; import org.ejml.dense.row.linsol.chol.LinearSolverChol_DDRM; import org.ejml.dense.row.linsol.lu.LinearSolverLu_DDRM; import org.ejml.dense.row.linsol.qr.*; import org.ejml.dense.row.linsol.svd.SolvePseudoInverseSvd_DDRM; import org.ejml.interfaces.linsol.LinearSolverDense; /** * A factory for generating solvers for systems of the form A*x=b, where A and B are known and x is unknown. * * @author Peter Abeles */ public class LinearSolverFactory_DDRM { /** * Creates a linear solver using LU decomposition */ public static LinearSolverDense<DMatrixRMaj> lu( int numRows ) { return linear(numRows); } /** * Creates a linear solver using Cholesky decomposition */ public static LinearSolverDense<DMatrixRMaj> chol( int numRows ) { return symmPosDef(numRows); } /** * Creates a linear solver using QR decomposition */ public static LinearSolverDense<DMatrixRMaj> qr( int numRows, int numCols ) { return leastSquares(numRows, numCols); } /** * Creates a linear solver using QRP decomposition */ public static LinearSolverDense<DMatrixRMaj> qrp( boolean computeNorm2, boolean computeQ ) { return leastSquaresQrPivot(computeNorm2, computeQ); } /** * Creates a general purpose solver. Use this if you are not sure what you need. * * @param numRows The number of rows that the decomposition is optimized for. * @param numCols The number of columns that the decomposition is optimized for. */ public static LinearSolverDense<DMatrixRMaj> general( int numRows, int numCols ) { if (numRows == numCols) return linear(numRows); else return leastSquares(numRows, numCols); } /** * Creates a solver for linear systems. The A matrix will have dimensions (m,m). * * @return A new linear solver. */ public static LinearSolverDense<DMatrixRMaj> linear( int matrixSize ) { return new LinearSolverLu_DDRM(new LUDecompositionAlt_DDRM()); } /** * Creates a good general purpose solver for over determined systems and returns the optimal least-squares * solution. The A matrix will have dimensions (m,n) where m &ge; n. * * @param numRows The number of rows that the decomposition is optimized for. * @param numCols The number of columns that the decomposition is optimized for. * @return A new least-squares solver for over determined systems. */ public static LinearSolverDense<DMatrixRMaj> leastSquares( int numRows, int numCols ) { if (numCols < EjmlParameters.SWITCH_BLOCK64_QR) { return new LinearSolverQrHouseCol_DDRM(); } else { if (EjmlParameters.MEMORY == EjmlParameters.MemoryUsage.FASTER) return new LinearSolverQrBlock64_DDRM(); else return new LinearSolverQrHouseCol_DDRM(); } } /** * Creates a solver for symmetric positive definite matrices. * * @return A new solver for symmetric positive definite matrices. */ public static LinearSolverDense<DMatrixRMaj> symmPosDef( int matrixWidth ) { if (matrixWidth < EjmlParameters.SWITCH_BLOCK64_CHOLESKY) { CholeskyDecompositionCommon_DDRM decomp = new CholeskyDecompositionInner_DDRM(true); return new LinearSolverChol_DDRM(decomp); } else { if (EjmlParameters.MEMORY == EjmlParameters.MemoryUsage.FASTER) return new LinearSolverChol_DDRB(); else { CholeskyDecompositionCommon_DDRM decomp = new CholeskyDecompositionInner_DDRM(true); return new LinearSolverChol_DDRM(decomp); } } } /** * <p> * Linear solver which uses QR pivot decomposition. These solvers can handle singular systems * and should never fail. For singular systems, the solution might not be as accurate as a * pseudo inverse that uses SVD. * </p> * * <p> * For singular systems there are multiple correct solutions. The optimal 2-norm solution is the * solution vector with the minimal 2-norm and is unique. If the optimal solution is not computed * then the basic solution is returned. See {@link org.ejml.dense.row.linsol.qr.BaseLinearSolverQrp_DDRM} * for details. There is only a runtime difference for small matrices, 2-norm solution is slower. * </p> * * <p> * Two different solvers are available. Compute Q will compute the Q matrix once then use it multiple times. * If the solution for a single vector is being found then this should be set to false. If the pseudo inverse * is being found or the solution matrix has more than one columns AND solve is being called numerous multiples * times then this should be set to true. * </p> * * @param computeNorm2 true to compute the minimum 2-norm solution for singular systems. Try true. * @param computeQ Should it precompute Q or use house holder. Try false; * @return Pseudo inverse type solver using QR with column pivots. */ public static LinearSolverDense<DMatrixRMaj> leastSquaresQrPivot( boolean computeNorm2, boolean computeQ ) { QRColPivDecompositionHouseholderColumn_DDRM decomposition = new QRColPivDecompositionHouseholderColumn_DDRM(); if (computeQ) return new SolvePseudoInverseQrp_DDRM(decomposition, computeNorm2); else return new LinearSolverQrpHouseCol_DDRM(decomposition, computeNorm2); } /** * <p> * Returns a solver which uses the pseudo inverse. Useful when a matrix * needs to be inverted which is singular. Two variants of pseudo inverse are provided. SVD * will tend to be the most robust but the slowest and QR decomposition with column pivots will * be faster, but less robust. * </p> * * <p> * See {@link #leastSquaresQrPivot} for additional options specific to QR decomposition based * pseudo inverse. These options allow for better runtime performance in different situations. * </p> * * @param useSVD If true SVD will be used, otherwise QR with column pivot will be used. * @return Solver for singular matrices. */ public static LinearSolverDense<DMatrixRMaj> pseudoInverse( boolean useSVD ) { if (useSVD) return new SolvePseudoInverseSvd_DDRM(); else return leastSquaresQrPivot(true, false); } /** * Create a solver which can efficiently add and remove elements instead of recomputing * everything from scratch. */ public static AdjustableLinearSolver_DDRM adjustable() { return new AdjLinearSolverQr_DDRM(); } }
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/row/factory/LinearSolverFactory_DDRM.java
Java
apache-2.0
8,049
// Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). package com.twitter.intellij.pants.compiler.actions; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.twitter.intellij.pants.util.PantsUtil; import org.jetbrains.annotations.NotNull; import java.util.Arrays; import java.util.Collection; import java.util.stream.Stream; /** * PantsCompileAllTargetsAction is a UI action that, when in a project, compiles all targets in the project */ public class PantsCompileAllTargetsAction extends PantsCompileActionBase { public PantsCompileAllTargetsAction() { super("Compile all targets in project"); } @NotNull @Override public Stream<String> getTargets(@NotNull AnActionEvent e, @NotNull Project project) { Module[] modules = ModuleManager.getInstance(project).getModules(); return Arrays.stream(modules) .map(PantsUtil::getNonGenTargetAddresses) .flatMap(Collection::stream); } }
wisechengyi/intellij-pants-plugin
src/com/twitter/intellij/pants/compiler/actions/PantsCompileAllTargetsAction.java
Java
apache-2.0
1,154
/* * Copyright (c) 2016 Yahoo Inc. * Licensed under the terms of the Apache version 2.0 license. * See LICENSE file for terms. */ package com.yahoo.yqlplus.api.types; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; /** * All this will be replaced by TDL. */ public final class YQLSchema { private static final Map<String, YQLType> baseTypes = createBaseTypes(); private static final Map<String, YQLType> createBaseTypes() { Map<String, YQLType> base = new LinkedHashMap<>(); for (Field type : YQLBaseType.class.getFields()) { if (Modifier.isPublic(type.getModifiers()) && Modifier.isStatic(type.getModifiers()) && YQLType.class.isAssignableFrom(type.getType())) { try { YQLType value = (YQLType) type.get(null); base.put(value.getName(), value); } catch (IllegalAccessException e) { // this should never happen } } } return Collections.unmodifiableMap(base); } private final Map<String, YQLType> types = new HashMap<>(); public YQLType get(String name) { if (baseTypes.containsKey(name)) { return baseTypes.get(name); } return types.get(name); } public void declare(YQLType type) { if (get(type.getName()) != null) { throw new YQLTypeException("Cannot override already declared type '" + type.getName() + "'"); } types.put(type.getName(), type); } public <T extends YQLType> T declareIfMissing(T type) { YQLType result = get(type.getName()); if (result == null) { declare(type); return type; } else if (!result.equals(type)) { throw new YQLTypeException("Declare-if-missing has conflicting type: " + result + " != " + type); } return (T) result; } public YQLMapType map(YQLType key, YQLType value) { return declareIfMissing(YQLMapType.create(key, value)); } public YQLArrayType array(YQLType element) { return declareIfMissing(new YQLArrayType(element)); } public YQLType union(YQLType... types) { // TODO: require that a union be itself non-optional (any optional types inside the union should be pushed up) // union<int,optional<string>> -> optional<union<int,string>> // until that is done, do not permit unions to be used return YQLUnionType.create(types); } public YQLStructType.Builder struct() { return YQLStructType.builder(); } public YQLType addStruct(YQLStructType type) { return declareIfMissing(type); } }
slolars/yql-plus
yqlplus_source_api/src/main/java/com/yahoo/yqlplus/api/types/YQLSchema.java
Java
apache-2.0
2,827
package com.alibaba.idst.nls.demo; import java.io.InputStream; import com.alibaba.idst.nls.NlsClient; import com.alibaba.idst.nls.NlsFuture; import com.alibaba.idst.nls.event.NlsEvent; import com.alibaba.idst.nls.event.NlsListener; import com.alibaba.idst.nls.protocol.NlsRequest; import com.alibaba.idst.nls.protocol.NlsResponse; public class AsrDemo implements NlsListener { private static NlsClient client = new NlsClient(); private String akId; private String akSecret; public AsrDemo(String akId, String akSecret) { System.out.println("init Nls client..."); this.akId = akId; this.akSecret = akSecret; // 初始化NlsClient client.init(); } public void shutDown() { System.out.println("close NLS client"); // 关闭客户端并释放资源 client.close(); System.out.println("demo done"); } public void startAsr() { //开始发送语音 System.out.println("open audio file..."); InputStream fis = null; try { fis = this.getClass().getClassLoader().getResourceAsStream("sample.pcm"); } catch (Exception e) { e.printStackTrace(); } if (fis != null) { System.out.println("create NLS future"); try { NlsRequest req = new NlsRequest(); req.setAppKey("nls-service"); // appkey请从 "快速开始" 帮助页面的appkey列表中获取 req.setAsrFormat("pcm"); // 设置语音文件格式为pcm,我们支持16k 16bit 的无头的pcm文件。 /*热词相关配置*/ //req.setAsrVocabularyId("热词词表id");//热词词表id /*热词相关配置*/ req.authorize(akId, akSecret); // 请替换为用户申请到的Access Key ID和Access Key // Secret NlsFuture future = client.createNlsFuture(req, this); // 实例化请求,传入请求和监听器 System.out.println("call NLS service"); byte[] b = new byte[8000]; int len = 0; while ((len = fis.read(b)) > 0) { future.sendVoice(b, 0, len); // 发送语音数据 Thread.sleep(50); } future.sendFinishSignal(); // 语音识别结束时,发送结束符 System.out.println("main thread enter waiting for less than 10s."); future.await(10000); // 设置服务端结果返回的超时时间 } catch (Exception e) { e.printStackTrace(); } System.out.println("calling NLS service end"); } } @Override public void onMessageReceived(NlsEvent e) { //识别结果的回调 NlsResponse response = e.getResponse(); String result = ""; int statusCode = response.getStatus_code(); if (response.getAsr_ret() != null) { result += "\nget asr result: statusCode=[" + statusCode + "], " + response.getAsr_ret(); } if (result != null) { System.out.println(result); } else { System.out.println(response.jsonResults.toString()); } } @Override public void onOperationFailed(NlsEvent e) { //识别失败的回调 String result = ""; result += "on operation failed: statusCode=[" + e.getResponse().getStatus_code() + "], " + e.getErrorMessage(); System.out.println(result); } @Override public void onChannelClosed(NlsEvent e) { //socket 连接关闭的回调 System.out.println("on websocket closed."); } public static void main(String[] args) { String akId = args[0]; String akSecret = args[1]; AsrDemo asrDemo = new AsrDemo(akId, akSecret); asrDemo.startAsr(); asrDemo.shutDown(); } }
rickding/WallE
nls-demo/src/main/java/com/alibaba/idst/nls/demo/AsrDemo.java
Java
apache-2.0
3,392
/* * Copyright 2011 Vasily Shiyan * * 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 see.functions.collections; import see.functions.VarArgFunction; import javax.annotation.Nonnull; import java.util.List; import static com.google.common.collect.Lists.newArrayList; import static java.util.Collections.unmodifiableList; public class MakeList implements VarArgFunction<Object, List<Object>> { @Override public List<Object> apply(@Nonnull List<Object> input) { return unmodifiableList(newArrayList(input)); } @Override public String toString() { return "makeList"; } }
xicmiah/see
src/main/java/see/functions/collections/MakeList.java
Java
apache-2.0
1,131
/* * Copyright 2013 Cyber Eagle * * 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 br.com.cybereagle.androidtestlibrary.util; public class MockUtils { }
CyberEagle/AndroidTestLibrary
library/src/main/java/br/com/cybereagle/androidtestlibrary/util/MockUtils.java
Java
apache-2.0
678
package org.drools.rule.builder.dialect.java; import java.util.Arrays; import org.drools.RuntimeDroolsException; import org.drools.compiler.Dialect; import org.drools.compiler.DialectConfiguration; import org.drools.compiler.PackageBuilder; import org.drools.compiler.PackageBuilderConfiguration; import org.drools.compiler.PackageRegistry; import org.drools.rule.Package; /** * * There are options to use various flavours of runtime compilers. * Apache JCI is used as the interface to all the runtime compilers. * * You can also use the system property "drools.compiler" to set the desired compiler. * The valid values are "ECLIPSE" and "JANINO" only. * * drools.dialect.java.compiler = <ECLIPSE|JANINO> * drools.dialect.java.lngLevel = <1.5|1.6> * * The default compiler is Eclipse and the default lngLevel is 1.5. * The lngLevel will attempt to autodiscover your system using the * system property "java.version" * * The JavaDialectConfiguration will attempt to validate that the specified compiler * is in the classpath, using ClassLoader.loasClass(String). If you intented to * just Janino sa the compiler you must either overload the compiler property before * instantiating this class or the PackageBuilder, or make sure Eclipse is in the * classpath, as Eclipse is the default. * */ public class JavaDialectConfiguration implements DialectConfiguration { public static final int ECLIPSE = 0; public static final int JANINO = 1; public static final String[] LANGUAGE_LEVELS = new String[]{"1.5", "1.6"}; private String languageLevel; private PackageBuilderConfiguration conf; private int compiler; public JavaDialectConfiguration() { } public void init(final PackageBuilderConfiguration conf) { this.conf = conf; setCompiler( getDefaultCompiler() ); setJavaLanguageLevel( getDefaultLanguageLevel() ); } public PackageBuilderConfiguration getPackageBuilderConfiguration() { return this.conf; } public Dialect newDialect(PackageBuilder packageBuilder, PackageRegistry pkgRegistry, Package pkg) { return new JavaDialect(packageBuilder, pkgRegistry, pkg); } public String getJavaLanguageLevel() { return this.languageLevel; } /** * You cannot set language level below 1.5, as we need static imports, 1.5 is now the default. * @param level */ public void setJavaLanguageLevel(final String languageLevel) { if ( Arrays.binarySearch( LANGUAGE_LEVELS, languageLevel ) < 0 ) { throw new RuntimeDroolsException( "value '" + languageLevel + "' is not a valid language level" ); } this.languageLevel = languageLevel; } /** * Set the compiler to be used when building the rules semantic code blocks. * This overrides the default, and even what was set as a system property. */ public void setCompiler(final int compiler) { // check that the jar for the specified compiler are present if ( compiler == ECLIPSE ) { try { getClass().getClassLoader().loadClass( "org.eclipse.jdt.internal.compiler.Compiler" ); } catch ( ClassNotFoundException e ) { throw new RuntimeException( "The Eclipse JDT Core jar is not in the classpath" ); } } else if ( compiler == JANINO ){ try { getClass().getClassLoader().loadClass( "org.codehaus.janino.Parser" ); } catch ( ClassNotFoundException e ) { throw new RuntimeException( "The Janino jar is not in the classpath" ); } } switch ( compiler ) { case JavaDialectConfiguration.ECLIPSE : this.compiler = JavaDialectConfiguration.ECLIPSE; break; case JavaDialectConfiguration.JANINO : this.compiler = JavaDialectConfiguration.JANINO; break; default : throw new RuntimeDroolsException( "value '" + compiler + "' is not a valid compiler" ); } } public int getCompiler() { return this.compiler; } /** * This will attempt to read the System property to work out what default to set. * This should only be done once when the class is loaded. After that point, you will have * to programmatically override it. */ private int getDefaultCompiler() { try { final String prop = this.conf.getChainedProperties().getProperty( "drools.dialect.java.compiler", "ECLIPSE" ); if ( prop.equals( "ECLIPSE".intern() ) ) { return JavaDialectConfiguration.ECLIPSE; } else if ( prop.equals( "JANINO" ) ) { return JavaDialectConfiguration.JANINO; } else { System.err.println( "Drools config: unable to use the drools.compiler property. Using default. It was set to:" + prop ); return JavaDialectConfiguration.ECLIPSE; } } catch ( final SecurityException e ) { System.err.println( "Drools config: unable to read the drools.compiler property. Using default." ); return JavaDialectConfiguration.ECLIPSE; } } private String getDefaultLanguageLevel() { String level = this.conf.getChainedProperties().getProperty( "drools.dialect.java.compiler.lnglevel", null ); if ( level == null ) { String version = System.getProperty( "java.version" ); if ( version.startsWith( "1.5" ) ) { level = "1.5"; } else if ( version.startsWith( "1.6" ) ) { level = "1.6"; } else { level = "1.5"; } } if ( Arrays.binarySearch( LANGUAGE_LEVELS, level ) < 0 ) { throw new RuntimeDroolsException( "value '" + level + "' is not a valid language level" ); } return level; } }
bobmcwhirter/drools
drools-compiler/src/main/java/org/drools/rule/builder/dialect/java/JavaDialectConfiguration.java
Java
apache-2.0
6,503
/******************************************************************************* * Copyright 2017 julien@squidsolutions.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.squid.kraken.v4.model; import java.util.ArrayList; import java.util.List; import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModelProperty; /** * Bookmark */ public class Bookmark extends DynamicObject<BookmarkPK> { @SerializedName("accessRights") private List<AccessRight> accessRights = new ArrayList<AccessRight>(); @SerializedName("description") private String description = null; @SerializedName("path") private String path = null; @SerializedName("config") private BookmarkConfig config = null; @SerializedName("reference") private String reference = null; @SerializedName("objectType") private String objectType = null; @SerializedName("name") private String name = null; public Bookmark accessRights(List<AccessRight> accessRights) { this.accessRights = accessRights; return this; } public Bookmark addAccessRightsItem(AccessRight accessRightsItem) { this.accessRights.add(accessRightsItem); return this; } /** * The ACL for this object * @return accessRights **/ @ApiModelProperty(example = "null", value = "The ACL for this object") public List<AccessRight> getAccessRights() { return accessRights; } public void setAccessRights(List<AccessRight> accessRights) { this.accessRights = accessRights; } public Bookmark description(String description) { this.description = description; return this; } /** * Get description * @return description **/ @ApiModelProperty(example = "null", value = "") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Bookmark path(String path) { this.path = path; return this; } /** * Get path * @return path **/ @ApiModelProperty(example = "null", value = "") public String getPath() { return path; } public void setPath(String path) { this.path = path; } public Bookmark config(BookmarkConfig config) { this.config = config; return this; } /** * Get config * @return config **/ @ApiModelProperty(example = "null", value = "") public BookmarkConfig getConfig() { return config; } public void setConfig(BookmarkConfig config) { this.config = config; } public Bookmark reference(String reference) { this.reference = reference; return this; } /** * Get reference * @return reference **/ @ApiModelProperty(example = "null", value = "") public String getReference() { return reference; } public void setReference(String reference) { this.reference = reference; } /** * Get objectType * @return objectType **/ @ApiModelProperty(example = "null", value = "") public String getObjectType() { return objectType; } public Bookmark name(String name) { this.name = name; return this; } /** * Get name * @return name **/ @ApiModelProperty(example = "null", value = "") public String getName() { return name; } public void setName(String name) { this.name = name; } }
jtheulier/bouquet-java-sdk
src/main/java/com/squid/kraken/v4/model/Bookmark.java
Java
apache-2.0
3,795
/** * Copyright (C) 2014 SignalFuse, Inc. */ package com.github.dockerjava.core; import java.io.File; import java.io.IOException; import junit.framework.Assert; import org.apache.commons.io.FilenameUtils; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class GoLangFileMatchTest { @Test(dataProvider = "getTestData") public void testMatch(MatchTestCase testCase) throws IOException { String pattern = testCase.pattern; String s = testCase.s; if (GoLangFileMatch.IS_WINDOWS) { if (pattern.indexOf('\\') > 0) { // no escape allowed on windows. return; } pattern = FilenameUtils.normalize(pattern); s = FilenameUtils.normalize(s); } try { boolean matched = GoLangFileMatch.match(pattern, s); if (testCase.expectException) { Assert.fail("Expected GoFileMatchException"); } Assert.assertEquals(testCase.matches, matched); } catch (GoLangFileMatchException e) { if (!testCase.expectException) { throw e; } } } @DataProvider public Object[][] getTestData() { return new Object[][] { new Object[] { new MatchTestCase("abc", "abc", true, false) }, new Object[] { new MatchTestCase("*", "abc", true, false) }, new Object[] { new MatchTestCase("*c", "abc", true, false) }, new Object[] { new MatchTestCase("a*", "a", true, false) }, new Object[] { new MatchTestCase("a*", "abc", true, false) }, new Object[] { new MatchTestCase("a*", "ab/c", false, false) }, new Object[] { new MatchTestCase("a*/b", "abc/b", true, false) }, new Object[] { new MatchTestCase("a*/b", "a/c/b", false, false) }, new Object[] { new MatchTestCase("a*b*c*d*e*/f", "axbxcxdxe/f", true, false) }, new Object[] { new MatchTestCase("a*b*c*d*e*/f", "axbxcxdxexxx/f", true, false) }, new Object[] { new MatchTestCase("a*b*c*d*e*/f", "axbxcxdxe/xxx/f", false, false) }, new Object[] { new MatchTestCase("a*b*c*d*e*/f", "axbxcxdxexxx/fff", false, false) }, new Object[] { new MatchTestCase("a*b?c*x", "abxbbxdbxebxczzx", true, false) }, new Object[] { new MatchTestCase("a*b?c*x", "abxbbxdbxebxczzy", false, false) }, new Object[] { new MatchTestCase("ab[c]", "abc", true, false) }, new Object[] { new MatchTestCase("ab[b-d]", "abc", true, false) }, new Object[] { new MatchTestCase("ab[e-g]", "abc", false, false) }, new Object[] { new MatchTestCase("ab[^c]", "abc", false, false) }, new Object[] { new MatchTestCase("ab[^b-d]", "abc", false, false) }, new Object[] { new MatchTestCase("ab[^e-g]", "abc", true, false) }, new Object[] { new MatchTestCase("a\\*b", "a*b", true, false) }, new Object[] { new MatchTestCase("a\\*b", "ab", false, false) }, new Object[] { new MatchTestCase("a?b", "a☺b", true, false) }, new Object[] { new MatchTestCase("a[^a]b", "a☺b", true, false) }, new Object[] { new MatchTestCase("a???b", "a☺b", false, false) }, new Object[] { new MatchTestCase("a[^a][^a][^a]b", "a☺b", false, false) }, new Object[] { new MatchTestCase("[a-ζ]*", "α", true, false) }, new Object[] { new MatchTestCase("*[a-ζ]", "A", false, false) }, new Object[] { new MatchTestCase("a?b", "a/b", false, false) }, new Object[] { new MatchTestCase("a*b", "a/b", false, false) }, new Object[] { new MatchTestCase("[\\]a]", "]", true, false) }, new Object[] { new MatchTestCase("[\\-]", "-", true, false) }, new Object[] { new MatchTestCase("[x\\-]", "x", true, false) }, new Object[] { new MatchTestCase("[x\\-]", "-", true, false) }, new Object[] { new MatchTestCase("[x\\-]", "z", false, false) }, new Object[] { new MatchTestCase("[\\-x]", "x", true, false) }, new Object[] { new MatchTestCase("[\\-x]", "-", true, false) }, new Object[] { new MatchTestCase("[\\-x]", "a", false, false) }, new Object[] { new MatchTestCase("[]a]", "]", false, true) }, new Object[] { new MatchTestCase("[-]", "-", false, true) }, new Object[] { new MatchTestCase("[x-]", "x", false, true) }, new Object[] { new MatchTestCase("[x-]", "-", false, true) }, new Object[] { new MatchTestCase("[x-]", "z", false, true) }, new Object[] { new MatchTestCase("[-x]", "x", false, true) }, new Object[] { new MatchTestCase("[-x]", "-", false, true) }, new Object[] { new MatchTestCase("[-x]", "a", false, true) }, new Object[] { new MatchTestCase("\\", "a", false, true) }, new Object[] { new MatchTestCase("[a-b-c]", "a", false, true) }, new Object[] { new MatchTestCase("[", "a", false, true) }, new Object[] { new MatchTestCase("[^", "a", false, true) }, new Object[] { new MatchTestCase("[^bc", "a", false, true) }, new Object[] { new MatchTestCase("a[", "a", false, false) }, new Object[] { new MatchTestCase("a[", "ab", false, true) }, new Object[] { new MatchTestCase("*x", "xxx", true, false) } }; } private final class MatchTestCase { private final String pattern; private final String s; private final boolean matches; private final boolean expectException; public MatchTestCase(String pattern, String s, boolean matches, boolean expectException) { super(); this.pattern = pattern; this.s = s; this.matches = matches; this.expectException = expectException; } @Override public String toString() { return "MatchTestCase [pattern=" + pattern + ", s=" + s + ", matches=" + matches + ", expectException=" + expectException + "]"; } } }
hermeswaldemarin/docker-java
src/test/java/com/github/dockerjava/core/GoLangFileMatchTest.java
Java
apache-2.0
6,443
package org.jenkinsci.plugins.mesos; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.CheckForNull; import net.sf.json.JSONException; import net.sf.json.JSONObject; import net.sf.json.JSONSerializer; import org.apache.commons.lang.StringUtils; import org.apache.mesos.Protos.ContainerInfo.DockerInfo.Network; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import hudson.Extension; import hudson.Util; import hudson.model.AbstractDescribableImpl; import hudson.model.Descriptor; import hudson.model.Descriptor.FormException; import hudson.model.Label; import hudson.model.Node; import hudson.model.Node.Mode; import hudson.slaves.NodeProperty; import hudson.slaves.NodePropertyDescriptor; import hudson.util.DescribableList; import hudson.util.FormValidation; import jenkins.model.Jenkins; public class MesosSlaveInfo extends AbstractDescribableImpl<MesosSlaveInfo> { @Extension public static class DescriptorImpl extends Descriptor<MesosSlaveInfo> { public FormValidation doCheckMinExecutors(@QueryParameter String minExecutors, @QueryParameter String maxExecutors) { int minExecutorsVal = Integer.parseInt(minExecutors); int maxExecutorsVal = Integer.parseInt(maxExecutors); if(minExecutorsVal < 1) { return FormValidation.error("minExecutors must at least be equal to 1."); } else if(minExecutorsVal > maxExecutorsVal) { return FormValidation.error("minExecutors must be lower than maxExecutors."); } else { return FormValidation.ok(); } } public FormValidation doCheckMaxExecutors(@QueryParameter String minExecutors, @QueryParameter String maxExecutors) { int minExecutorsVal = Integer.parseInt(minExecutors); int maxExecutorsVal = Integer.parseInt(maxExecutors); if(maxExecutorsVal < 1) { return FormValidation.error("maxExecutors must at least be equal to 1."); } else if(maxExecutorsVal < minExecutorsVal) { return FormValidation.error("maxExecutors must be higher than minExecutors."); } else { return FormValidation.ok(); } } public String getDisplayName() { return ""; } public Class<? extends Node> getNodeClass() { return MesosSlave.class; } } private static final String DEFAULT_JVM_ARGS = "-Xms16m -XX:+UseConcMarkSweepGC -Djava.net.preferIPv4Stack=true"; private static final String JVM_ARGS_PATTERN = "-Xmx.+ "; private static final String CUSTOM_IMAGE_SEPARATOR = ":"; private static final Pattern CUSTOM_IMAGE_FROM_LABEL_PATTERN = Pattern.compile(CUSTOM_IMAGE_SEPARATOR + "([\\w\\.\\-/:]+[\\w])"); private final double slaveCpus; private final double diskNeeded; //MB private final int slaveMem; // MB. private final double executorCpus; private /*almost final*/ int minExecutors; private final int maxExecutors; private final int executorMem; // MB. private final String remoteFSRoot; private final int idleTerminationMinutes; private final String jvmArgs; private final String jnlpArgs; private final boolean defaultSlave; // Slave attributes JSON representation. private String slaveAttributesString; @Deprecated private transient JSONObject slaveAttributes; private final ContainerInfo containerInfo; private final List<URI> additionalURIs; private final Mode mode; private /*almost final*/ DescribableList<NodeProperty<?>,NodePropertyDescriptor> nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(Jenkins.getInstance()); @CheckForNull private String labelString; private static final Logger LOGGER = Logger.getLogger(MesosSlaveInfo.class .getName()); @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MesosSlaveInfo that = (MesosSlaveInfo) o; if (Double.compare(that.slaveCpus, slaveCpus) != 0) return false; if (slaveMem != that.slaveMem) return false; if (Double.compare(that.executorCpus, executorCpus) != 0) return false; if (Double.compare(that.diskNeeded, diskNeeded) !=0 ) return false; if (minExecutors != that.minExecutors) return false; if (maxExecutors != that.maxExecutors) return false; if (executorMem != that.executorMem) return false; if (idleTerminationMinutes != that.idleTerminationMinutes) return false; if (remoteFSRoot != null ? !remoteFSRoot.equals(that.remoteFSRoot) : that.remoteFSRoot != null) return false; if (jvmArgs != null ? !jvmArgs.equals(that.jvmArgs) : that.jvmArgs != null) return false; if (jnlpArgs != null ? !jnlpArgs.equals(that.jnlpArgs) : that.jnlpArgs != null) return false; if (slaveAttributesString != null ? !slaveAttributesString.equals(that.slaveAttributesString) : that.slaveAttributesString != null) return false; if (containerInfo != null ? !containerInfo.equals(that.containerInfo) : that.containerInfo != null) return false; if (additionalURIs != null ? !additionalURIs.equals(that.additionalURIs) : that.additionalURIs != null) return false; if (mode != that.mode) return false; if (nodeProperties != null ? !nodeProperties.equals(that.nodeProperties) : that.nodeProperties != null) return false; return labelString != null ? labelString.equals(that.labelString) : that.labelString == null; } @Override public int hashCode() { int result; long temp; temp = Double.doubleToLongBits(slaveCpus); result = (int) (temp ^ (temp >>> 32)); result = 31 * result + slaveMem; temp = Double.doubleToLongBits(executorCpus); result = 31 * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(diskNeeded); result = 31 * result + (int) (temp ^ (temp >>> 32)); result = 31 * result + minExecutors; result = 31 * result + maxExecutors; result = 31 * result + executorMem; result = 31 * result + (remoteFSRoot != null ? remoteFSRoot.hashCode() : 0); result = 31 * result + idleTerminationMinutes; result = 31 * result + (jvmArgs != null ? jvmArgs.hashCode() : 0); result = 31 * result + (jnlpArgs != null ? jnlpArgs.hashCode() : 0); result = 31 * result + (slaveAttributesString != null ? slaveAttributesString.hashCode() : 0); result = 31 * result + (containerInfo != null ? containerInfo.hashCode() : 0); result = 31 * result + (additionalURIs != null ? additionalURIs.hashCode() : 0); result = 31 * result + (mode != null ? mode.hashCode() : 0); result = 31 * result + (nodeProperties != null ? nodeProperties.hashCode() : 0); result = 31 * result + (labelString != null ? labelString.hashCode() : 0); return result; } @DataBoundConstructor public MesosSlaveInfo( String labelString, Mode mode, String slaveCpus, String slaveMem, String minExecutors, String maxExecutors, String executorCpus, String diskNeeded, String executorMem, String remoteFSRoot, String idleTerminationMinutes, String slaveAttributes, String jvmArgs, String jnlpArgs, String defaultSlave, ContainerInfo containerInfo, List<URI> additionalURIs, List<? extends NodeProperty<?>> nodeProperties) throws IOException, NumberFormatException { // Parse the attributes provided from the cloud config this( Util.fixEmptyAndTrim(labelString), mode != null ? mode : Mode.NORMAL, Double.parseDouble(slaveCpus), Integer.parseInt(slaveMem), Integer.parseInt(minExecutors), Integer.parseInt(maxExecutors), Double.parseDouble(executorCpus), Double.parseDouble(diskNeeded), Integer.parseInt(executorMem), StringUtils.isNotBlank(remoteFSRoot) ? remoteFSRoot.trim() : "jenkins", Integer.parseInt(idleTerminationMinutes), parseSlaveAttributes(slaveAttributes), StringUtils.isNotBlank(jvmArgs) ? cleanseJvmArgs(jvmArgs) : DEFAULT_JVM_ARGS, StringUtils.isNotBlank(jnlpArgs) ? jnlpArgs : "", Boolean.valueOf(defaultSlave), containerInfo, additionalURIs, nodeProperties); } public MesosSlaveInfo( String labelString, Mode mode, double slaveCpus, int slaveMem, int minExecutors, int maxExecutors, double executorCpus, double diskNeeded, int executorMem, String remoteFSRoot, int idleTerminationMinutes, JSONObject slaveAttributes, String jvmArgs, String jnlpArgs, Boolean defaultSlave, ContainerInfo containerInfo, List<URI> additionalURIs, List<? extends NodeProperty<?>> nodeProperties) throws IOException, NumberFormatException { this.labelString = labelString; this.mode = mode; this.slaveCpus = slaveCpus; this.slaveMem = slaveMem; this.minExecutors = minExecutors < 1 ? 1 : minExecutors; // Ensure minExecutors is at least equal to 1 this.maxExecutors = maxExecutors; this.executorCpus = executorCpus; this.diskNeeded = diskNeeded; this.executorMem = executorMem; this.remoteFSRoot = remoteFSRoot; this.idleTerminationMinutes = idleTerminationMinutes; this.slaveAttributesString = slaveAttributes != null ? slaveAttributes.toString() : null; this.jvmArgs = jvmArgs; this.jnlpArgs = jnlpArgs; this.defaultSlave = defaultSlave; this.containerInfo = containerInfo; this.additionalURIs = additionalURIs; this.nodeProperties.replaceBy(nodeProperties == null ? new ArrayList<NodeProperty<?>>() : nodeProperties); } private static JSONObject parseSlaveAttributes(String slaveAttributes) { if (StringUtils.isNotBlank(slaveAttributes)) { try { return (JSONObject) JSONSerializer.toJSON(slaveAttributes); } catch (JSONException e) { LOGGER.warning("Ignoring Mesos slave attributes JSON due to parsing error : " + slaveAttributes); } } return null; } public double getdiskNeeded() { return diskNeeded; } public MesosSlaveInfo copyWithDockerImage(String label, String dockerImage) { LOGGER.fine(String.format("Customize mesos slave %s using docker image %s", this.getLabelString(), dockerImage)); try { return new MesosSlaveInfo( label, mode, slaveCpus, slaveMem, minExecutors, maxExecutors, executorCpus, diskNeeded, executorMem, remoteFSRoot, idleTerminationMinutes, parseSlaveAttributes(slaveAttributesString), jvmArgs, jnlpArgs, defaultSlave, containerInfo.copyWithDockerImage(dockerImage), additionalURIs, nodeProperties ); } catch (Descriptor.FormException e) { LOGGER.log(Level.WARNING, "Failed to create customized mesos container info", e); return null; } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to create customized mesos slave info", e); return null; } } @CheckForNull public String getLabelString() { return labelString; } public Mode getMode() { return mode; } public double getExecutorCpus() { return executorCpus; } public double getSlaveCpus() { return slaveCpus; } public int getSlaveMem() { return slaveMem; } public int getMinExecutors() { return minExecutors; } public int getMaxExecutors() { return maxExecutors; } public int getExecutorMem() { return executorMem; } public String getRemoteFSRoot() { return remoteFSRoot; } public int getIdleTerminationMinutes() { return idleTerminationMinutes; } public JSONObject getSlaveAttributes() { return parseSlaveAttributes(slaveAttributesString); } public String getJvmArgs() { return jvmArgs; } public String getJnlpArgs() { return jnlpArgs; } public boolean isDefaultSlave() { return defaultSlave; } public ContainerInfo getContainerInfo() { return containerInfo; } public List<URI> getAdditionalURIs() { return additionalURIs; } public DescribableList<NodeProperty<?>, NodePropertyDescriptor> getNodeProperties() { assert nodeProperties != null; return nodeProperties; } /** * Removes any additional {@code -Xmx} JVM args from the provided JVM * arguments. This is to ensure that the logic that sets the maximum heap * sized based on the memory available to the slave is not overriden by a * value provided via the configuration that may not work with the current * slave's configuration. * * @param jvmArgs * the string of JVM arguments. * @return The cleansed JVM argument string. */ private static String cleanseJvmArgs(final String jvmArgs) { return jvmArgs.replaceAll(JVM_ARGS_PATTERN, ""); } /** * Check if the label in the slave matches the provided label, either both are null or are the same. * * @param label * @return Whether the slave label matches. */ public boolean matchesLabel(@CheckForNull Label label) { if (label == null || getLabelString() == null) { return label == null && getLabelString() == null; } if (label.matches(Label.parse(getLabelString()))) { return true; } if (containerInfo == null || !containerInfo.getDockerImageCustomizable()) { return false; } String customImage = getCustomImage(label); return customImage != null && getLabelWithoutCustomImage(label, customImage).matches(Label.parse(getLabelString())); } public Object readResolve() { if (nodeProperties == null) { nodeProperties = new DescribableList<NodeProperty<?>,NodePropertyDescriptor>(Jenkins.getInstance()); } if (minExecutors == 0) { this.minExecutors = 1; } if (slaveAttributes != null) { slaveAttributesString = slaveAttributes.toString(); slaveAttributes = null; } return this; } private static String getCustomImage(Label label) { Matcher m = CUSTOM_IMAGE_FROM_LABEL_PATTERN.matcher(label.toString()); if (m.find()) { return m.group(1); } return null; } private static Label getLabelWithoutCustomImage(Label label, String customDockerImage) { return Label.get(label.toString().replace(CUSTOM_IMAGE_SEPARATOR + customDockerImage, "")); } public MesosSlaveInfo getMesosSlaveInfoForLabel(Label label) { if (!matchesLabel(label)) { return null; } if (label == null) { if (getLabelString() == null) { return this; } else { return null; } } if (label.matches(Label.parse(getLabelString()))) { return this; } if (!containerInfo.getDockerImageCustomizable()) { return null; } String customImage = getCustomImage(label); if (customImage == null) { return null; } return copyWithDockerImage(label.toString(), customImage); } public static class ExternalContainerInfo { private final String image; private final String options; @DataBoundConstructor public ExternalContainerInfo(String image, String options) { this.image = image; this.options = options; } public String getOptions() { return options; } public String getImage() { return image; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ExternalContainerInfo that = (ExternalContainerInfo) o; if (image != null ? !image.equals(that.image) : that.image != null) return false; return options != null ? options.equals(that.options) : that.options == null; } @Override public int hashCode() { int result = image != null ? image.hashCode() : 0; result = 31 * result + (options != null ? options.hashCode() : 0); return result; } } public static class ContainerInfo extends AbstractDescribableImpl<ContainerInfo> { @Extension public static class DescriptorImpl extends Descriptor<ContainerInfo> { public String getDisplayName() { return ""; } } private final String type; private final String dockerImage; private final List<Volume> volumes; private final List<Parameter> parameters; private final String networking; private static final String DEFAULT_NETWORKING = Network.BRIDGE.name(); private final List<PortMapping> portMappings; private final List<NetworkInfo> networkInfos; private final boolean useCustomDockerCommandShell; private final String customDockerCommandShell; private final boolean dockerPrivilegedMode; private final boolean dockerForcePullImage; private final boolean dockerImageCustomizable; @DataBoundConstructor public ContainerInfo(String type, String dockerImage, boolean dockerPrivilegedMode, boolean dockerForcePullImage, boolean dockerImageCustomizable, boolean useCustomDockerCommandShell, String customDockerCommandShell, List<Volume> volumes, List<Parameter> parameters, String networking, List<PortMapping> portMappings, List<NetworkInfo> networkInfos) throws FormException { this.type = type; this.dockerImage = dockerImage; this.dockerPrivilegedMode = dockerPrivilegedMode; this.dockerForcePullImage = dockerForcePullImage; this.dockerImageCustomizable = dockerImageCustomizable; this.useCustomDockerCommandShell = useCustomDockerCommandShell; this.customDockerCommandShell = customDockerCommandShell; this.volumes = volumes; this.parameters = parameters; this.networkInfos = networkInfos; if (networking == null) { this.networking = DEFAULT_NETWORKING; } else { this.networking = networking; } if (Network.HOST.equals(Network.valueOf(networking))) { this.portMappings = Collections.emptyList(); } else { this.portMappings = portMappings; } } public ContainerInfo copyWithDockerImage(String dockerImage) throws FormException { return new ContainerInfo( type, dockerImage, // custom docker image dockerPrivilegedMode, dockerForcePullImage, dockerImageCustomizable, useCustomDockerCommandShell, customDockerCommandShell, volumes, parameters, networking, portMappings, networkInfos ); } public String getType() { return type; } public String getDockerImage() { return dockerImage; } public List<Volume> getVolumes() { return volumes; } public List<Parameter> getParameters() { return parameters; } public List<NetworkInfo> getNetworkInfos() { return networkInfos; } public boolean hasNetworkInfos() { return networkInfos != null && !networkInfos.isEmpty(); } public String getNetworking() { if (networking != null) { return networking; } else { return DEFAULT_NETWORKING; } } public List<PortMapping> getPortMappings() { if (portMappings != null) { return portMappings; } else { return Collections.emptyList(); } } public boolean hasPortMappings() { return portMappings != null && !portMappings.isEmpty(); } public boolean getDockerPrivilegedMode() { return dockerPrivilegedMode; } public boolean getDockerForcePullImage() { return dockerForcePullImage; } public boolean getDockerImageCustomizable() { return dockerImageCustomizable; } public boolean getUseCustomDockerCommandShell() { return useCustomDockerCommandShell; } public String getCustomDockerCommandShell() { return customDockerCommandShell; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ContainerInfo that = (ContainerInfo) o; if (useCustomDockerCommandShell != that.useCustomDockerCommandShell) return false; if (type != null ? !type.equals(that.type) : that.type != null) return false; if (dockerImage != null ? !dockerImage.equals(that.dockerImage) : that.dockerImage != null) return false; if (volumes != null ? !volumes.equals(that.volumes) : that.volumes != null) return false; if (parameters != null ? !parameters.equals(that.parameters) : that.parameters != null) return false; if (networking != null ? !networking.equals(that.networking) : that.networking != null) return false; if (portMappings != null ? !portMappings.equals(that.portMappings) : that.portMappings != null) return false; if (networkInfos != null ? !networkInfos.equals(that.networkInfos) : that.networkInfos != null) return false; if (customDockerCommandShell != null ? !customDockerCommandShell.equals(that.customDockerCommandShell) : that.customDockerCommandShell != null) return false; if (dockerPrivilegedMode != that.dockerPrivilegedMode) return false; if (dockerForcePullImage != that.dockerForcePullImage) return false; return dockerImageCustomizable == that.dockerImageCustomizable; } @Override public int hashCode() { int result = type != null ? type.hashCode() : 0; result = 31 * result + (dockerImage != null ? dockerImage.hashCode() : 0); result = 31 * result + (volumes != null ? volumes.hashCode() : 0); result = 31 * result + (parameters != null ? parameters.hashCode() : 0); result = 31 * result + (networking != null ? networking.hashCode() : 0); result = 31 * result + (networkInfos != null ? networkInfos.hashCode() : 0); result = 31 * result + (portMappings != null ? portMappings.hashCode() : 0); result = 31 * result + (useCustomDockerCommandShell ? 1 : 0); result = 31 * result + (customDockerCommandShell != null ? customDockerCommandShell.hashCode() : 0); result = 31 * result + (dockerPrivilegedMode ? 1 : 0); result = 31 * result + (dockerForcePullImage ? 1 : 0); result = 31 * result + (dockerImageCustomizable ? 1 : 0); return result; } } public static class Parameter extends AbstractDescribableImpl<Parameter> { @Extension public static class DescriptorImpl extends Descriptor<Parameter> { public String getDisplayName() { return ""; } } private final String key; private final String value; @DataBoundConstructor public Parameter(String key, String value) { this.key = key; this.value = value; } public String getKey() { return key; } public String getValue() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Parameter parameter = (Parameter) o; if (key != null ? !key.equals(parameter.key) : parameter.key != null) return false; return value != null ? value.equals(parameter.value) : parameter.value == null; } @Override public int hashCode() { int result = key != null ? key.hashCode() : 0; result = 31 * result + (value != null ? value.hashCode() : 0); return result; } } public static class PortMapping extends AbstractDescribableImpl<PortMapping> { @Extension public static class DescriptorImpl extends Descriptor<PortMapping> { public String getDisplayName() { return ""; } } // TODO validate 1 to 65535 private final Integer containerPort; private final Integer hostPort; private final String protocol; @DataBoundConstructor public PortMapping(Integer containerPort, Integer hostPort, String protocol) { this.containerPort = containerPort; this.hostPort = hostPort; this.protocol = protocol; } public Integer getContainerPort() { return containerPort; } public Integer getHostPort() { return hostPort; } public String getProtocol() { return protocol; } @Override public String toString() { return (hostPort == null ? 0 : hostPort) + ":" + containerPort; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PortMapping that = (PortMapping) o; if (containerPort != null ? !containerPort.equals(that.containerPort) : that.containerPort != null) return false; if (hostPort != null ? !hostPort.equals(that.hostPort) : that.hostPort != null) return false; return protocol != null ? protocol.equals(that.protocol) : that.protocol == null; } @Override public int hashCode() { int result = containerPort != null ? containerPort.hashCode() : 0; result = 31 * result + (hostPort != null ? hostPort.hashCode() : 0); result = 31 * result + (protocol != null ? protocol.hashCode() : 0); return result; } } public static class Volume extends AbstractDescribableImpl<Volume> { @Extension public static class DescriptorImpl extends Descriptor<Volume> { public String getDisplayName() { return ""; } } private final String containerPath; private final String hostPath; private final boolean readOnly; @DataBoundConstructor public Volume(String containerPath, String hostPath, boolean readOnly) { this.containerPath = containerPath; this.hostPath = hostPath; this.readOnly = readOnly; } public String getContainerPath() { return containerPath; } public String getHostPath() { return hostPath; } public boolean isReadOnly() { return readOnly; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Volume volume = (Volume) o; if (readOnly != volume.readOnly) return false; if (containerPath != null ? !containerPath.equals(volume.containerPath) : volume.containerPath != null) return false; return hostPath != null ? hostPath.equals(volume.hostPath) : volume.hostPath == null; } @Override public int hashCode() { int result = containerPath != null ? containerPath.hashCode() : 0; result = 31 * result + (hostPath != null ? hostPath.hashCode() : 0); result = 31 * result + (readOnly ? 1 : 0); return result; } } public static class URI extends AbstractDescribableImpl<URI> { @Extension public static class DescriptorImpl extends Descriptor<URI> { public String getDisplayName() { return ""; } } private final String value; private final boolean executable; private final boolean extract; @DataBoundConstructor public URI(String value, boolean executable, boolean extract) { this.value = value; this.executable = executable; this.extract = extract; } public String getValue() { return value; } public boolean isExecutable() { return executable; } public boolean isExtract() { return extract; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; URI uri = (URI) o; if (executable != uri.executable) return false; if (extract != uri.extract) return false; return value != null ? value.equals(uri.value) : uri.value == null; } @Override public int hashCode() { int result = value != null ? value.hashCode() : 0; result = 31 * result + (executable ? 1 : 0); result = 31 * result + (extract ? 1 : 0); return result; } } public static class NetworkInfo extends AbstractDescribableImpl<NetworkInfo> { @Extension public static class DescriptorImpl extends Descriptor<NetworkInfo> { public String getDisplayName() { return ""; } } private final String networkName; @DataBoundConstructor public NetworkInfo(String networkName) { this.networkName = networkName; } public String getNetworkName() { return networkName; } public boolean hasNetworkName() { return networkName != null && !networkName.isEmpty(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NetworkInfo networkInfo = (NetworkInfo) o; return networkName != null ? networkName.equals(networkInfo.networkName) : networkInfo.networkName == null; } @Override public int hashCode() { int result = networkName != null ? networkName.hashCode() : 0; return result; } } }
maselvaraj/mesos-plugin
src/main/java/org/jenkinsci/plugins/mesos/MesosSlaveInfo.java
Java
apache-2.0
29,757
/** * Copyright 2011 (C) 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.livetribe.jmx.jsonrpc.model; import javax.management.ObjectName; import java.util.Date; /** * */ public class Notification { /** * @serial The notification type. * A string expressed in a dot notation similar to Java properties. * An example of a notification type is network.alarm.router */ private String type; /** * @serial The notification sequence number. * A serial number which identify particular instance * of notification in the context of the notification source. */ private long sequenceNumber; /** * @serial The notification timestamp. * Indicating when the notification was generated */ private long timeStamp; /** * @serial The notification user data. * Used for whatever other data the notification * source wishes to communicate to its consumers */ private Object userData = null; /** * @serial The notification message. */ private String message = ""; /** * @serial The object on which the notification initially occurred. */ private ObjectName source = null; public Notification() { } public Notification(String type, long sequenceNumber, long timeStamp, Object userData, String message, ObjectName source) { this.type = type; this.sequenceNumber = sequenceNumber; this.timeStamp = timeStamp; this.userData = userData; this.message = message; this.source = source; } public Notification(javax.management.Notification notification, ObjectName source) { assert notification != null; assert source != null; this.type = notification.getType(); this.sequenceNumber = notification.getSequenceNumber(); this.timeStamp = notification.getTimeStamp(); this.userData = notification.getUserData(); this.message = notification.getMessage(); this.source = source; } public String getType() { return type; } public void setType(String type) { this.type = type; } public long getSequenceNumber() { return sequenceNumber; } public void setSequenceNumber(long sequenceNumber) { this.sequenceNumber = sequenceNumber; } public long getTimeStamp() { return timeStamp; } public void setTimeStamp(long timeStamp) { this.timeStamp = timeStamp; } public Object getUserData() { return userData; } public void setUserData(Object userData) { this.userData = userData; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public ObjectName getSource() { return source; } public void setSource(ObjectName source) { this.source = source; } @Override public String toString() { return "[" + sequenceNumber + "] " + type + ": " + message + " " + new Date(timeStamp) + " from " + source; } }
livetribe/livetribe-jmx-json
core/src/main/java/org/livetribe/jmx/jsonrpc/model/Notification.java
Java
apache-2.0
3,752
package io.irontest.core; import org.apache.commons.text.StrLookup; import java.util.HashSet; import java.util.Map; import java.util.Set; public class MapValueLookup extends StrLookup<String> { private Map<String, String> map; private boolean escapeForJSON; private Set<String> unfoundKeys = new HashSet<>(); public MapValueLookup(Map<String, String> map, boolean escapeForJSON) { this.map = map; this.escapeForJSON = escapeForJSON; } @Override public String lookup(String key) { key = key.trim(); for (Map.Entry<String, String> entry: map.entrySet()) { if (key.equals(entry.getKey())) { String value = entry.getValue(); if (escapeForJSON) { // replace \ and " with \\ and \" for the result to be used in JSON string value = value.replace("\\", "\\\\"); value = value.replace("\"", "\\\""); } return value; } } unfoundKeys.add(key); return null; // returning null leaves the reference untouched (not replaced) in the template string } public Set<String> getUnfoundKeys() { return unfoundKeys; } }
zheng-wang/irontest
irontest-core-server/src/main/java/io/irontest/core/MapValueLookup.java
Java
apache-2.0
1,241
/* Written in 2015 by Sebastiano Vigna (vigna@acm.org) To the extent possible under law, the author has dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. See <http://creativecommons.org/publicdomain/zero/1.0/>. */ package squidpony.squidmath; /** * This is a SplittableRandom-style generator, meant to have a tiny state * that permits storing many different generators with low overhead. * It should be rather fast, though no guarantees can be made. * Written in 2015 by Sebastiano Vigna (vigna@acm.org) * @author Sebastiano Vigna * @author Tommy Ettinger */ public class LightRNG implements RandomnessSource, StatefulRandomness { private static final long serialVersionUID = 4L; /** 2 raised to the 53, - 1. */ private static final long DOUBLE_MASK = ( 1L << 53 ) - 1; /** 2 raised to the -53. */ private static final double NORM_53 = 1. / ( 1L << 53 ); /** 2 raised to the 24, -1. */ private static final long FLOAT_MASK = ( 1L << 24 ) - 1; /** 2 raised to the -24. */ private static final double NORM_24 = 1. / ( 1L << 24 ); public long state; /* The state can be seeded with any value. */ /** Creates a new generator seeded using Math.random. */ public LightRNG() { this((long) Math.floor(Math.random() * Long.MAX_VALUE)); } public LightRNG( final long seed ) { setSeed(seed); } @Override public int next( int bits ) { return (int)( nextLong() & ( 1L << bits ) - 1 ); } /** * Can return any long, positive or negative, of any size permissible in a 64-bit signed integer. * @return */ public long nextLong() { long z = ( state += 0x9E3779B97F4A7C15l ); z = (z ^ (z >>> 30)) * 0xBF58476D1CE4E5B9l; z = (z ^ (z >>> 27)) * 0x94D049BB133111EBl; return z ^ (z >>> 31); } /** * Can return any int, positive or negative, of any size permissible in a 32-bit signed integer. * @return */ public int nextInt() { return (int)nextLong(); } /** * Exclusive on the upper bound n. The lower bound is 0. * @param n * @return */ public int nextInt( final int n ) { if ( n <= 0 ) throw new IllegalArgumentException(); for(;;) { final int bits = nextInt(); int value = bits % n; value = (value < 0) ? -value : value; if ( bits - value + ( n - 1 ) >= 0 ) return value; } } /** * Inclusive lower, exclusive upper. * @param lower * @param upper * @return */ public int nextInt( final int lower, final int upper ) { if ( upper - lower <= 0 ) throw new IllegalArgumentException(); return lower + nextInt(upper - lower); } /** * Exclusive on the upper bound n. The lower bound is 0. * @param n * @return */ public long nextLong( final long n ) { if ( n <= 0 ) throw new IllegalArgumentException(); for(;;) { final long bits = nextLong() >>> 1; long value = bits % n; value = (value < 0) ? -value : value; if ( bits - value + ( n - 1 ) >= 0 ) return value; } } /** * Inclusive lower, exclusive upper. * @param lower * @param upper * @return */ public long nextLong( final long lower, final long upper ) { if ( upper - lower <= 0 ) throw new IllegalArgumentException(); return lower + nextLong(upper - lower); } /** * Gets a uniform random double in the range [0.0,1.0) * @return */ public double nextDouble() { return ( nextLong() & DOUBLE_MASK ) * NORM_53; } /** * Gets a uniform random double in the range [0.0,upper) given the parameter upper. * @param upper * @return */ public double nextDouble(final double upper) { return nextDouble() * upper; } /** * Gets a uniform random float in the range [0.0,1.0) * @return */ public float nextFloat() { return (float)( ( nextLong() & FLOAT_MASK ) * NORM_24 ); } public boolean nextBoolean() { return ( nextLong() & 1 ) != 0L; } public void nextBytes( final byte[] bytes ) { int i = bytes.length, n = 0; while( i != 0 ) { n = Math.min( i, 8 ); for ( long bits = nextLong(); n-- != 0; bits >>= 8 ) bytes[ --i ] = (byte)bits; } } /** * Sets the seed of this generator (which is also the current state). */ public void setSeed( final long seed ) { state = seed; } /** * Sets the seed (also the current state) of this generator. */ public void setState( final long seed ) { state = seed; } /** * Gets the current state of this generator. */ public long getState( ) { return state; } /** * Skip forward or backward a number of steps specified by advance, without generating a number at each step. * @param advance Number of future generations to skip past. Can be negative to backtrack. */ public void skip(long advance) { state += 0x9E3779B97F4A7C15l * advance; } }
devilbuddy/SquidLib
squidlib-util/src/main/java/squidpony/squidmath/LightRNG.java
Java
apache-2.0
5,337
package com.secunet.eidserver.testbed.common.interfaces.entities; import java.util.Set; import com.secunet.eidserver.testbed.common.enumerations.Role; public interface User { public String getId(); public void setId(String id); public String getName(); public void setName(String name); public String getPwdHash(); public void setPwdHash(String pwdHash); public Role getRole(); public void setRole(Role role); public Token getToken(); public void setToken(Token token); public Set<TestCandidate> getProfiles(); public void setProfiles(Set<TestCandidate> profiles); }
eID-Testbeds/server
eidsrv-testbed-common/src/main/java/com/secunet/eidserver/testbed/common/interfaces/entities/User.java
Java
apache-2.0
628
package org.certificatetransparency.ctlog.comm; import java.io.ByteArrayInputStream; import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.ArrayList; import java.util.List; import org.apache.commons.codec.binary.Base64; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.certificatetransparency.ctlog.CertificateInfo; import org.certificatetransparency.ctlog.CertificateTransparencyException; import org.certificatetransparency.ctlog.ParsedLogEntry; import org.certificatetransparency.ctlog.MerkleAuditProof; import org.certificatetransparency.ctlog.ParsedLogEntryWithProof; import org.certificatetransparency.ctlog.SignedTreeHead; import org.certificatetransparency.ctlog.proto.Ct; import org.certificatetransparency.ctlog.serialization.Deserializer; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.protobuf.ByteString; /** A CT HTTP client. Abstracts away the json encoding necessary for the server. */ public class HttpLogClient { private static final String ADD_PRE_CHAIN_PATH = "add-pre-chain"; private static final String ADD_CHAIN_PATH = "add-chain"; private static final String GET_STH_PATH = "get-sth"; private static final String GET_ROOTS_PATH = "get-roots"; private static final String GET_ENTRIES = "get-entries"; private static final String GET_STH_CONSISTENCY = "get-sth-consistency"; private static final String GET_ENTRY_AND_PROOF = "get-entry-and-proof"; private static final String GET_PROOF_BY_HASH = "get-proof-by-hash"; private final String logUrl; private final HttpInvoker postInvoker; /** * New HttpLogClient. * * @param logUrl CT Log's full URL, e.g. "http://ct.googleapis.com/pilot/ct/v1/" */ public HttpLogClient(String logUrl) { this(logUrl, new HttpInvoker()); } /** * For testing specify an HttpInvoker * * @param logUrl URL of the log. * @param postInvoker HttpInvoker instance to use. */ public HttpLogClient(String logUrl, HttpInvoker postInvoker) { this.logUrl = logUrl; this.postInvoker = postInvoker; } /** * JSON-encodes the list of certificates into a JSON object. * * @param certs Certificates to encode. * @return A JSON object with one field, "chain", holding a JSON array of base64-encoded certs. */ @SuppressWarnings("unchecked") // Because JSONObject, JSONArray extend raw types. JSONObject encodeCertificates(List<Certificate> certs) { JSONArray retObject = new JSONArray(); try { for (Certificate cert : certs) { retObject.add(Base64.encodeBase64String(cert.getEncoded())); } } catch (CertificateEncodingException e) { throw new CertificateTransparencyException("Error encoding certificate", e); } JSONObject jsonObject = new JSONObject(); jsonObject.put("chain", retObject); return jsonObject; } /** * Parses the CT Log's json response into a proper proto. * * @param responseBody Response string to parse. * @return SCT filled from the JSON input. */ static Ct.SignedCertificateTimestamp parseServerResponse(String responseBody) { if (responseBody == null) { return null; } JSONObject parsedResponse = (JSONObject) JSONValue.parse(responseBody); Ct.SignedCertificateTimestamp.Builder builder = Ct.SignedCertificateTimestamp.newBuilder(); int numericVersion = ((Number) parsedResponse.get("sct_version")).intValue(); Ct.Version version = Ct.Version.valueOf(numericVersion); if (version == null) { throw new IllegalArgumentException( String.format("Input JSON has an invalid version: %d", numericVersion)); } builder.setVersion(version); Ct.LogID.Builder logIdBuilder = Ct.LogID.newBuilder(); logIdBuilder.setKeyId( ByteString.copyFrom(Base64.decodeBase64((String) parsedResponse.get("id")))); builder.setId(logIdBuilder.build()); builder.setTimestamp(((Number) parsedResponse.get("timestamp")).longValue()); String extensions = (String) parsedResponse.get("extensions"); if (!extensions.isEmpty()) { builder.setExtensions(ByteString.copyFrom(Base64.decodeBase64(extensions))); } String base64Signature = (String) parsedResponse.get("signature"); builder.setSignature( Deserializer.parseDigitallySignedFromBinary( new ByteArrayInputStream(Base64.decodeBase64(base64Signature)))); return builder.build(); } /** * Adds a certificate to the log. * * @param certificatesChain The certificate chain to add. * @return SignedCertificateTimestamp if the log added the chain successfully. */ public Ct.SignedCertificateTimestamp addCertificate(List<Certificate> certificatesChain) { Preconditions.checkArgument( !certificatesChain.isEmpty(), "Must have at least one certificate to submit."); boolean isPreCertificate = CertificateInfo.isPreCertificate(certificatesChain.get(0)); if (isPreCertificate && CertificateInfo.isPreCertificateSigningCert(certificatesChain.get(1))) { Preconditions.checkArgument( certificatesChain.size() >= 3, "When signing a PreCertificate with a PreCertificate Signing Cert," + " the issuer certificate must follow."); } return addCertificate(certificatesChain, isPreCertificate); } private Ct.SignedCertificateTimestamp addCertificate( List<Certificate> certificatesChain, boolean isPreCertificate) { String jsonPayload = encodeCertificates(certificatesChain).toJSONString(); String methodPath; if (isPreCertificate) { methodPath = ADD_PRE_CHAIN_PATH; } else { methodPath = ADD_CHAIN_PATH; } String response = postInvoker.makePostRequest(logUrl + methodPath, jsonPayload); return parseServerResponse(response); } /** * Retrieves Latest Signed Tree Head from the log. The signature of the Signed Tree Head component * is not verified. * * @return latest STH */ public SignedTreeHead getLogSTH() { String response = postInvoker.makeGetRequest(logUrl + GET_STH_PATH); return parseSTHResponse(response); } /** * Retrieves accepted Root Certificates. * * @return a list of root certificates. */ public List<Certificate> getLogRoots() { String response = postInvoker.makeGetRequest(logUrl + GET_ROOTS_PATH); return parseRootCertsResponse(response); } /** * Retrieve Entries from Log. * * @param start 0-based index of first entry to retrieve, in decimal. * @param end 0-based index of last entry to retrieve, in decimal. * @return list of Log's entries. */ public List<ParsedLogEntry> getLogEntries(long start, long end) { Preconditions.checkArgument(0 <= start && end >= start); List<NameValuePair> params = createParamsList("start", "end", Long.toString(start), Long.toString(end)); String response = postInvoker.makeGetRequest(logUrl + GET_ENTRIES, params); return parseLogEntries(response); } /** * Retrieve Merkle Consistency Proof between Two Signed Tree Heads. * * @param first The tree_size of the first tree, in decimal. * @param second The tree_size of the second tree, in decimal. * @return A list of base64 decoded Merkle Tree nodes serialized to ByteString objects. */ public List<ByteString> getSTHConsistency(long first, long second) { Preconditions.checkArgument(0 <= first && second >= first); List<NameValuePair> params = createParamsList("first", "second", Long.toString(first), Long.toString(second)); String response = postInvoker.makeGetRequest(logUrl + GET_STH_CONSISTENCY, params); return parseConsistencyProof(response); } /** * Retrieve Entry+Merkle Audit Proof from Log. * * @param leafindex The index of the desired entry. * @param treeSize The tree_size of the tree for which the proof is desired. * @return ParsedLog entry object with proof. */ public ParsedLogEntryWithProof getLogEntryAndProof(long leafindex, long treeSize) { Preconditions.checkArgument(0 <= leafindex && treeSize >= leafindex); List<NameValuePair> params = createParamsList( "leaf_index", "tree_size", Long.toString(leafindex), Long.toString(treeSize)); String response = postInvoker.makeGetRequest(logUrl + GET_ENTRY_AND_PROOF, params); JSONObject entry = (JSONObject) JSONValue.parse(response); JSONArray auditPath = (JSONArray) entry.get("audit_path"); return Deserializer.parseLogEntryWithProof( jsonToLogEntry.apply(entry), auditPath, leafindex, treeSize); } /** * Retrieve Merkle Audit Proof from Log by Merkle Leaf Hash. * * @param leafHash sha256 hash of MerkleTreeLeaf. * @return MerkleAuditProof object. */ public MerkleAuditProof getProofByHash(byte[] leafHash) { Preconditions.checkArgument(leafHash != null && leafHash.length > 0); String encodedMerkleLeafHash = Base64.encodeBase64String(leafHash); SignedTreeHead sth = getLogSTH(); return getProofByEncodedHash(encodedMerkleLeafHash, sth.treeSize); } /** * Retrieve Merkle Audit Proof from Log by Merkle Leaf Hash. * * @param encodedMerkleLeafHash Base64 encoded of sha256 hash of MerkleTreeLeaf. * @param treeSize The tree_size of the tree for which the proof is desired. It can be obtained * from latest STH. * @return MerkleAuditProof object. */ public MerkleAuditProof getProofByEncodedHash(String encodedMerkleLeafHash, long treeSize) { Preconditions.checkArgument( encodedMerkleLeafHash != null && encodedMerkleLeafHash.length() > 0); List<NameValuePair> params = createParamsList("tree_size", "hash", Long.toString(treeSize), encodedMerkleLeafHash); String response = postInvoker.makeGetRequest(logUrl + GET_PROOF_BY_HASH, params); JSONObject entry = (JSONObject) JSONValue.parse(response); JSONArray auditPath = (JSONArray) entry.get("audit_path"); long leafindex = Long.valueOf(String.valueOf(entry.get("leaf_index"))); return Deserializer.parseAuditProof(auditPath, leafindex, treeSize); } /** * Creates a list of NameValuePair objects. * * @param firstParamName The first parameter name. * @param firstParamValue The first parameter value. * @param secondParamName The second parameter name. * @param secondParamValue The second parameter value. * @return A list of NameValuePair objects. */ private List<NameValuePair> createParamsList( String firstParamName, String secondParamName, String firstParamValue, String secondParamValue) { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(firstParamName, firstParamValue)); params.add(new BasicNameValuePair(secondParamName, secondParamValue)); return params; } /** * Parses CT log's response for "get-entries" into a list of {@link ParsedLogEntry} objects. * * @param response Log response to pars. * @return list of Log's entries. */ @SuppressWarnings("unchecked") private List<ParsedLogEntry> parseLogEntries(String response) { Preconditions.checkNotNull(response, "Log entries response from Log should not be null."); JSONObject responseJson = (JSONObject) JSONValue.parse(response); JSONArray arr = (JSONArray) responseJson.get("entries"); return Lists.transform(arr, jsonToLogEntry); } private Function<JSONObject, ParsedLogEntry> jsonToLogEntry = new Function<JSONObject, ParsedLogEntry>() { @Override public ParsedLogEntry apply(JSONObject entry) { String leaf = (String) entry.get("leaf_input"); String extra = (String) entry.get("extra_data"); return Deserializer.parseLogEntry( new ByteArrayInputStream(Base64.decodeBase64(leaf)), new ByteArrayInputStream(Base64.decodeBase64(extra))); } }; /** * Parses CT log's response for the "get-sth-consistency" request. * * @param response JsonObject containing an array of Merkle Tree nodes. * @return A list of base64 decoded Merkle Tree nodes serialized to ByteString objects. */ private List<ByteString> parseConsistencyProof(String response) { Preconditions.checkNotNull(response, "Merkle Consistency response should not be null."); JSONObject responseJson = (JSONObject) JSONValue.parse(response); JSONArray arr = (JSONArray) responseJson.get("consistency"); List<ByteString> proof = new ArrayList<ByteString>(); for (Object node : arr) { proof.add(ByteString.copyFrom(Base64.decodeBase64((String) node))); } return proof; } /** * Parses CT log's response for "get-sth" into a proto object. * * @param sthResponse Log response to parse * @return a proto object of SignedTreeHead type. */ SignedTreeHead parseSTHResponse(String sthResponse) { Preconditions.checkNotNull( sthResponse, "Sign Tree Head response from a CT log should not be null"); JSONObject response = (JSONObject) JSONValue.parse(sthResponse); long treeSize = (Long) response.get("tree_size"); long timestamp = (Long) response.get("timestamp"); if (treeSize < 0 || timestamp < 0) { throw new CertificateTransparencyException( String.format( "Bad response. Size of tree or timestamp cannot be a negative value. " + "Log Tree size: %d Timestamp: %d", treeSize, timestamp)); } String base64Signature = (String) response.get("tree_head_signature"); String sha256RootHash = (String) response.get("sha256_root_hash"); SignedTreeHead sth = new SignedTreeHead(Ct.Version.V1); sth.treeSize = treeSize; sth.timestamp = timestamp; sth.sha256RootHash = Base64.decodeBase64(sha256RootHash); sth.signature = Deserializer.parseDigitallySignedFromBinary( new ByteArrayInputStream(Base64.decodeBase64(base64Signature))); if (sth.sha256RootHash.length != 32) { throw new CertificateTransparencyException( String.format( "Bad response. The root hash of the Merkle Hash Tree must be 32 bytes. " + "The size of the root hash is %d", sth.sha256RootHash.length)); } return sth; } /** * Parses the response from "get-roots" GET method. * * @param response JSONObject with certificates to parse. * @return a list of root certificates. */ List<Certificate> parseRootCertsResponse(String response) { List<Certificate> certs = new ArrayList<>(); JSONObject entries = (JSONObject) JSONValue.parse(response); JSONArray entriesArray = (JSONArray) entries.get("certificates"); for (Object i : entriesArray) { // We happen to know that JSONArray contains strings. byte[] in = Base64.decodeBase64((String) i); try { certs.add( CertificateFactory.getInstance("X509") .generateCertificate(new ByteArrayInputStream(in))); } catch (CertificateException e) { throw new CertificateTransparencyException( "Malformed data from a CT log have been received: " + e.getLocalizedMessage(), e); } } return certs; } }
google/certificate-transparency-java
src/main/java/org/certificatetransparency/ctlog/comm/HttpLogClient.java
Java
apache-2.0
15,577
package org.apereo.cas.web.flow.login; import org.apereo.cas.CentralAuthenticationService; import org.apereo.cas.authentication.Authentication; import org.apereo.cas.authentication.AuthenticationResult; import org.apereo.cas.authentication.AuthenticationSystemSupport; import org.apereo.cas.authentication.MessageDescriptor; import org.apereo.cas.authentication.PrincipalException; import org.apereo.cas.ticket.InvalidTicketException; import org.apereo.cas.ticket.TicketGrantingTicket; import org.apereo.cas.ticket.registry.TicketRegistrySupport; import org.apereo.cas.web.flow.CasWebflowConstants; import org.apereo.cas.web.support.WebUtils; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.EqualsBuilder; import org.springframework.binding.message.MessageBuilder; import org.springframework.binding.message.MessageContext; import org.springframework.webflow.action.AbstractAction; import org.springframework.webflow.action.EventFactorySupport; import org.springframework.webflow.core.collection.LocalAttributeMap; import org.springframework.webflow.execution.Event; import org.springframework.webflow.execution.RequestContext; import java.util.Collection; import java.util.stream.Collectors; /** * Action that handles the {@link TicketGrantingTicket} creation and destruction. If the * action is given a {@link TicketGrantingTicket} and one also already exists, the old * one is destroyed and replaced with the new one. This action always returns * "success". * * @author Scott Battaglia * @since 3.0.0 */ @Slf4j @RequiredArgsConstructor public class CreateTicketGrantingTicketAction extends AbstractAction { private final CentralAuthenticationService centralAuthenticationService; private final AuthenticationSystemSupport authenticationSystemSupport; private final TicketRegistrySupport ticketRegistrySupport; /** * Add warning messages to message context if needed. * * @param tgtId the tgt id * @param messageContext the message context * @return authn warnings from all handlers and results * @since 4.1.0 */ private static Collection<MessageDescriptor> calculateAuthenticationWarningMessages(final TicketGrantingTicket tgtId, final MessageContext messageContext) { val entries = tgtId.getAuthentication().getSuccesses().entrySet(); val messages = entries .stream() .map(entry -> entry.getValue().getWarnings()) .filter(entry -> !entry.isEmpty()) .collect(Collectors.toList()); messages.add(tgtId.getAuthentication().getWarnings()); return messages .stream() .flatMap(Collection::stream) .peek(message -> addMessageDescriptorToMessageContext(messageContext, message)) .collect(Collectors.toSet()); } /** * Adds a warning message to the message context. * * @param context Message context. * @param warning Warning message. */ protected static void addMessageDescriptorToMessageContext(final MessageContext context, final MessageDescriptor warning) { val builder = new MessageBuilder() .warning() .code(warning.getCode()) .defaultText(warning.getDefaultMessage()) .args((Object[]) warning.getParams()); context.addMessage(builder.build()); } @Override public Event doExecute(final RequestContext context) { val service = WebUtils.getService(context); val registeredService = WebUtils.getRegisteredService(context); val authenticationResultBuilder = WebUtils.getAuthenticationResultBuilder(context); LOGGER.trace("Finalizing authentication transactions and issuing ticket-granting ticket"); val authenticationResult = this.authenticationSystemSupport.finalizeAllAuthenticationTransactions(authenticationResultBuilder, service); LOGGER.trace("Finalizing authentication event..."); val authentication = buildFinalAuthentication(authenticationResult); val ticketGrantingTicket = WebUtils.getTicketGrantingTicketId(context); LOGGER.debug("Creating ticket-granting ticket, potentially based on [{}]", ticketGrantingTicket); val tgt = createOrUpdateTicketGrantingTicket(authenticationResult, authentication, ticketGrantingTicket); if (registeredService != null && registeredService.getAccessStrategy() != null) { WebUtils.putUnauthorizedRedirectUrlIntoFlowScope(context, registeredService.getAccessStrategy().getUnauthorizedRedirectUrl()); } WebUtils.putTicketGrantingTicketInScopes(context, tgt); WebUtils.putAuthenticationResult(authenticationResult, context); WebUtils.putAuthentication(tgt.getAuthentication(), context); LOGGER.trace("Calculating authentication warning messages..."); val warnings = calculateAuthenticationWarningMessages(tgt, context.getMessageContext()); if (!warnings.isEmpty()) { val attributes = new LocalAttributeMap(CasWebflowConstants.ATTRIBUTE_ID_AUTHENTICATION_WARNINGS, warnings); return new EventFactorySupport().event(this, CasWebflowConstants.TRANSITION_ID_SUCCESS_WITH_WARNINGS, attributes); } return success(); } /** * Build final authentication authentication. * * @param authenticationResult the authentication result * @return the authentication */ protected Authentication buildFinalAuthentication(final AuthenticationResult authenticationResult) { return authenticationResult.getAuthentication(); } /** * Create or update ticket granting ticket ticket granting ticket. * * @param authenticationResult the authentication result * @param authentication the authentication * @param ticketGrantingTicket the ticket granting ticket * @return the ticket granting ticket */ protected TicketGrantingTicket createOrUpdateTicketGrantingTicket(final AuthenticationResult authenticationResult, final Authentication authentication, final String ticketGrantingTicket) { try { if (shouldIssueTicketGrantingTicket(authentication, ticketGrantingTicket)) { LOGGER.debug("Attempting to issue a new ticket-granting ticket..."); return this.centralAuthenticationService.createTicketGrantingTicket(authenticationResult); } LOGGER.debug("Updating the existing ticket-granting ticket [{}]...", ticketGrantingTicket); val tgt = this.centralAuthenticationService.getTicket(ticketGrantingTicket, TicketGrantingTicket.class); tgt.getAuthentication().update(authentication); this.centralAuthenticationService.updateTicket(tgt); return tgt; } catch (final PrincipalException e) { LOGGER.error(e.getMessage(), e); throw e; } catch (final Exception e) { LOGGER.error(e.getMessage(), e); throw new InvalidTicketException(ticketGrantingTicket); } } private boolean shouldIssueTicketGrantingTicket(final Authentication authentication, final String ticketGrantingTicket) { if (StringUtils.isBlank(ticketGrantingTicket)) { return true; } LOGGER.debug("Located ticket-granting ticket in the context. Retrieving associated authentication"); val authenticationFromTgt = this.ticketRegistrySupport.getAuthenticationFrom(ticketGrantingTicket); if (authenticationFromTgt == null) { LOGGER.debug("Authentication session associated with [{}] is no longer valid", ticketGrantingTicket); this.centralAuthenticationService.destroyTicketGrantingTicket(ticketGrantingTicket); return true; } if (areAuthenticationsEssentiallyEqual(authentication, authenticationFromTgt)) { LOGGER.debug("Resulting authentication matches the authentication from context"); return false; } LOGGER.debug("Resulting authentication is different from the context"); return true; } private static boolean areAuthenticationsEssentiallyEqual(final Authentication auth1, final Authentication auth2) { if (auth1 == null && auth2 == null) { return false; } if (auth1 == null && auth2 != null) { return false; } if (auth1 != null && auth2 == null) { return false; } val builder = new EqualsBuilder(); builder.append(auth1.getPrincipal(), auth2.getPrincipal()); builder.append(auth1.getCredentials(), auth2.getCredentials()); builder.append(auth1.getSuccesses(), auth2.getSuccesses()); builder.append(auth1.getAttributes(), auth2.getAttributes()); return builder.isEquals(); } }
rrenomeron/cas
support/cas-server-support-actions/src/main/java/org/apereo/cas/web/flow/login/CreateTicketGrantingTicketAction.java
Java
apache-2.0
9,062
/* * Copyright 2010-2015 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.identitymanagement; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.handlers.AsyncHandler; import com.amazonaws.ClientConfiguration; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.services.identitymanagement.model.*; /** * Asynchronous client for accessing AmazonIdentityManagement. * All asynchronous calls made using this client are non-blocking. Callers could either * process the result and handle the exceptions in the worker thread by providing a callback handler * when making the call, or use the returned Future object to check the result of the call in the calling thread. * AWS Identity and Access Management <p> * AWS Identity and Access Management (IAM) is a web service that you can * use to manage users and user permissions under your AWS account. This * guide provides descriptions of IAM actions that you can call * programmatically. For general information about IAM, see * <a href="http://aws.amazon.com/iam/"> AWS Identity and Access Management (IAM) </a> . For the user guide for IAM, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/"> Using IAM </a> * . * </p> * <p> * <b>NOTE:</b>AWS provides SDKs that consist of libraries and sample * code for various programming languages and platforms (Java, Ruby, * .NET, iOS, Android, etc.). The SDKs provide a convenient way to create * programmatic access to IAM and AWS. For example, the SDKs take care of * tasks such as cryptographically signing requests (see below), managing * errors, and retrying requests automatically. For information about the * AWS SDKs, including how to download and install them, see the Tools * for Amazon Web Services page. * </p> * <p> * We recommend that you use the AWS SDKs to make programmatic API calls * to IAM. However, you can also use the IAM Query API to make direct * calls to the IAM web service. To learn more about the IAM Query API, * see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html"> Making Query Requests </a> * in the <i>Using IAM</i> guide. IAM supports GET and POST requests * for all actions. That is, the API does not require you to use GET for * some actions and POST for others. However, GET requests are subject to * the limitation size of a URL. Therefore, for operations that require * larger sizes, use a POST request. * </p> * <p> * <b>Signing Requests</b> * </p> * <p> * Requests must be signed using an access key ID and a secret access * key. We strongly recommend that you do not use your AWS account access * key ID and secret access key for everyday work with IAM. You can use * the access key ID and secret access key for an IAM user or you can use * the AWS Security Token Service to generate temporary security * credentials and use those to sign requests. * </p> * <p> * To sign requests, we recommend that you use * <a href="http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html"> Signature Version 4 </a> * . If you have an existing application that uses Signature Version 2, * you do not have to update it to use Signature Version 4. However, some * operations now require Signature Version 4. The documentation for * operations that require version 4 indicate this requirement. * </p> * <p> * <b>Additional Resources</b> * </p> * <p> * For more information, see the following: * </p> * * <ul> * <li> * <a href="http://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html"> AWS Security Credentials </a> * . This topic provides general information about the types of * credentials used for accessing AWS. </li> * <li> * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/IAMBestPractices.html"> IAM Best Practices </a> * . This topic presents a list of suggestions for using the IAM service * to help secure your AWS resources. </li> * <li> * <a href="http://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html"> Signing AWS API Requests </a> * . This set of topics walk you through the process of signing a * request using an access key ID and secret access key. </li> * * </ul> */ public class AmazonIdentityManagementAsyncClient extends AmazonIdentityManagementClient implements AmazonIdentityManagementAsync { /** * Executor service for executing asynchronous requests. */ private final ExecutorService executorService; private static final int DEFAULT_THREAD_POOL_SIZE = 50; /** * Constructs a new asynchronous client to invoke service methods on * AmazonIdentityManagement. A credentials provider chain will be used * that searches for credentials in this order: * <ul> * <li> Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY </li> * <li> Java System Properties - aws.accessKeyId and aws.secretKey </li> * <li> Instance profile credentials delivered through the Amazon EC2 metadata service </li> * </ul> * * <p> * All service calls made using this new client object are blocking, and will not * return until the service call completes. * * @see DefaultAWSCredentialsProviderChain */ public AmazonIdentityManagementAsyncClient() { this(new DefaultAWSCredentialsProviderChain()); } /** * Constructs a new asynchronous client to invoke service methods on * AmazonIdentityManagement. A credentials provider chain will be used * that searches for credentials in this order: * <ul> * <li> Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY </li> * <li> Java System Properties - aws.accessKeyId and aws.secretKey </li> * <li> Instance profile credentials delivered through the Amazon EC2 metadata service </li> * </ul> * * <p> * All service calls made using this new client object are blocking, and will not * return until the service call completes. * * @param clientConfiguration The client configuration options controlling how this * client connects to AmazonIdentityManagement * (ex: proxy settings, retry counts, etc.). * * @see DefaultAWSCredentialsProviderChain */ public AmazonIdentityManagementAsyncClient(ClientConfiguration clientConfiguration) { this(new DefaultAWSCredentialsProviderChain(), clientConfiguration, Executors.newFixedThreadPool(clientConfiguration.getMaxConnections())); } /** * Constructs a new asynchronous client to invoke service methods on * AmazonIdentityManagement using the specified AWS account credentials. * Default client settings will be used, and a fixed size thread pool will be * created for executing the asynchronous tasks. * * <p> * All calls made using this new client object are non-blocking, and will immediately * return a Java Future object that the caller can later check to see if the service * call has actually completed. * * @param awsCredentials The AWS credentials (access key ID and secret key) to use * when authenticating with AWS services. */ public AmazonIdentityManagementAsyncClient(AWSCredentials awsCredentials) { this(awsCredentials, Executors.newFixedThreadPool(DEFAULT_THREAD_POOL_SIZE)); } /** * Constructs a new asynchronous client to invoke service methods on * AmazonIdentityManagement using the specified AWS account credentials * and executor service. Default client settings will be used. * * <p> * All calls made using this new client object are non-blocking, and will immediately * return a Java Future object that the caller can later check to see if the service * call has actually completed. * * @param awsCredentials * The AWS credentials (access key ID and secret key) to use * when authenticating with AWS services. * @param executorService * The executor service by which all asynchronous requests will * be executed. */ public AmazonIdentityManagementAsyncClient(AWSCredentials awsCredentials, ExecutorService executorService) { super(awsCredentials); this.executorService = executorService; } /** * Constructs a new asynchronous client to invoke service methods on * AmazonIdentityManagement using the specified AWS account credentials, * executor service, and client configuration options. * * <p> * All calls made using this new client object are non-blocking, and will immediately * return a Java Future object that the caller can later check to see if the service * call has actually completed. * * @param awsCredentials * The AWS credentials (access key ID and secret key) to use * when authenticating with AWS services. * @param clientConfiguration * Client configuration options (ex: max retry limit, proxy * settings, etc). * @param executorService * The executor service by which all asynchronous requests will * be executed. */ public AmazonIdentityManagementAsyncClient(AWSCredentials awsCredentials, ClientConfiguration clientConfiguration, ExecutorService executorService) { super(awsCredentials, clientConfiguration); this.executorService = executorService; } /** * Constructs a new asynchronous client to invoke service methods on * AmazonIdentityManagement using the specified AWS account credentials provider. * Default client settings will be used, and a fixed size thread pool will be * created for executing the asynchronous tasks. * * <p> * All calls made using this new client object are non-blocking, and will immediately * return a Java Future object that the caller can later check to see if the service * call has actually completed. * * @param awsCredentialsProvider * The AWS credentials provider which will provide credentials * to authenticate requests with AWS services. */ public AmazonIdentityManagementAsyncClient(AWSCredentialsProvider awsCredentialsProvider) { this(awsCredentialsProvider, Executors.newFixedThreadPool(DEFAULT_THREAD_POOL_SIZE)); } /** * Constructs a new asynchronous client to invoke service methods on * AmazonIdentityManagement using the specified AWS account credentials provider * and executor service. Default client settings will be used. * * <p> * All calls made using this new client object are non-blocking, and will immediately * return a Java Future object that the caller can later check to see if the service * call has actually completed. * * @param awsCredentialsProvider * The AWS credentials provider which will provide credentials * to authenticate requests with AWS services. * @param executorService * The executor service by which all asynchronous requests will * be executed. */ public AmazonIdentityManagementAsyncClient(AWSCredentialsProvider awsCredentialsProvider, ExecutorService executorService) { this(awsCredentialsProvider, new ClientConfiguration(), executorService); } /** * Constructs a new asynchronous client to invoke service methods on * AmazonIdentityManagement using the specified AWS account credentials * provider and client configuration options. * * <p> * All calls made using this new client object are non-blocking, and will immediately * return a Java Future object that the caller can later check to see if the service * call has actually completed. * * @param awsCredentialsProvider * The AWS credentials provider which will provide credentials * to authenticate requests with AWS services. * @param clientConfiguration * Client configuration options (ex: max retry limit, proxy * settings, etc). */ public AmazonIdentityManagementAsyncClient(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration) { this(awsCredentialsProvider, clientConfiguration, Executors.newFixedThreadPool(clientConfiguration.getMaxConnections())); } /** * Constructs a new asynchronous client to invoke service methods on * AmazonIdentityManagement using the specified AWS account credentials * provider, executor service, and client configuration options. * * <p> * All calls made using this new client object are non-blocking, and will immediately * return a Java Future object that the caller can later check to see if the service * call has actually completed. * * @param awsCredentialsProvider * The AWS credentials provider which will provide credentials * to authenticate requests with AWS services. * @param clientConfiguration * Client configuration options (ex: max retry limit, proxy * settings, etc). * @param executorService * The executor service by which all asynchronous requests will * be executed. */ public AmazonIdentityManagementAsyncClient(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration, ExecutorService executorService) { super(awsCredentialsProvider, clientConfiguration); this.executorService = executorService; } /** * Returns the executor service used by this async client to execute * requests. * * @return The executor service used by this async client to execute * requests. */ public ExecutorService getExecutorService() { return executorService; } /** * Shuts down the client, releasing all managed resources. This includes * forcibly terminating all pending asynchronous service calls. Clients who * wish to give pending asynchronous service calls time to complete should * call getExecutorService().shutdown() followed by * getExecutorService().awaitTermination() prior to calling this method. */ @Override public void shutdown() { super.shutdown(); executorService.shutdownNow(); } /** * <p> * Deletes the specified AWS account alias. For information about using * an AWS account alias, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/AccountAlias.html"> Using an Alias for Your AWS Account ID </a> * in the <i>IAM User Guide</i> . * </p> * * @param deleteAccountAliasRequest Container for the necessary * parameters to execute the DeleteAccountAlias operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DeleteAccountAlias service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteAccountAliasAsync(final DeleteAccountAliasRequest deleteAccountAliasRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { deleteAccountAlias(deleteAccountAliasRequest); return null; } }); } /** * <p> * Deletes the specified AWS account alias. For information about using * an AWS account alias, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/AccountAlias.html"> Using an Alias for Your AWS Account ID </a> * in the <i>IAM User Guide</i> . * </p> * * @param deleteAccountAliasRequest Container for the necessary * parameters to execute the DeleteAccountAlias operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DeleteAccountAlias service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteAccountAliasAsync( final DeleteAccountAliasRequest deleteAccountAliasRequest, final AsyncHandler<DeleteAccountAliasRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { deleteAccountAlias(deleteAccountAliasRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(deleteAccountAliasRequest, null); return null; } }); } /** * <p> * Lists the groups that have the specified path prefix. * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listGroupsRequest Container for the necessary parameters to * execute the ListGroups operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListGroups service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListGroupsResult> listGroupsAsync(final ListGroupsRequest listGroupsRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListGroupsResult>() { public ListGroupsResult call() throws Exception { return listGroups(listGroupsRequest); } }); } /** * <p> * Lists the groups that have the specified path prefix. * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listGroupsRequest Container for the necessary parameters to * execute the ListGroups operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListGroups service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListGroupsResult> listGroupsAsync( final ListGroupsRequest listGroupsRequest, final AsyncHandler<ListGroupsRequest, ListGroupsResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListGroupsResult>() { public ListGroupsResult call() throws Exception { ListGroupsResult result; try { result = listGroups(listGroupsRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listGroupsRequest, result); return result; } }); } /** * <p> * Deletes a virtual MFA device. * </p> * <p> * <b>NOTE:</b> You must deactivate a user's virtual MFA device before * you can delete it. For information about deactivating MFA devices, see * DeactivateMFADevice. * </p> * * @param deleteVirtualMFADeviceRequest Container for the necessary * parameters to execute the DeleteVirtualMFADevice operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DeleteVirtualMFADevice service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteVirtualMFADeviceAsync(final DeleteVirtualMFADeviceRequest deleteVirtualMFADeviceRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { deleteVirtualMFADevice(deleteVirtualMFADeviceRequest); return null; } }); } /** * <p> * Deletes a virtual MFA device. * </p> * <p> * <b>NOTE:</b> You must deactivate a user's virtual MFA device before * you can delete it. For information about deactivating MFA devices, see * DeactivateMFADevice. * </p> * * @param deleteVirtualMFADeviceRequest Container for the necessary * parameters to execute the DeleteVirtualMFADevice operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DeleteVirtualMFADevice service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteVirtualMFADeviceAsync( final DeleteVirtualMFADeviceRequest deleteVirtualMFADeviceRequest, final AsyncHandler<DeleteVirtualMFADeviceRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { deleteVirtualMFADevice(deleteVirtualMFADeviceRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(deleteVirtualMFADeviceRequest, null); return null; } }); } /** * <p> * Adds (or updates) an inline policy document that is embedded in the * specified user. * </p> * <p> * A user can also have a managed policy attached to it. To attach a * managed policy to a user, use AttachUserPolicy. To create a new * managed policy, use CreatePolicy. For information about policies, * refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * For information about limits on the number of inline policies that * you can embed in a user, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on IAM Entities </a> * in the <i>IAM User Guide</i> . * </p> * <p> * <b>NOTE:</b>Because policy documents can be large, you should use * POST rather than GET when calling PutUserPolicy. For general * information about using the Query API with IAM, go to Making Query * Requests in the Using IAM guide. * </p> * * @param putUserPolicyRequest Container for the necessary parameters to * execute the PutUserPolicy operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * PutUserPolicy service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> putUserPolicyAsync(final PutUserPolicyRequest putUserPolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { putUserPolicy(putUserPolicyRequest); return null; } }); } /** * <p> * Adds (or updates) an inline policy document that is embedded in the * specified user. * </p> * <p> * A user can also have a managed policy attached to it. To attach a * managed policy to a user, use AttachUserPolicy. To create a new * managed policy, use CreatePolicy. For information about policies, * refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * For information about limits on the number of inline policies that * you can embed in a user, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on IAM Entities </a> * in the <i>IAM User Guide</i> . * </p> * <p> * <b>NOTE:</b>Because policy documents can be large, you should use * POST rather than GET when calling PutUserPolicy. For general * information about using the Query API with IAM, go to Making Query * Requests in the Using IAM guide. * </p> * * @param putUserPolicyRequest Container for the necessary parameters to * execute the PutUserPolicy operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * PutUserPolicy service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> putUserPolicyAsync( final PutUserPolicyRequest putUserPolicyRequest, final AsyncHandler<PutUserPolicyRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { putUserPolicy(putUserPolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(putUserPolicyRequest, null); return null; } }); } /** * <p> * Returns information about the SSH public keys associated with the * specified IAM user. If there are none, the action returns an empty * list. * </p> * <p> * The SSH public keys returned by this action are used only for * authenticating the IAM user to an AWS CodeCommit repository. For more * information about using SSH keys to authenticate to an AWS CodeCommit * repository, see * <a href="http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html"> Set up AWS CodeCommit for SSH Connections </a> * in the <i>AWS CodeCommit User Guide</i> . * </p> * <p> * Although each user is limited to a small number of keys, you can * still paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listSSHPublicKeysRequest Container for the necessary parameters * to execute the ListSSHPublicKeys operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListSSHPublicKeys service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListSSHPublicKeysResult> listSSHPublicKeysAsync(final ListSSHPublicKeysRequest listSSHPublicKeysRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListSSHPublicKeysResult>() { public ListSSHPublicKeysResult call() throws Exception { return listSSHPublicKeys(listSSHPublicKeysRequest); } }); } /** * <p> * Returns information about the SSH public keys associated with the * specified IAM user. If there are none, the action returns an empty * list. * </p> * <p> * The SSH public keys returned by this action are used only for * authenticating the IAM user to an AWS CodeCommit repository. For more * information about using SSH keys to authenticate to an AWS CodeCommit * repository, see * <a href="http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html"> Set up AWS CodeCommit for SSH Connections </a> * in the <i>AWS CodeCommit User Guide</i> . * </p> * <p> * Although each user is limited to a small number of keys, you can * still paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listSSHPublicKeysRequest Container for the necessary parameters * to execute the ListSSHPublicKeys operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListSSHPublicKeys service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListSSHPublicKeysResult> listSSHPublicKeysAsync( final ListSSHPublicKeysRequest listSSHPublicKeysRequest, final AsyncHandler<ListSSHPublicKeysRequest, ListSSHPublicKeysResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListSSHPublicKeysResult>() { public ListSSHPublicKeysResult call() throws Exception { ListSSHPublicKeysResult result; try { result = listSSHPublicKeys(listSSHPublicKeysRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listSSHPublicKeysRequest, result); return result; } }); } /** * <p> * Lists the SAML providers in the account. * </p> * <p> * <b>NOTE:</b> This operation requires Signature Version 4. * </p> * * @param listSAMLProvidersRequest Container for the necessary parameters * to execute the ListSAMLProviders operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListSAMLProviders service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListSAMLProvidersResult> listSAMLProvidersAsync(final ListSAMLProvidersRequest listSAMLProvidersRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListSAMLProvidersResult>() { public ListSAMLProvidersResult call() throws Exception { return listSAMLProviders(listSAMLProvidersRequest); } }); } /** * <p> * Lists the SAML providers in the account. * </p> * <p> * <b>NOTE:</b> This operation requires Signature Version 4. * </p> * * @param listSAMLProvidersRequest Container for the necessary parameters * to execute the ListSAMLProviders operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListSAMLProviders service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListSAMLProvidersResult> listSAMLProvidersAsync( final ListSAMLProvidersRequest listSAMLProvidersRequest, final AsyncHandler<ListSAMLProvidersRequest, ListSAMLProvidersResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListSAMLProvidersResult>() { public ListSAMLProvidersResult call() throws Exception { ListSAMLProvidersResult result; try { result = listSAMLProviders(listSAMLProvidersRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listSAMLProvidersRequest, result); return result; } }); } /** * <p> * Retrieves the specified inline policy document that is embedded in * the specified user. * </p> * <p> * A user can also have managed policies attached to it. To retrieve a * managed policy document that is attached to a user, use GetPolicy to * determine the policy's default version, then use GetPolicyVersion to * retrieve the policy document. * </p> * <p> * For more information about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param getUserPolicyRequest Container for the necessary parameters to * execute the GetUserPolicy operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * GetUserPolicy service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetUserPolicyResult> getUserPolicyAsync(final GetUserPolicyRequest getUserPolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetUserPolicyResult>() { public GetUserPolicyResult call() throws Exception { return getUserPolicy(getUserPolicyRequest); } }); } /** * <p> * Retrieves the specified inline policy document that is embedded in * the specified user. * </p> * <p> * A user can also have managed policies attached to it. To retrieve a * managed policy document that is attached to a user, use GetPolicy to * determine the policy's default version, then use GetPolicyVersion to * retrieve the policy document. * </p> * <p> * For more information about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param getUserPolicyRequest Container for the necessary parameters to * execute the GetUserPolicy operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * GetUserPolicy service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetUserPolicyResult> getUserPolicyAsync( final GetUserPolicyRequest getUserPolicyRequest, final AsyncHandler<GetUserPolicyRequest, GetUserPolicyResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetUserPolicyResult>() { public GetUserPolicyResult call() throws Exception { GetUserPolicyResult result; try { result = getUserPolicy(getUserPolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(getUserPolicyRequest, result); return result; } }); } /** * <p> * Deletes an IAM OpenID Connect identity provider. * </p> * <p> * Deleting an OIDC provider does not update any roles that reference * the provider as a principal in their trust policies. Any attempt to * assume a role that references a provider that has been deleted will * fail. * </p> * <p> * This action is idempotent; it does not fail or return an error if you * call the action for a provider that was already deleted. * </p> * * @param deleteOpenIDConnectProviderRequest Container for the necessary * parameters to execute the DeleteOpenIDConnectProvider operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DeleteOpenIDConnectProvider service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteOpenIDConnectProviderAsync(final DeleteOpenIDConnectProviderRequest deleteOpenIDConnectProviderRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { deleteOpenIDConnectProvider(deleteOpenIDConnectProviderRequest); return null; } }); } /** * <p> * Deletes an IAM OpenID Connect identity provider. * </p> * <p> * Deleting an OIDC provider does not update any roles that reference * the provider as a principal in their trust policies. Any attempt to * assume a role that references a provider that has been deleted will * fail. * </p> * <p> * This action is idempotent; it does not fail or return an error if you * call the action for a provider that was already deleted. * </p> * * @param deleteOpenIDConnectProviderRequest Container for the necessary * parameters to execute the DeleteOpenIDConnectProvider operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DeleteOpenIDConnectProvider service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteOpenIDConnectProviderAsync( final DeleteOpenIDConnectProviderRequest deleteOpenIDConnectProviderRequest, final AsyncHandler<DeleteOpenIDConnectProviderRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { deleteOpenIDConnectProvider(deleteOpenIDConnectProviderRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(deleteOpenIDConnectProviderRequest, null); return null; } }); } /** * <p> * Changes the status of the specified signing certificate from active * to disabled, or vice versa. This action can be used to disable a * user's signing certificate as part of a certificate rotation work * flow. * </p> * <p> * If the <code>UserName</code> field is not specified, the UserName is * determined implicitly based on the AWS access key ID used to sign the * request. Because this action works for access keys under the AWS * account, you can use this action to manage root credentials even if * the AWS account has no associated users. * </p> * * @param updateSigningCertificateRequest Container for the necessary * parameters to execute the UpdateSigningCertificate operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * UpdateSigningCertificate service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> updateSigningCertificateAsync(final UpdateSigningCertificateRequest updateSigningCertificateRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { updateSigningCertificate(updateSigningCertificateRequest); return null; } }); } /** * <p> * Changes the status of the specified signing certificate from active * to disabled, or vice versa. This action can be used to disable a * user's signing certificate as part of a certificate rotation work * flow. * </p> * <p> * If the <code>UserName</code> field is not specified, the UserName is * determined implicitly based on the AWS access key ID used to sign the * request. Because this action works for access keys under the AWS * account, you can use this action to manage root credentials even if * the AWS account has no associated users. * </p> * * @param updateSigningCertificateRequest Container for the necessary * parameters to execute the UpdateSigningCertificate operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * UpdateSigningCertificate service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> updateSigningCertificateAsync( final UpdateSigningCertificateRequest updateSigningCertificateRequest, final AsyncHandler<UpdateSigningCertificateRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { updateSigningCertificate(updateSigningCertificateRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(updateSigningCertificateRequest, null); return null; } }); } /** * <p> * Lists the IAM users that have the specified path prefix. If no path * prefix is specified, the action returns all users in the AWS account. * If there are none, the action returns an empty list. * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listUsersRequest Container for the necessary parameters to * execute the ListUsers operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListUsers service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListUsersResult> listUsersAsync(final ListUsersRequest listUsersRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListUsersResult>() { public ListUsersResult call() throws Exception { return listUsers(listUsersRequest); } }); } /** * <p> * Lists the IAM users that have the specified path prefix. If no path * prefix is specified, the action returns all users in the AWS account. * If there are none, the action returns an empty list. * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listUsersRequest Container for the necessary parameters to * execute the ListUsers operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListUsers service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListUsersResult> listUsersAsync( final ListUsersRequest listUsersRequest, final AsyncHandler<ListUsersRequest, ListUsersResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListUsersResult>() { public ListUsersResult call() throws Exception { ListUsersResult result; try { result = listUsers(listUsersRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listUsersRequest, result); return result; } }); } /** * <p> * Attaches the specified managed policy to the specified role. * </p> * <p> * When you attach a managed policy to a role, the managed policy is * used as the role's access (permissions) policy. You cannot use a * managed policy as the role's trust policy. The role's trust policy is * created at the same time as the role, using CreateRole. You can update * a role's trust policy using UpdateAssumeRolePolicy. * </p> * <p> * Use this API to attach a managed policy to a role. To embed an inline * policy in a role, use PutRolePolicy. For more information about * policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param attachRolePolicyRequest Container for the necessary parameters * to execute the AttachRolePolicy operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * AttachRolePolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> attachRolePolicyAsync(final AttachRolePolicyRequest attachRolePolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { attachRolePolicy(attachRolePolicyRequest); return null; } }); } /** * <p> * Attaches the specified managed policy to the specified role. * </p> * <p> * When you attach a managed policy to a role, the managed policy is * used as the role's access (permissions) policy. You cannot use a * managed policy as the role's trust policy. The role's trust policy is * created at the same time as the role, using CreateRole. You can update * a role's trust policy using UpdateAssumeRolePolicy. * </p> * <p> * Use this API to attach a managed policy to a role. To embed an inline * policy in a role, use PutRolePolicy. For more information about * policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param attachRolePolicyRequest Container for the necessary parameters * to execute the AttachRolePolicy operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * AttachRolePolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> attachRolePolicyAsync( final AttachRolePolicyRequest attachRolePolicyRequest, final AsyncHandler<AttachRolePolicyRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { attachRolePolicy(attachRolePolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(attachRolePolicyRequest, null); return null; } }); } /** * <p> * Gets a list of all of the context keys referenced in * <code>Condition</code> elements in the input policies. The policies * are supplied as a list of one or more strings. To get the context keys * from policies associated with an IAM user, group, or role, use * GetContextKeysForPrincipalPolicy. * </p> * <p> * Context keys are variables maintained by AWS and its services that * provide details about the context of an API query request, and can be * evaluated by using the <code>Condition</code> element of an IAM * policy. Use GetContextKeysForCustomPolicy to understand what key names * and values you must supply when you call SimulateCustomPolicy. Note * that all parameters are shown in unencoded form here for clarity, but * must be URL encoded to be included as a part of a real HTML request. * </p> * * @param getContextKeysForCustomPolicyRequest Container for the * necessary parameters to execute the GetContextKeysForCustomPolicy * operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * GetContextKeysForCustomPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetContextKeysForCustomPolicyResult> getContextKeysForCustomPolicyAsync(final GetContextKeysForCustomPolicyRequest getContextKeysForCustomPolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetContextKeysForCustomPolicyResult>() { public GetContextKeysForCustomPolicyResult call() throws Exception { return getContextKeysForCustomPolicy(getContextKeysForCustomPolicyRequest); } }); } /** * <p> * Gets a list of all of the context keys referenced in * <code>Condition</code> elements in the input policies. The policies * are supplied as a list of one or more strings. To get the context keys * from policies associated with an IAM user, group, or role, use * GetContextKeysForPrincipalPolicy. * </p> * <p> * Context keys are variables maintained by AWS and its services that * provide details about the context of an API query request, and can be * evaluated by using the <code>Condition</code> element of an IAM * policy. Use GetContextKeysForCustomPolicy to understand what key names * and values you must supply when you call SimulateCustomPolicy. Note * that all parameters are shown in unencoded form here for clarity, but * must be URL encoded to be included as a part of a real HTML request. * </p> * * @param getContextKeysForCustomPolicyRequest Container for the * necessary parameters to execute the GetContextKeysForCustomPolicy * operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * GetContextKeysForCustomPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetContextKeysForCustomPolicyResult> getContextKeysForCustomPolicyAsync( final GetContextKeysForCustomPolicyRequest getContextKeysForCustomPolicyRequest, final AsyncHandler<GetContextKeysForCustomPolicyRequest, GetContextKeysForCustomPolicyResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetContextKeysForCustomPolicyResult>() { public GetContextKeysForCustomPolicyResult call() throws Exception { GetContextKeysForCustomPolicyResult result; try { result = getContextKeysForCustomPolicy(getContextKeysForCustomPolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(getContextKeysForCustomPolicyRequest, result); return result; } }); } /** * <p> * Retrieves a credential report for the AWS account. For more * information about the credential report, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/credential-reports.html"> Getting Credential Reports </a> * in the <i>IAM User Guide</i> . * </p> * * @param getCredentialReportRequest Container for the necessary * parameters to execute the GetCredentialReport operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * GetCredentialReport service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetCredentialReportResult> getCredentialReportAsync(final GetCredentialReportRequest getCredentialReportRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetCredentialReportResult>() { public GetCredentialReportResult call() throws Exception { return getCredentialReport(getCredentialReportRequest); } }); } /** * <p> * Retrieves a credential report for the AWS account. For more * information about the credential report, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/credential-reports.html"> Getting Credential Reports </a> * in the <i>IAM User Guide</i> . * </p> * * @param getCredentialReportRequest Container for the necessary * parameters to execute the GetCredentialReport operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * GetCredentialReport service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetCredentialReportResult> getCredentialReportAsync( final GetCredentialReportRequest getCredentialReportRequest, final AsyncHandler<GetCredentialReportRequest, GetCredentialReportResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetCredentialReportResult>() { public GetCredentialReportResult call() throws Exception { GetCredentialReportResult result; try { result = getCredentialReport(getCredentialReportRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(getCredentialReportRequest, result); return result; } }); } /** * <p> * Enables the specified MFA device and associates it with the specified * user name. When enabled, the MFA device is required for every * subsequent login by the user name associated with the device. * </p> * * @param enableMFADeviceRequest Container for the necessary parameters * to execute the EnableMFADevice operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * EnableMFADevice service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> enableMFADeviceAsync(final EnableMFADeviceRequest enableMFADeviceRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { enableMFADevice(enableMFADeviceRequest); return null; } }); } /** * <p> * Enables the specified MFA device and associates it with the specified * user name. When enabled, the MFA device is required for every * subsequent login by the user name associated with the device. * </p> * * @param enableMFADeviceRequest Container for the necessary parameters * to execute the EnableMFADevice operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * EnableMFADevice service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> enableMFADeviceAsync( final EnableMFADeviceRequest enableMFADeviceRequest, final AsyncHandler<EnableMFADeviceRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { enableMFADevice(enableMFADeviceRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(enableMFADeviceRequest, null); return null; } }); } /** * <p> * Deletes the password policy for the AWS account. * </p> * * @param deleteAccountPasswordPolicyRequest Container for the necessary * parameters to execute the DeleteAccountPasswordPolicy operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DeleteAccountPasswordPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteAccountPasswordPolicyAsync(final DeleteAccountPasswordPolicyRequest deleteAccountPasswordPolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { deleteAccountPasswordPolicy(deleteAccountPasswordPolicyRequest); return null; } }); } /** * <p> * Deletes the password policy for the AWS account. * </p> * * @param deleteAccountPasswordPolicyRequest Container for the necessary * parameters to execute the DeleteAccountPasswordPolicy operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DeleteAccountPasswordPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteAccountPasswordPolicyAsync( final DeleteAccountPasswordPolicyRequest deleteAccountPasswordPolicyRequest, final AsyncHandler<DeleteAccountPasswordPolicyRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { deleteAccountPasswordPolicy(deleteAccountPasswordPolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(deleteAccountPasswordPolicyRequest, null); return null; } }); } /** * <p> * Retrieves the user name and password-creation date for the specified * user. If the user has not been assigned a password, the action returns * a 404 ( <code>NoSuchEntity</code> ) error. * </p> * * @param getLoginProfileRequest Container for the necessary parameters * to execute the GetLoginProfile operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * GetLoginProfile service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetLoginProfileResult> getLoginProfileAsync(final GetLoginProfileRequest getLoginProfileRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetLoginProfileResult>() { public GetLoginProfileResult call() throws Exception { return getLoginProfile(getLoginProfileRequest); } }); } /** * <p> * Retrieves the user name and password-creation date for the specified * user. If the user has not been assigned a password, the action returns * a 404 ( <code>NoSuchEntity</code> ) error. * </p> * * @param getLoginProfileRequest Container for the necessary parameters * to execute the GetLoginProfile operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * GetLoginProfile service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetLoginProfileResult> getLoginProfileAsync( final GetLoginProfileRequest getLoginProfileRequest, final AsyncHandler<GetLoginProfileRequest, GetLoginProfileResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetLoginProfileResult>() { public GetLoginProfileResult call() throws Exception { GetLoginProfileResult result; try { result = getLoginProfile(getLoginProfileRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(getLoginProfileRequest, result); return result; } }); } /** * <p> * Updates the metadata document for an existing SAML provider. * </p> * <p> * <b>NOTE:</b>This operation requires Signature Version 4. * </p> * * @param updateSAMLProviderRequest Container for the necessary * parameters to execute the UpdateSAMLProvider operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * UpdateSAMLProvider service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<UpdateSAMLProviderResult> updateSAMLProviderAsync(final UpdateSAMLProviderRequest updateSAMLProviderRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<UpdateSAMLProviderResult>() { public UpdateSAMLProviderResult call() throws Exception { return updateSAMLProvider(updateSAMLProviderRequest); } }); } /** * <p> * Updates the metadata document for an existing SAML provider. * </p> * <p> * <b>NOTE:</b>This operation requires Signature Version 4. * </p> * * @param updateSAMLProviderRequest Container for the necessary * parameters to execute the UpdateSAMLProvider operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * UpdateSAMLProvider service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<UpdateSAMLProviderResult> updateSAMLProviderAsync( final UpdateSAMLProviderRequest updateSAMLProviderRequest, final AsyncHandler<UpdateSAMLProviderRequest, UpdateSAMLProviderResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<UpdateSAMLProviderResult>() { public UpdateSAMLProviderResult call() throws Exception { UpdateSAMLProviderResult result; try { result = updateSAMLProvider(updateSAMLProviderRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(updateSAMLProviderRequest, result); return result; } }); } /** * <p> * Uploads a server certificate entity for the AWS account. The server * certificate entity includes a public key certificate, a private key, * and an optional certificate chain, which should all be PEM-encoded. * </p> * <p> * For information about the number of server certificates you can * upload, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on IAM Entities </a> * in the <i>IAM User Guide</i> . * </p> * <p> * <b>NOTE:</b>Because the body of the public key certificate, private * key, and the certificate chain can be large, you should use POST * rather than GET when calling UploadServerCertificate. For information * about setting up signatures and authorization through the API, go to * Signing AWS API Requests in the AWS General Reference. For general * information about using the Query API with IAM, go to Making Query * Requests in the IAM User Guide. * </p> * * @param uploadServerCertificateRequest Container for the necessary * parameters to execute the UploadServerCertificate operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * UploadServerCertificate service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<UploadServerCertificateResult> uploadServerCertificateAsync(final UploadServerCertificateRequest uploadServerCertificateRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<UploadServerCertificateResult>() { public UploadServerCertificateResult call() throws Exception { return uploadServerCertificate(uploadServerCertificateRequest); } }); } /** * <p> * Uploads a server certificate entity for the AWS account. The server * certificate entity includes a public key certificate, a private key, * and an optional certificate chain, which should all be PEM-encoded. * </p> * <p> * For information about the number of server certificates you can * upload, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on IAM Entities </a> * in the <i>IAM User Guide</i> . * </p> * <p> * <b>NOTE:</b>Because the body of the public key certificate, private * key, and the certificate chain can be large, you should use POST * rather than GET when calling UploadServerCertificate. For information * about setting up signatures and authorization through the API, go to * Signing AWS API Requests in the AWS General Reference. For general * information about using the Query API with IAM, go to Making Query * Requests in the IAM User Guide. * </p> * * @param uploadServerCertificateRequest Container for the necessary * parameters to execute the UploadServerCertificate operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * UploadServerCertificate service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<UploadServerCertificateResult> uploadServerCertificateAsync( final UploadServerCertificateRequest uploadServerCertificateRequest, final AsyncHandler<UploadServerCertificateRequest, UploadServerCertificateResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<UploadServerCertificateResult>() { public UploadServerCertificateResult call() throws Exception { UploadServerCertificateResult result; try { result = uploadServerCertificate(uploadServerCertificateRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(uploadServerCertificateRequest, result); return result; } }); } /** * <p> * Creates an alias for your AWS account. For information about using an * AWS account alias, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/AccountAlias.html"> Using an Alias for Your AWS Account ID </a> * in the <i>IAM User Guide</i> . * </p> * * @param createAccountAliasRequest Container for the necessary * parameters to execute the CreateAccountAlias operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * CreateAccountAlias service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> createAccountAliasAsync(final CreateAccountAliasRequest createAccountAliasRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { createAccountAlias(createAccountAliasRequest); return null; } }); } /** * <p> * Creates an alias for your AWS account. For information about using an * AWS account alias, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/AccountAlias.html"> Using an Alias for Your AWS Account ID </a> * in the <i>IAM User Guide</i> . * </p> * * @param createAccountAliasRequest Container for the necessary * parameters to execute the CreateAccountAlias operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * CreateAccountAlias service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> createAccountAliasAsync( final CreateAccountAliasRequest createAccountAliasRequest, final AsyncHandler<CreateAccountAliasRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { createAccountAlias(createAccountAliasRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(createAccountAliasRequest, null); return null; } }); } /** * <p> * Lists all managed policies that are attached to the specified user. * </p> * <p> * A user can also have inline policies embedded with it. To list the * inline policies for a user, use the ListUserPolicies API. For * information about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. You can use the * <code>PathPrefix</code> parameter to limit the list of policies to * only those matching the specified path prefix. If there are no * policies attached to the specified group (or none that match the * specified path prefix), the action returns an empty list. * </p> * * @param listAttachedUserPoliciesRequest Container for the necessary * parameters to execute the ListAttachedUserPolicies operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListAttachedUserPolicies service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListAttachedUserPoliciesResult> listAttachedUserPoliciesAsync(final ListAttachedUserPoliciesRequest listAttachedUserPoliciesRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListAttachedUserPoliciesResult>() { public ListAttachedUserPoliciesResult call() throws Exception { return listAttachedUserPolicies(listAttachedUserPoliciesRequest); } }); } /** * <p> * Lists all managed policies that are attached to the specified user. * </p> * <p> * A user can also have inline policies embedded with it. To list the * inline policies for a user, use the ListUserPolicies API. For * information about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. You can use the * <code>PathPrefix</code> parameter to limit the list of policies to * only those matching the specified path prefix. If there are no * policies attached to the specified group (or none that match the * specified path prefix), the action returns an empty list. * </p> * * @param listAttachedUserPoliciesRequest Container for the necessary * parameters to execute the ListAttachedUserPolicies operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListAttachedUserPolicies service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListAttachedUserPoliciesResult> listAttachedUserPoliciesAsync( final ListAttachedUserPoliciesRequest listAttachedUserPoliciesRequest, final AsyncHandler<ListAttachedUserPoliciesRequest, ListAttachedUserPoliciesResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListAttachedUserPoliciesResult>() { public ListAttachedUserPoliciesResult call() throws Exception { ListAttachedUserPoliciesResult result; try { result = listAttachedUserPolicies(listAttachedUserPoliciesRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listAttachedUserPoliciesRequest, result); return result; } }); } /** * <p> * Deletes the specified managed policy. * </p> * <p> * Before you can delete a managed policy, you must detach the policy * from all users, groups, and roles that it is attached to, and you must * delete all of the policy's versions. The following steps describe the * process for deleting a managed policy: <ol> <li>Detach the policy from * all users, groups, and roles that the policy is attached to, using the * DetachUserPolicy, DetachGroupPolicy, or DetachRolePolicy APIs. To list * all the users, groups, and roles that a policy is attached to, use * ListEntitiesForPolicy. </li> * <li>Delete all versions of the policy using DeletePolicyVersion. To * list the policy's versions, use ListPolicyVersions. You cannot use * DeletePolicyVersion to delete the version that is marked as the * default version. You delete the policy's default version in the next * step of the process. </li> * <li>Delete the policy (this automatically deletes the policy's * default version) using this API. </li> * </ol> * </p> * <p> * For information about managed policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param deletePolicyRequest Container for the necessary parameters to * execute the DeletePolicy operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DeletePolicy service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deletePolicyAsync(final DeletePolicyRequest deletePolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { deletePolicy(deletePolicyRequest); return null; } }); } /** * <p> * Deletes the specified managed policy. * </p> * <p> * Before you can delete a managed policy, you must detach the policy * from all users, groups, and roles that it is attached to, and you must * delete all of the policy's versions. The following steps describe the * process for deleting a managed policy: <ol> <li>Detach the policy from * all users, groups, and roles that the policy is attached to, using the * DetachUserPolicy, DetachGroupPolicy, or DetachRolePolicy APIs. To list * all the users, groups, and roles that a policy is attached to, use * ListEntitiesForPolicy. </li> * <li>Delete all versions of the policy using DeletePolicyVersion. To * list the policy's versions, use ListPolicyVersions. You cannot use * DeletePolicyVersion to delete the version that is marked as the * default version. You delete the policy's default version in the next * step of the process. </li> * <li>Delete the policy (this automatically deletes the policy's * default version) using this API. </li> * </ol> * </p> * <p> * For information about managed policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param deletePolicyRequest Container for the necessary parameters to * execute the DeletePolicy operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DeletePolicy service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deletePolicyAsync( final DeletePolicyRequest deletePolicyRequest, final AsyncHandler<DeletePolicyRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { deletePolicy(deletePolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(deletePolicyRequest, null); return null; } }); } /** * <p> * Simulate how a set of IAM policies and optionally a resource-based * policy works with a list of API actions and AWS resources to determine * the policies' effective permissions. The policies are provided as * strings. * </p> * <p> * The simulation does not perform the API actions; it only checks the * authorization to determine if the simulated policies allow or deny the * actions. * </p> * <p> * If you want to simulate existing policies attached to an IAM user, * group, or role, use SimulatePrincipalPolicy instead. * </p> * <p> * Context keys are variables maintained by AWS and its services that * provide details about the context of an API query request. You can use * the <code>Condition</code> element of an IAM policy to evaluate * context keys. To get the list of context keys that the policies * require for correct simulation, use GetContextKeysForCustomPolicy. * </p> * <p> * If the output is long, you can use <code>MaxItems</code> and * <code>Marker</code> parameters to paginate the results. * </p> * Example This example specifies a policy by string and supplies a * ContextEntry to use for the context key that the policy references. * Note that all parameters are shown in unencoded form here for clarity * but must be URL encoded to be included as a part of a real HTML * request. The results show that the policy allows s3:ListBucket access * to the S3 bucket named teambucket. * https://iam.amazonaws.com/Action=SimulateCustomPolicy * &ActionNames.member.1=s3:ListBucket * &ResourceArns.member.1=arn:aws:s3:::teambucket * &ContextEntries.member.1.ContextKeyName=aws:MultiFactorAuthPresent * &ContextEntries.member.1.ContextKeyType=boolean * &ContextEntries.member.1.ContextKeyValues.member.1=true * &PolicyInputList.member.1={' "Version":"2012-10-17", "Statement":{ * "Effect":"Allow", "Action":"s3:ListBucket", * "Resource":"arn:aws:s3:::teambucket", * "Condition":{"Bool":{"aws:MultiFactorAuthPresent":"true"}} } } * &Version=2010-05-08 &AUTHPARAMS <SimulateCustomPolicyResponse * xmlns="https://iam.amazonaws.com/doc/2010-05-08/"> * <SimulateCustomPolicyResult> <IsTruncated>false</IsTruncated> * <EvaluationResults> <member> <MatchedStatements> <member> * <SourcePolicyId>PolicyInputList.1</SourcePolicyId> <EndPosition> * <Column>4</Column> <Line>8</Line> </EndPosition> <StartPosition> * <Column>16</Column> <Line>3</Line> </StartPosition> </member> * </MatchedStatements> <MissingContextValues/> * <EvalResourceName>arn:aws:s3:::teambucket</EvalResourceName> * <EvalDecision>allowed</EvalDecision> * <EvalActionName>s3:ListBucket</EvalActionName> </member> * </EvaluationResults> </SimulateCustomPolicyResult> <ResponseMetadata> * <RequestId>1cdb5b0a-4c15-11e5-b121-bd8c7EXAMPLE</RequestId> * </ResponseMetadata> </SimulateCustomPolicyResponse> * * @param simulateCustomPolicyRequest Container for the necessary * parameters to execute the SimulateCustomPolicy operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * SimulateCustomPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<SimulateCustomPolicyResult> simulateCustomPolicyAsync(final SimulateCustomPolicyRequest simulateCustomPolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<SimulateCustomPolicyResult>() { public SimulateCustomPolicyResult call() throws Exception { return simulateCustomPolicy(simulateCustomPolicyRequest); } }); } /** * <p> * Simulate how a set of IAM policies and optionally a resource-based * policy works with a list of API actions and AWS resources to determine * the policies' effective permissions. The policies are provided as * strings. * </p> * <p> * The simulation does not perform the API actions; it only checks the * authorization to determine if the simulated policies allow or deny the * actions. * </p> * <p> * If you want to simulate existing policies attached to an IAM user, * group, or role, use SimulatePrincipalPolicy instead. * </p> * <p> * Context keys are variables maintained by AWS and its services that * provide details about the context of an API query request. You can use * the <code>Condition</code> element of an IAM policy to evaluate * context keys. To get the list of context keys that the policies * require for correct simulation, use GetContextKeysForCustomPolicy. * </p> * <p> * If the output is long, you can use <code>MaxItems</code> and * <code>Marker</code> parameters to paginate the results. * </p> * Example This example specifies a policy by string and supplies a * ContextEntry to use for the context key that the policy references. * Note that all parameters are shown in unencoded form here for clarity * but must be URL encoded to be included as a part of a real HTML * request. The results show that the policy allows s3:ListBucket access * to the S3 bucket named teambucket. * https://iam.amazonaws.com/Action=SimulateCustomPolicy * &ActionNames.member.1=s3:ListBucket * &ResourceArns.member.1=arn:aws:s3:::teambucket * &ContextEntries.member.1.ContextKeyName=aws:MultiFactorAuthPresent * &ContextEntries.member.1.ContextKeyType=boolean * &ContextEntries.member.1.ContextKeyValues.member.1=true * &PolicyInputList.member.1={' "Version":"2012-10-17", "Statement":{ * "Effect":"Allow", "Action":"s3:ListBucket", * "Resource":"arn:aws:s3:::teambucket", * "Condition":{"Bool":{"aws:MultiFactorAuthPresent":"true"}} } } * &Version=2010-05-08 &AUTHPARAMS <SimulateCustomPolicyResponse * xmlns="https://iam.amazonaws.com/doc/2010-05-08/"> * <SimulateCustomPolicyResult> <IsTruncated>false</IsTruncated> * <EvaluationResults> <member> <MatchedStatements> <member> * <SourcePolicyId>PolicyInputList.1</SourcePolicyId> <EndPosition> * <Column>4</Column> <Line>8</Line> </EndPosition> <StartPosition> * <Column>16</Column> <Line>3</Line> </StartPosition> </member> * </MatchedStatements> <MissingContextValues/> * <EvalResourceName>arn:aws:s3:::teambucket</EvalResourceName> * <EvalDecision>allowed</EvalDecision> * <EvalActionName>s3:ListBucket</EvalActionName> </member> * </EvaluationResults> </SimulateCustomPolicyResult> <ResponseMetadata> * <RequestId>1cdb5b0a-4c15-11e5-b121-bd8c7EXAMPLE</RequestId> * </ResponseMetadata> </SimulateCustomPolicyResponse> * * @param simulateCustomPolicyRequest Container for the necessary * parameters to execute the SimulateCustomPolicy operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * SimulateCustomPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<SimulateCustomPolicyResult> simulateCustomPolicyAsync( final SimulateCustomPolicyRequest simulateCustomPolicyRequest, final AsyncHandler<SimulateCustomPolicyRequest, SimulateCustomPolicyResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<SimulateCustomPolicyResult>() { public SimulateCustomPolicyResult call() throws Exception { SimulateCustomPolicyResult result; try { result = simulateCustomPolicy(simulateCustomPolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(simulateCustomPolicyRequest, result); return result; } }); } /** * <p> * Deletes the specified role. The role must not have any policies * attached. For more information about roles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html"> Working with Roles </a> * . * </p> * <p> * <b>IMPORTANT:</b>Make sure you do not have any Amazon EC2 instances * running with the role you are about to delete. Deleting a role or * instance profile that is associated with a running instance will break * any applications running on the instance. * </p> * * @param deleteRoleRequest Container for the necessary parameters to * execute the DeleteRole operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DeleteRole service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteRoleAsync(final DeleteRoleRequest deleteRoleRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { deleteRole(deleteRoleRequest); return null; } }); } /** * <p> * Deletes the specified role. The role must not have any policies * attached. For more information about roles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html"> Working with Roles </a> * . * </p> * <p> * <b>IMPORTANT:</b>Make sure you do not have any Amazon EC2 instances * running with the role you are about to delete. Deleting a role or * instance profile that is associated with a running instance will break * any applications running on the instance. * </p> * * @param deleteRoleRequest Container for the necessary parameters to * execute the DeleteRole operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DeleteRole service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteRoleAsync( final DeleteRoleRequest deleteRoleRequest, final AsyncHandler<DeleteRoleRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { deleteRole(deleteRoleRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(deleteRoleRequest, null); return null; } }); } /** * <p> * Creates a new AWS secret access key and corresponding AWS access key * ID for the specified user. The default status for new keys is * <code>Active</code> . * </p> * <p> * If you do not specify a user name, IAM determines the user name * implicitly based on the AWS access key ID signing the request. Because * this action works for access keys under the AWS account, you can use * this action to manage root credentials even if the AWS account has no * associated users. * </p> * <p> * For information about limits on the number of keys you can create, * see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on IAM Entities </a> * in the <i>IAM User Guide</i> . * </p> * <p> * <b>IMPORTANT:</b> To ensure the security of your AWS account, the * secret access key is accessible only during key and user creation. You * must save the key (for example, in a text file) if you want to be able * to access it again. If a secret key is lost, you can delete the access * keys for the associated user and then create new keys. * </p> * * @param createAccessKeyRequest Container for the necessary parameters * to execute the CreateAccessKey operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * CreateAccessKey service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreateAccessKeyResult> createAccessKeyAsync(final CreateAccessKeyRequest createAccessKeyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreateAccessKeyResult>() { public CreateAccessKeyResult call() throws Exception { return createAccessKey(createAccessKeyRequest); } }); } /** * <p> * Creates a new AWS secret access key and corresponding AWS access key * ID for the specified user. The default status for new keys is * <code>Active</code> . * </p> * <p> * If you do not specify a user name, IAM determines the user name * implicitly based on the AWS access key ID signing the request. Because * this action works for access keys under the AWS account, you can use * this action to manage root credentials even if the AWS account has no * associated users. * </p> * <p> * For information about limits on the number of keys you can create, * see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on IAM Entities </a> * in the <i>IAM User Guide</i> . * </p> * <p> * <b>IMPORTANT:</b> To ensure the security of your AWS account, the * secret access key is accessible only during key and user creation. You * must save the key (for example, in a text file) if you want to be able * to access it again. If a secret key is lost, you can delete the access * keys for the associated user and then create new keys. * </p> * * @param createAccessKeyRequest Container for the necessary parameters * to execute the CreateAccessKey operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * CreateAccessKey service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreateAccessKeyResult> createAccessKeyAsync( final CreateAccessKeyRequest createAccessKeyRequest, final AsyncHandler<CreateAccessKeyRequest, CreateAccessKeyResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreateAccessKeyResult>() { public CreateAccessKeyResult call() throws Exception { CreateAccessKeyResult result; try { result = createAccessKey(createAccessKeyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(createAccessKeyRequest, result); return result; } }); } /** * <p> * Retrieves information about the specified user, including the user's * creation date, path, unique ID, and ARN. * </p> * <p> * If you do not specify a user name, IAM determines the user name * implicitly based on the AWS access key ID used to sign the request. * </p> * * @param getUserRequest Container for the necessary parameters to * execute the GetUser operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the GetUser * service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetUserResult> getUserAsync(final GetUserRequest getUserRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetUserResult>() { public GetUserResult call() throws Exception { return getUser(getUserRequest); } }); } /** * <p> * Retrieves information about the specified user, including the user's * creation date, path, unique ID, and ARN. * </p> * <p> * If you do not specify a user name, IAM determines the user name * implicitly based on the AWS access key ID used to sign the request. * </p> * * @param getUserRequest Container for the necessary parameters to * execute the GetUser operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the GetUser * service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetUserResult> getUserAsync( final GetUserRequest getUserRequest, final AsyncHandler<GetUserRequest, GetUserResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetUserResult>() { public GetUserResult call() throws Exception { GetUserResult result; try { result = getUser(getUserRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(getUserRequest, result); return result; } }); } /** * <p> * Lists all managed policies that are attached to the specified group. * </p> * <p> * A group can also have inline policies embedded with it. To list the * inline policies for a group, use the ListGroupPolicies API. For * information about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. You can use the * <code>PathPrefix</code> parameter to limit the list of policies to * only those matching the specified path prefix. If there are no * policies attached to the specified group (or none that match the * specified path prefix), the action returns an empty list. * </p> * * @param listAttachedGroupPoliciesRequest Container for the necessary * parameters to execute the ListAttachedGroupPolicies operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListAttachedGroupPolicies service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListAttachedGroupPoliciesResult> listAttachedGroupPoliciesAsync(final ListAttachedGroupPoliciesRequest listAttachedGroupPoliciesRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListAttachedGroupPoliciesResult>() { public ListAttachedGroupPoliciesResult call() throws Exception { return listAttachedGroupPolicies(listAttachedGroupPoliciesRequest); } }); } /** * <p> * Lists all managed policies that are attached to the specified group. * </p> * <p> * A group can also have inline policies embedded with it. To list the * inline policies for a group, use the ListGroupPolicies API. For * information about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. You can use the * <code>PathPrefix</code> parameter to limit the list of policies to * only those matching the specified path prefix. If there are no * policies attached to the specified group (or none that match the * specified path prefix), the action returns an empty list. * </p> * * @param listAttachedGroupPoliciesRequest Container for the necessary * parameters to execute the ListAttachedGroupPolicies operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListAttachedGroupPolicies service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListAttachedGroupPoliciesResult> listAttachedGroupPoliciesAsync( final ListAttachedGroupPoliciesRequest listAttachedGroupPoliciesRequest, final AsyncHandler<ListAttachedGroupPoliciesRequest, ListAttachedGroupPoliciesResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListAttachedGroupPoliciesResult>() { public ListAttachedGroupPoliciesResult call() throws Exception { ListAttachedGroupPoliciesResult result; try { result = listAttachedGroupPolicies(listAttachedGroupPoliciesRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listAttachedGroupPoliciesRequest, result); return result; } }); } /** * <p> * Synchronizes the specified MFA device with AWS servers. * </p> * <p> * For more information about creating and working with virtual MFA * devices, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_VirtualMFA.html"> Using a Virtual MFA Device </a> * in the <i>Using IAM</i> guide. * </p> * * @param resyncMFADeviceRequest Container for the necessary parameters * to execute the ResyncMFADevice operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ResyncMFADevice service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> resyncMFADeviceAsync(final ResyncMFADeviceRequest resyncMFADeviceRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { resyncMFADevice(resyncMFADeviceRequest); return null; } }); } /** * <p> * Synchronizes the specified MFA device with AWS servers. * </p> * <p> * For more information about creating and working with virtual MFA * devices, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_VirtualMFA.html"> Using a Virtual MFA Device </a> * in the <i>Using IAM</i> guide. * </p> * * @param resyncMFADeviceRequest Container for the necessary parameters * to execute the ResyncMFADevice operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ResyncMFADevice service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> resyncMFADeviceAsync( final ResyncMFADeviceRequest resyncMFADeviceRequest, final AsyncHandler<ResyncMFADeviceRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { resyncMFADevice(resyncMFADeviceRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(resyncMFADeviceRequest, null); return null; } }); } /** * <p> * Lists the MFA devices. If the request includes the user name, then * this action lists all the MFA devices associated with the specified * user name. If you do not specify a user name, IAM determines the user * name implicitly based on the AWS access key ID signing the request. * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listMFADevicesRequest Container for the necessary parameters to * execute the ListMFADevices operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListMFADevices service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListMFADevicesResult> listMFADevicesAsync(final ListMFADevicesRequest listMFADevicesRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListMFADevicesResult>() { public ListMFADevicesResult call() throws Exception { return listMFADevices(listMFADevicesRequest); } }); } /** * <p> * Lists the MFA devices. If the request includes the user name, then * this action lists all the MFA devices associated with the specified * user name. If you do not specify a user name, IAM determines the user * name implicitly based on the AWS access key ID signing the request. * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listMFADevicesRequest Container for the necessary parameters to * execute the ListMFADevices operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListMFADevices service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListMFADevicesResult> listMFADevicesAsync( final ListMFADevicesRequest listMFADevicesRequest, final AsyncHandler<ListMFADevicesRequest, ListMFADevicesResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListMFADevicesResult>() { public ListMFADevicesResult call() throws Exception { ListMFADevicesResult result; try { result = listMFADevices(listMFADevicesRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listMFADevicesRequest, result); return result; } }); } /** * <p> * Creates a new virtual MFA device for the AWS account. After creating * the virtual MFA, use EnableMFADevice to attach the MFA device to an * IAM user. For more information about creating and working with virtual * MFA devices, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_VirtualMFA.html"> Using a Virtual MFA Device </a> * in the <i>Using IAM</i> guide. * </p> * <p> * For information about limits on the number of MFA devices you can * create, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on Entities </a> * in the <i>Using IAM</i> guide. * </p> * <p> * <b>IMPORTANT:</b>The seed information contained in the QR code and * the Base32 string should be treated like any other secret access * information, such as your AWS access keys or your passwords. After you * provision your virtual device, you should ensure that the information * is destroyed following secure procedures. * </p> * * @param createVirtualMFADeviceRequest Container for the necessary * parameters to execute the CreateVirtualMFADevice operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * CreateVirtualMFADevice service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreateVirtualMFADeviceResult> createVirtualMFADeviceAsync(final CreateVirtualMFADeviceRequest createVirtualMFADeviceRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreateVirtualMFADeviceResult>() { public CreateVirtualMFADeviceResult call() throws Exception { return createVirtualMFADevice(createVirtualMFADeviceRequest); } }); } /** * <p> * Creates a new virtual MFA device for the AWS account. After creating * the virtual MFA, use EnableMFADevice to attach the MFA device to an * IAM user. For more information about creating and working with virtual * MFA devices, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_VirtualMFA.html"> Using a Virtual MFA Device </a> * in the <i>Using IAM</i> guide. * </p> * <p> * For information about limits on the number of MFA devices you can * create, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on Entities </a> * in the <i>Using IAM</i> guide. * </p> * <p> * <b>IMPORTANT:</b>The seed information contained in the QR code and * the Base32 string should be treated like any other secret access * information, such as your AWS access keys or your passwords. After you * provision your virtual device, you should ensure that the information * is destroyed following secure procedures. * </p> * * @param createVirtualMFADeviceRequest Container for the necessary * parameters to execute the CreateVirtualMFADevice operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * CreateVirtualMFADevice service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreateVirtualMFADeviceResult> createVirtualMFADeviceAsync( final CreateVirtualMFADeviceRequest createVirtualMFADeviceRequest, final AsyncHandler<CreateVirtualMFADeviceRequest, CreateVirtualMFADeviceResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreateVirtualMFADeviceResult>() { public CreateVirtualMFADeviceResult call() throws Exception { CreateVirtualMFADeviceResult result; try { result = createVirtualMFADevice(createVirtualMFADeviceRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(createVirtualMFADeviceRequest, result); return result; } }); } /** * <p> * Deletes the specified version of the specified managed policy. * </p> * <p> * You cannot delete the default version of a policy using this API. To * delete the default version of a policy, use DeletePolicy. To find out * which version of a policy is marked as the default version, use * ListPolicyVersions. * </p> * <p> * For information about versions for managed policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html"> Versioning for Managed Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param deletePolicyVersionRequest Container for the necessary * parameters to execute the DeletePolicyVersion operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DeletePolicyVersion service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deletePolicyVersionAsync(final DeletePolicyVersionRequest deletePolicyVersionRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { deletePolicyVersion(deletePolicyVersionRequest); return null; } }); } /** * <p> * Deletes the specified version of the specified managed policy. * </p> * <p> * You cannot delete the default version of a policy using this API. To * delete the default version of a policy, use DeletePolicy. To find out * which version of a policy is marked as the default version, use * ListPolicyVersions. * </p> * <p> * For information about versions for managed policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html"> Versioning for Managed Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param deletePolicyVersionRequest Container for the necessary * parameters to execute the DeletePolicyVersion operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DeletePolicyVersion service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deletePolicyVersionAsync( final DeletePolicyVersionRequest deletePolicyVersionRequest, final AsyncHandler<DeletePolicyVersionRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { deletePolicyVersion(deletePolicyVersionRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(deletePolicyVersionRequest, null); return null; } }); } /** * <p> * Lists the account aliases associated with the account. For * information about using an AWS account alias, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/AccountAlias.html"> Using an Alias for Your AWS Account ID </a> * in the <i>IAM User Guide</i> . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listAccountAliasesRequest Container for the necessary * parameters to execute the ListAccountAliases operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListAccountAliases service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListAccountAliasesResult> listAccountAliasesAsync(final ListAccountAliasesRequest listAccountAliasesRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListAccountAliasesResult>() { public ListAccountAliasesResult call() throws Exception { return listAccountAliases(listAccountAliasesRequest); } }); } /** * <p> * Lists the account aliases associated with the account. For * information about using an AWS account alias, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/AccountAlias.html"> Using an Alias for Your AWS Account ID </a> * in the <i>IAM User Guide</i> . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listAccountAliasesRequest Container for the necessary * parameters to execute the ListAccountAliases operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListAccountAliases service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListAccountAliasesResult> listAccountAliasesAsync( final ListAccountAliasesRequest listAccountAliasesRequest, final AsyncHandler<ListAccountAliasesRequest, ListAccountAliasesResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListAccountAliasesResult>() { public ListAccountAliasesResult call() throws Exception { ListAccountAliasesResult result; try { result = listAccountAliases(listAccountAliasesRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listAccountAliasesRequest, result); return result; } }); } /** * <p> * Creates an IAM entity to describe an identity provider (IdP) that * supports * <a href="http://openid.net/connect/"> OpenID Connect (OIDC) </a> * . * </p> * <p> * The OIDC provider that you create with this operation can be used as * a principal in a role's trust policy to establish a trust relationship * between AWS and the OIDC provider. * </p> * <p> * When you create the IAM OIDC provider, you specify the URL of the * OIDC identity provider (IdP) to trust, a list of client IDs (also * known as audiences) that identify the application or applications that * are allowed to authenticate using the OIDC provider, and a list of * thumbprints of the server certificate(s) that the IdP uses. You get * all of this information from the OIDC IdP that you want to use for * access to AWS. * </p> * <p> * <b>NOTE:</b>Because trust for the OIDC provider is ultimately derived * from the IAM provider that this action creates, it is a best practice * to limit access to the CreateOpenIDConnectProvider action to * highly-privileged users. * </p> * * @param createOpenIDConnectProviderRequest Container for the necessary * parameters to execute the CreateOpenIDConnectProvider operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * CreateOpenIDConnectProvider service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreateOpenIDConnectProviderResult> createOpenIDConnectProviderAsync(final CreateOpenIDConnectProviderRequest createOpenIDConnectProviderRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreateOpenIDConnectProviderResult>() { public CreateOpenIDConnectProviderResult call() throws Exception { return createOpenIDConnectProvider(createOpenIDConnectProviderRequest); } }); } /** * <p> * Creates an IAM entity to describe an identity provider (IdP) that * supports * <a href="http://openid.net/connect/"> OpenID Connect (OIDC) </a> * . * </p> * <p> * The OIDC provider that you create with this operation can be used as * a principal in a role's trust policy to establish a trust relationship * between AWS and the OIDC provider. * </p> * <p> * When you create the IAM OIDC provider, you specify the URL of the * OIDC identity provider (IdP) to trust, a list of client IDs (also * known as audiences) that identify the application or applications that * are allowed to authenticate using the OIDC provider, and a list of * thumbprints of the server certificate(s) that the IdP uses. You get * all of this information from the OIDC IdP that you want to use for * access to AWS. * </p> * <p> * <b>NOTE:</b>Because trust for the OIDC provider is ultimately derived * from the IAM provider that this action creates, it is a best practice * to limit access to the CreateOpenIDConnectProvider action to * highly-privileged users. * </p> * * @param createOpenIDConnectProviderRequest Container for the necessary * parameters to execute the CreateOpenIDConnectProvider operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * CreateOpenIDConnectProvider service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreateOpenIDConnectProviderResult> createOpenIDConnectProviderAsync( final CreateOpenIDConnectProviderRequest createOpenIDConnectProviderRequest, final AsyncHandler<CreateOpenIDConnectProviderRequest, CreateOpenIDConnectProviderResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreateOpenIDConnectProviderResult>() { public CreateOpenIDConnectProviderResult call() throws Exception { CreateOpenIDConnectProviderResult result; try { result = createOpenIDConnectProvider(createOpenIDConnectProviderRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(createOpenIDConnectProviderRequest, result); return result; } }); } /** * <p> * Retrieves information about the specified role, including the role's * path, GUID, ARN, and the policy granting permission to assume the * role. For more information about ARNs, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html#Identifiers_ARNs"> ARNs </a> . For more information about roles, go to <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html"> Working with Roles </a> * . * </p> * * @param getRoleRequest Container for the necessary parameters to * execute the GetRole operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the GetRole * service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetRoleResult> getRoleAsync(final GetRoleRequest getRoleRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetRoleResult>() { public GetRoleResult call() throws Exception { return getRole(getRoleRequest); } }); } /** * <p> * Retrieves information about the specified role, including the role's * path, GUID, ARN, and the policy granting permission to assume the * role. For more information about ARNs, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html#Identifiers_ARNs"> ARNs </a> . For more information about roles, go to <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html"> Working with Roles </a> * . * </p> * * @param getRoleRequest Container for the necessary parameters to * execute the GetRole operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the GetRole * service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetRoleResult> getRoleAsync( final GetRoleRequest getRoleRequest, final AsyncHandler<GetRoleRequest, GetRoleResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetRoleResult>() { public GetRoleResult call() throws Exception { GetRoleResult result; try { result = getRole(getRoleRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(getRoleRequest, result); return result; } }); } /** * <p> * Lists the names of the inline policies that are embedded in the * specified role. * </p> * <p> * A role can also have managed policies attached to it. To list the * managed policies that are attached to a role, use * ListAttachedRolePolicies. For more information about policies, refer * to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. If there are no inline policies * embedded with the specified role, the action returns an empty list. * </p> * * @param listRolePoliciesRequest Container for the necessary parameters * to execute the ListRolePolicies operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListRolePolicies service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListRolePoliciesResult> listRolePoliciesAsync(final ListRolePoliciesRequest listRolePoliciesRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListRolePoliciesResult>() { public ListRolePoliciesResult call() throws Exception { return listRolePolicies(listRolePoliciesRequest); } }); } /** * <p> * Lists the names of the inline policies that are embedded in the * specified role. * </p> * <p> * A role can also have managed policies attached to it. To list the * managed policies that are attached to a role, use * ListAttachedRolePolicies. For more information about policies, refer * to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. If there are no inline policies * embedded with the specified role, the action returns an empty list. * </p> * * @param listRolePoliciesRequest Container for the necessary parameters * to execute the ListRolePolicies operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListRolePolicies service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListRolePoliciesResult> listRolePoliciesAsync( final ListRolePoliciesRequest listRolePoliciesRequest, final AsyncHandler<ListRolePoliciesRequest, ListRolePoliciesResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListRolePoliciesResult>() { public ListRolePoliciesResult call() throws Exception { ListRolePoliciesResult result; try { result = listRolePolicies(listRolePoliciesRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listRolePoliciesRequest, result); return result; } }); } /** * <p> * Returns information about the signing certificates associated with * the specified user. If there are none, the action returns an empty * list. * </p> * <p> * Although each user is limited to a small number of signing * certificates, you can still paginate the results using the * <code>MaxItems</code> and <code>Marker</code> parameters. * </p> * <p> * If the <code>UserName</code> field is not specified, the user name is * determined implicitly based on the AWS access key ID used to sign the * request. Because this action works for access keys under the AWS * account, you can use this action to manage root credentials even if * the AWS account has no associated users. * </p> * * @param listSigningCertificatesRequest Container for the necessary * parameters to execute the ListSigningCertificates operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListSigningCertificates service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListSigningCertificatesResult> listSigningCertificatesAsync(final ListSigningCertificatesRequest listSigningCertificatesRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListSigningCertificatesResult>() { public ListSigningCertificatesResult call() throws Exception { return listSigningCertificates(listSigningCertificatesRequest); } }); } /** * <p> * Returns information about the signing certificates associated with * the specified user. If there are none, the action returns an empty * list. * </p> * <p> * Although each user is limited to a small number of signing * certificates, you can still paginate the results using the * <code>MaxItems</code> and <code>Marker</code> parameters. * </p> * <p> * If the <code>UserName</code> field is not specified, the user name is * determined implicitly based on the AWS access key ID used to sign the * request. Because this action works for access keys under the AWS * account, you can use this action to manage root credentials even if * the AWS account has no associated users. * </p> * * @param listSigningCertificatesRequest Container for the necessary * parameters to execute the ListSigningCertificates operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListSigningCertificates service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListSigningCertificatesResult> listSigningCertificatesAsync( final ListSigningCertificatesRequest listSigningCertificatesRequest, final AsyncHandler<ListSigningCertificatesRequest, ListSigningCertificatesResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListSigningCertificatesResult>() { public ListSigningCertificatesResult call() throws Exception { ListSigningCertificatesResult result; try { result = listSigningCertificates(listSigningCertificatesRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listSigningCertificatesRequest, result); return result; } }); } /** * <p> * Uploads an X.509 signing certificate and associates it with the * specified user. Some AWS services use X.509 signing certificates to * validate requests that are signed with a corresponding private key. * When you upload the certificate, its default status is * <code>Active</code> . * </p> * <p> * If the <code>UserName</code> field is not specified, the user name is * determined implicitly based on the AWS access key ID used to sign the * request. Because this action works for access keys under the AWS * account, you can use this action to manage root credentials even if * the AWS account has no associated users. * </p> * <p> * <b>NOTE:</b>Because the body of a X.509 certificate can be large, you * should use POST rather than GET when calling UploadSigningCertificate. * For information about setting up signatures and authorization through * the API, go to Signing AWS API Requests in the AWS General Reference. * For general information about using the Query API with IAM, go to * Making Query Requests in the Using IAMguide. * </p> * * @param uploadSigningCertificateRequest Container for the necessary * parameters to execute the UploadSigningCertificate operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * UploadSigningCertificate service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<UploadSigningCertificateResult> uploadSigningCertificateAsync(final UploadSigningCertificateRequest uploadSigningCertificateRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<UploadSigningCertificateResult>() { public UploadSigningCertificateResult call() throws Exception { return uploadSigningCertificate(uploadSigningCertificateRequest); } }); } /** * <p> * Uploads an X.509 signing certificate and associates it with the * specified user. Some AWS services use X.509 signing certificates to * validate requests that are signed with a corresponding private key. * When you upload the certificate, its default status is * <code>Active</code> . * </p> * <p> * If the <code>UserName</code> field is not specified, the user name is * determined implicitly based on the AWS access key ID used to sign the * request. Because this action works for access keys under the AWS * account, you can use this action to manage root credentials even if * the AWS account has no associated users. * </p> * <p> * <b>NOTE:</b>Because the body of a X.509 certificate can be large, you * should use POST rather than GET when calling UploadSigningCertificate. * For information about setting up signatures and authorization through * the API, go to Signing AWS API Requests in the AWS General Reference. * For general information about using the Query API with IAM, go to * Making Query Requests in the Using IAMguide. * </p> * * @param uploadSigningCertificateRequest Container for the necessary * parameters to execute the UploadSigningCertificate operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * UploadSigningCertificate service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<UploadSigningCertificateResult> uploadSigningCertificateAsync( final UploadSigningCertificateRequest uploadSigningCertificateRequest, final AsyncHandler<UploadSigningCertificateRequest, UploadSigningCertificateResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<UploadSigningCertificateResult>() { public UploadSigningCertificateResult call() throws Exception { UploadSigningCertificateResult result; try { result = uploadSigningCertificate(uploadSigningCertificateRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(uploadSigningCertificateRequest, result); return result; } }); } /** * <p> * Retrieves information about all IAM users, groups, roles, and * policies in your account, including their relationships to one * another. Use this API to obtain a snapshot of the configuration of IAM * permissions (users, groups, roles, and policies) in your account. * </p> * <p> * You can optionally filter the results using the <code>Filter</code> * parameter. You can paginate the results using the * <code>MaxItems</code> and <code>Marker</code> parameters. * </p> * * @param getAccountAuthorizationDetailsRequest Container for the * necessary parameters to execute the GetAccountAuthorizationDetails * operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * GetAccountAuthorizationDetails service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetAccountAuthorizationDetailsResult> getAccountAuthorizationDetailsAsync(final GetAccountAuthorizationDetailsRequest getAccountAuthorizationDetailsRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetAccountAuthorizationDetailsResult>() { public GetAccountAuthorizationDetailsResult call() throws Exception { return getAccountAuthorizationDetails(getAccountAuthorizationDetailsRequest); } }); } /** * <p> * Retrieves information about all IAM users, groups, roles, and * policies in your account, including their relationships to one * another. Use this API to obtain a snapshot of the configuration of IAM * permissions (users, groups, roles, and policies) in your account. * </p> * <p> * You can optionally filter the results using the <code>Filter</code> * parameter. You can paginate the results using the * <code>MaxItems</code> and <code>Marker</code> parameters. * </p> * * @param getAccountAuthorizationDetailsRequest Container for the * necessary parameters to execute the GetAccountAuthorizationDetails * operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * GetAccountAuthorizationDetails service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetAccountAuthorizationDetailsResult> getAccountAuthorizationDetailsAsync( final GetAccountAuthorizationDetailsRequest getAccountAuthorizationDetailsRequest, final AsyncHandler<GetAccountAuthorizationDetailsRequest, GetAccountAuthorizationDetailsResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetAccountAuthorizationDetailsResult>() { public GetAccountAuthorizationDetailsResult call() throws Exception { GetAccountAuthorizationDetailsResult result; try { result = getAccountAuthorizationDetails(getAccountAuthorizationDetailsRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(getAccountAuthorizationDetailsRequest, result); return result; } }); } /** * <p> * Changes the password of the IAM user who is calling this action. The * root account password is not affected by this action. * </p> * <p> * To change the password for a different user, see UpdateLoginProfile. * For more information about modifying passwords, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingLogins.html"> Managing Passwords </a> * in the <i>IAM User Guide</i> . * </p> * * @param changePasswordRequest Container for the necessary parameters to * execute the ChangePassword operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ChangePassword service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> changePasswordAsync(final ChangePasswordRequest changePasswordRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { changePassword(changePasswordRequest); return null; } }); } /** * <p> * Changes the password of the IAM user who is calling this action. The * root account password is not affected by this action. * </p> * <p> * To change the password for a different user, see UpdateLoginProfile. * For more information about modifying passwords, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingLogins.html"> Managing Passwords </a> * in the <i>IAM User Guide</i> . * </p> * * @param changePasswordRequest Container for the necessary parameters to * execute the ChangePassword operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ChangePassword service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> changePasswordAsync( final ChangePasswordRequest changePasswordRequest, final AsyncHandler<ChangePasswordRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { changePassword(changePasswordRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(changePasswordRequest, null); return null; } }); } /** * <p> * Adds (or updates) an inline policy document that is embedded in the * specified group. * </p> * <p> * A user can also have managed policies attached to it. To attach a * managed policy to a group, use AttachGroupPolicy. To create a new * managed policy, use CreatePolicy. For information about policies, * refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * For information about limits on the number of inline policies that * you can embed in a group, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on IAM Entities </a> * in the <i>IAM User Guide</i> . * </p> * <p> * <b>NOTE:</b>Because policy documents can be large, you should use * POST rather than GET when calling PutGroupPolicy. For general * information about using the Query API with IAM, go to Making Query * Requests in the Using IAM guide. * </p> * * @param putGroupPolicyRequest Container for the necessary parameters to * execute the PutGroupPolicy operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * PutGroupPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> putGroupPolicyAsync(final PutGroupPolicyRequest putGroupPolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { putGroupPolicy(putGroupPolicyRequest); return null; } }); } /** * <p> * Adds (or updates) an inline policy document that is embedded in the * specified group. * </p> * <p> * A user can also have managed policies attached to it. To attach a * managed policy to a group, use AttachGroupPolicy. To create a new * managed policy, use CreatePolicy. For information about policies, * refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * For information about limits on the number of inline policies that * you can embed in a group, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on IAM Entities </a> * in the <i>IAM User Guide</i> . * </p> * <p> * <b>NOTE:</b>Because policy documents can be large, you should use * POST rather than GET when calling PutGroupPolicy. For general * information about using the Query API with IAM, go to Making Query * Requests in the Using IAM guide. * </p> * * @param putGroupPolicyRequest Container for the necessary parameters to * execute the PutGroupPolicy operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * PutGroupPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> putGroupPolicyAsync( final PutGroupPolicyRequest putGroupPolicyRequest, final AsyncHandler<PutGroupPolicyRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { putGroupPolicy(putGroupPolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(putGroupPolicyRequest, null); return null; } }); } /** * <p> * Deletes the specified signing certificate associated with the * specified user. * </p> * <p> * If you do not specify a user name, IAM determines the user name * implicitly based on the AWS access key ID signing the request. Because * this action works for access keys under the AWS account, you can use * this action to manage root credentials even if the AWS account has no * associated users. * </p> * * @param deleteSigningCertificateRequest Container for the necessary * parameters to execute the DeleteSigningCertificate operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DeleteSigningCertificate service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteSigningCertificateAsync(final DeleteSigningCertificateRequest deleteSigningCertificateRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { deleteSigningCertificate(deleteSigningCertificateRequest); return null; } }); } /** * <p> * Deletes the specified signing certificate associated with the * specified user. * </p> * <p> * If you do not specify a user name, IAM determines the user name * implicitly based on the AWS access key ID signing the request. Because * this action works for access keys under the AWS account, you can use * this action to manage root credentials even if the AWS account has no * associated users. * </p> * * @param deleteSigningCertificateRequest Container for the necessary * parameters to execute the DeleteSigningCertificate operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DeleteSigningCertificate service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteSigningCertificateAsync( final DeleteSigningCertificateRequest deleteSigningCertificateRequest, final AsyncHandler<DeleteSigningCertificateRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { deleteSigningCertificate(deleteSigningCertificateRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(deleteSigningCertificateRequest, null); return null; } }); } /** * <p> * Returns information about the access key IDs associated with the * specified user. If there are none, the action returns an empty list. * </p> * <p> * Although each user is limited to a small number of keys, you can * still paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * <p> * If the <code>UserName</code> field is not specified, the UserName is * determined implicitly based on the AWS access key ID used to sign the * request. Because this action works for access keys under the AWS * account, you can use this action to manage root credentials even if * the AWS account has no associated users. * </p> * <p> * <b>NOTE:</b>To ensure the security of your AWS account, the secret * access key is accessible only during key and user creation. * </p> * * @param listAccessKeysRequest Container for the necessary parameters to * execute the ListAccessKeys operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListAccessKeys service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListAccessKeysResult> listAccessKeysAsync(final ListAccessKeysRequest listAccessKeysRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListAccessKeysResult>() { public ListAccessKeysResult call() throws Exception { return listAccessKeys(listAccessKeysRequest); } }); } /** * <p> * Returns information about the access key IDs associated with the * specified user. If there are none, the action returns an empty list. * </p> * <p> * Although each user is limited to a small number of keys, you can * still paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * <p> * If the <code>UserName</code> field is not specified, the UserName is * determined implicitly based on the AWS access key ID used to sign the * request. Because this action works for access keys under the AWS * account, you can use this action to manage root credentials even if * the AWS account has no associated users. * </p> * <p> * <b>NOTE:</b>To ensure the security of your AWS account, the secret * access key is accessible only during key and user creation. * </p> * * @param listAccessKeysRequest Container for the necessary parameters to * execute the ListAccessKeys operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListAccessKeys service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListAccessKeysResult> listAccessKeysAsync( final ListAccessKeysRequest listAccessKeysRequest, final AsyncHandler<ListAccessKeysRequest, ListAccessKeysResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListAccessKeysResult>() { public ListAccessKeysResult call() throws Exception { ListAccessKeysResult result; try { result = listAccessKeys(listAccessKeysRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listAccessKeysRequest, result); return result; } }); } /** * <p> * Lists information about the OpenID Connect providers in the AWS * account. * </p> * * @param listOpenIDConnectProvidersRequest Container for the necessary * parameters to execute the ListOpenIDConnectProviders operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListOpenIDConnectProviders service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListOpenIDConnectProvidersResult> listOpenIDConnectProvidersAsync(final ListOpenIDConnectProvidersRequest listOpenIDConnectProvidersRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListOpenIDConnectProvidersResult>() { public ListOpenIDConnectProvidersResult call() throws Exception { return listOpenIDConnectProviders(listOpenIDConnectProvidersRequest); } }); } /** * <p> * Lists information about the OpenID Connect providers in the AWS * account. * </p> * * @param listOpenIDConnectProvidersRequest Container for the necessary * parameters to execute the ListOpenIDConnectProviders operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListOpenIDConnectProviders service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListOpenIDConnectProvidersResult> listOpenIDConnectProvidersAsync( final ListOpenIDConnectProvidersRequest listOpenIDConnectProvidersRequest, final AsyncHandler<ListOpenIDConnectProvidersRequest, ListOpenIDConnectProvidersResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListOpenIDConnectProvidersResult>() { public ListOpenIDConnectProvidersResult call() throws Exception { ListOpenIDConnectProvidersResult result; try { result = listOpenIDConnectProviders(listOpenIDConnectProvidersRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listOpenIDConnectProvidersRequest, result); return result; } }); } /** * <p> * Replaces the existing list of server certificate thumbprints with a * new list. * </p> * <p> * The list that you pass with this action completely replaces the * existing list of thumbprints. (The lists are not merged.) * </p> * <p> * Typically, you need to update a thumbprint only when the identity * provider's certificate changes, which occurs rarely. However, if the * provider's certificate <i>does</i> change, any attempt to assume an * IAM role that specifies the OIDC provider as a principal will fail * until the certificate thumbprint is updated. * </p> * <p> * <b>NOTE:</b>Because trust for the OpenID Connect provider is * ultimately derived from the provider's certificate and is validated by * the thumbprint, it is a best practice to limit access to the * UpdateOpenIDConnectProviderThumbprint action to highly-privileged * users. * </p> * * @param updateOpenIDConnectProviderThumbprintRequest Container for the * necessary parameters to execute the * UpdateOpenIDConnectProviderThumbprint operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * UpdateOpenIDConnectProviderThumbprint service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> updateOpenIDConnectProviderThumbprintAsync(final UpdateOpenIDConnectProviderThumbprintRequest updateOpenIDConnectProviderThumbprintRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { updateOpenIDConnectProviderThumbprint(updateOpenIDConnectProviderThumbprintRequest); return null; } }); } /** * <p> * Replaces the existing list of server certificate thumbprints with a * new list. * </p> * <p> * The list that you pass with this action completely replaces the * existing list of thumbprints. (The lists are not merged.) * </p> * <p> * Typically, you need to update a thumbprint only when the identity * provider's certificate changes, which occurs rarely. However, if the * provider's certificate <i>does</i> change, any attempt to assume an * IAM role that specifies the OIDC provider as a principal will fail * until the certificate thumbprint is updated. * </p> * <p> * <b>NOTE:</b>Because trust for the OpenID Connect provider is * ultimately derived from the provider's certificate and is validated by * the thumbprint, it is a best practice to limit access to the * UpdateOpenIDConnectProviderThumbprint action to highly-privileged * users. * </p> * * @param updateOpenIDConnectProviderThumbprintRequest Container for the * necessary parameters to execute the * UpdateOpenIDConnectProviderThumbprint operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * UpdateOpenIDConnectProviderThumbprint service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> updateOpenIDConnectProviderThumbprintAsync( final UpdateOpenIDConnectProviderThumbprintRequest updateOpenIDConnectProviderThumbprintRequest, final AsyncHandler<UpdateOpenIDConnectProviderThumbprintRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { updateOpenIDConnectProviderThumbprint(updateOpenIDConnectProviderThumbprintRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(updateOpenIDConnectProviderThumbprintRequest, null); return null; } }); } /** * <p> * Retrieves the specified SSH public key, including metadata about the * key. * </p> * <p> * The SSH public key retrieved by this action is used only for * authenticating the associated IAM user to an AWS CodeCommit * repository. For more information about using SSH keys to authenticate * to an AWS CodeCommit repository, see * <a href="http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html"> Set up AWS CodeCommit for SSH Connections </a> * in the <i>AWS CodeCommit User Guide</i> . * </p> * * @param getSSHPublicKeyRequest Container for the necessary parameters * to execute the GetSSHPublicKey operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * GetSSHPublicKey service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetSSHPublicKeyResult> getSSHPublicKeyAsync(final GetSSHPublicKeyRequest getSSHPublicKeyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetSSHPublicKeyResult>() { public GetSSHPublicKeyResult call() throws Exception { return getSSHPublicKey(getSSHPublicKeyRequest); } }); } /** * <p> * Retrieves the specified SSH public key, including metadata about the * key. * </p> * <p> * The SSH public key retrieved by this action is used only for * authenticating the associated IAM user to an AWS CodeCommit * repository. For more information about using SSH keys to authenticate * to an AWS CodeCommit repository, see * <a href="http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html"> Set up AWS CodeCommit for SSH Connections </a> * in the <i>AWS CodeCommit User Guide</i> . * </p> * * @param getSSHPublicKeyRequest Container for the necessary parameters * to execute the GetSSHPublicKey operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * GetSSHPublicKey service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetSSHPublicKeyResult> getSSHPublicKeyAsync( final GetSSHPublicKeyRequest getSSHPublicKeyRequest, final AsyncHandler<GetSSHPublicKeyRequest, GetSSHPublicKeyResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetSSHPublicKeyResult>() { public GetSSHPublicKeyResult call() throws Exception { GetSSHPublicKeyResult result; try { result = getSSHPublicKey(getSSHPublicKeyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(getSSHPublicKeyRequest, result); return result; } }); } /** * <p> * Removes the specified managed policy from the specified role. * </p> * <p> * A role can also have inline policies embedded with it. To delete an * inline policy, use the DeleteRolePolicy API. For information about * policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param detachRolePolicyRequest Container for the necessary parameters * to execute the DetachRolePolicy operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DetachRolePolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> detachRolePolicyAsync(final DetachRolePolicyRequest detachRolePolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { detachRolePolicy(detachRolePolicyRequest); return null; } }); } /** * <p> * Removes the specified managed policy from the specified role. * </p> * <p> * A role can also have inline policies embedded with it. To delete an * inline policy, use the DeleteRolePolicy API. For information about * policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param detachRolePolicyRequest Container for the necessary parameters * to execute the DetachRolePolicy operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DetachRolePolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> detachRolePolicyAsync( final DetachRolePolicyRequest detachRolePolicyRequest, final AsyncHandler<DetachRolePolicyRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { detachRolePolicy(detachRolePolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(detachRolePolicyRequest, null); return null; } }); } /** * <p> * Creates a new managed policy for your AWS account. * </p> * <p> * This operation creates a policy version with a version identifier of * <code>v1</code> and sets v1 as the policy's default version. For more * information about policy versions, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html"> Versioning for Managed Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * For more information about managed policies in general, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param createPolicyRequest Container for the necessary parameters to * execute the CreatePolicy operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * CreatePolicy service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreatePolicyResult> createPolicyAsync(final CreatePolicyRequest createPolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreatePolicyResult>() { public CreatePolicyResult call() throws Exception { return createPolicy(createPolicyRequest); } }); } /** * <p> * Creates a new managed policy for your AWS account. * </p> * <p> * This operation creates a policy version with a version identifier of * <code>v1</code> and sets v1 as the policy's default version. For more * information about policy versions, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html"> Versioning for Managed Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * For more information about managed policies in general, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param createPolicyRequest Container for the necessary parameters to * execute the CreatePolicy operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * CreatePolicy service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreatePolicyResult> createPolicyAsync( final CreatePolicyRequest createPolicyRequest, final AsyncHandler<CreatePolicyRequest, CreatePolicyResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreatePolicyResult>() { public CreatePolicyResult call() throws Exception { CreatePolicyResult result; try { result = createPolicy(createPolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(createPolicyRequest, result); return result; } }); } /** * <p> * Creates a new instance profile. For information about instance * profiles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html"> About Instance Profiles </a> * . * </p> * <p> * For information about the number of instance profiles you can create, * see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on IAM Entities </a> * in the <i>IAM User Guide</i> . * </p> * * @param createInstanceProfileRequest Container for the necessary * parameters to execute the CreateInstanceProfile operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * CreateInstanceProfile service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreateInstanceProfileResult> createInstanceProfileAsync(final CreateInstanceProfileRequest createInstanceProfileRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreateInstanceProfileResult>() { public CreateInstanceProfileResult call() throws Exception { return createInstanceProfile(createInstanceProfileRequest); } }); } /** * <p> * Creates a new instance profile. For information about instance * profiles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html"> About Instance Profiles </a> * . * </p> * <p> * For information about the number of instance profiles you can create, * see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on IAM Entities </a> * in the <i>IAM User Guide</i> . * </p> * * @param createInstanceProfileRequest Container for the necessary * parameters to execute the CreateInstanceProfile operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * CreateInstanceProfile service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreateInstanceProfileResult> createInstanceProfileAsync( final CreateInstanceProfileRequest createInstanceProfileRequest, final AsyncHandler<CreateInstanceProfileRequest, CreateInstanceProfileResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreateInstanceProfileResult>() { public CreateInstanceProfileResult call() throws Exception { CreateInstanceProfileResult result; try { result = createInstanceProfile(createInstanceProfileRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(createInstanceProfileRequest, result); return result; } }); } /** * <p> * Creates a password for the specified user, giving the user the * ability to access AWS services through the AWS Management Console. For * more information about managing passwords, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingLogins.html"> Managing Passwords </a> * in the <i>Using IAM</i> guide. * </p> * * @param createLoginProfileRequest Container for the necessary * parameters to execute the CreateLoginProfile operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * CreateLoginProfile service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreateLoginProfileResult> createLoginProfileAsync(final CreateLoginProfileRequest createLoginProfileRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreateLoginProfileResult>() { public CreateLoginProfileResult call() throws Exception { return createLoginProfile(createLoginProfileRequest); } }); } /** * <p> * Creates a password for the specified user, giving the user the * ability to access AWS services through the AWS Management Console. For * more information about managing passwords, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingLogins.html"> Managing Passwords </a> * in the <i>Using IAM</i> guide. * </p> * * @param createLoginProfileRequest Container for the necessary * parameters to execute the CreateLoginProfile operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * CreateLoginProfile service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreateLoginProfileResult> createLoginProfileAsync( final CreateLoginProfileRequest createLoginProfileRequest, final AsyncHandler<CreateLoginProfileRequest, CreateLoginProfileResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreateLoginProfileResult>() { public CreateLoginProfileResult call() throws Exception { CreateLoginProfileResult result; try { result = createLoginProfile(createLoginProfileRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(createLoginProfileRequest, result); return result; } }); } /** * <p> * Removes the specified role from the specified instance profile. * </p> * <p> * <b>IMPORTANT:</b> Make sure you do not have any Amazon EC2 instances * running with the role you are about to remove from the instance * profile. Removing a role from an instance profile that is associated * with a running instance will break any applications running on the * instance. * </p> * <p> * For more information about roles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html"> Working with Roles </a> . For more information about instance profiles, go to <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html"> About Instance Profiles </a> * . * </p> * * @param removeRoleFromInstanceProfileRequest Container for the * necessary parameters to execute the RemoveRoleFromInstanceProfile * operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * RemoveRoleFromInstanceProfile service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> removeRoleFromInstanceProfileAsync(final RemoveRoleFromInstanceProfileRequest removeRoleFromInstanceProfileRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { removeRoleFromInstanceProfile(removeRoleFromInstanceProfileRequest); return null; } }); } /** * <p> * Removes the specified role from the specified instance profile. * </p> * <p> * <b>IMPORTANT:</b> Make sure you do not have any Amazon EC2 instances * running with the role you are about to remove from the instance * profile. Removing a role from an instance profile that is associated * with a running instance will break any applications running on the * instance. * </p> * <p> * For more information about roles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html"> Working with Roles </a> . For more information about instance profiles, go to <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html"> About Instance Profiles </a> * . * </p> * * @param removeRoleFromInstanceProfileRequest Container for the * necessary parameters to execute the RemoveRoleFromInstanceProfile * operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * RemoveRoleFromInstanceProfile service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> removeRoleFromInstanceProfileAsync( final RemoveRoleFromInstanceProfileRequest removeRoleFromInstanceProfileRequest, final AsyncHandler<RemoveRoleFromInstanceProfileRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { removeRoleFromInstanceProfile(removeRoleFromInstanceProfileRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(removeRoleFromInstanceProfileRequest, null); return null; } }); } /** * <p> * Updates the password policy settings for the AWS account. * </p> * <p> * <b>NOTE:</b> This action does not support partial updates. No * parameters are required, but if you do not specify a parameter, that * parameter's value reverts to its default value. See the Request * Parameters section for each parameter's default value. * </p> * <p> * For more information about using a password policy, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingPasswordPolicies.html"> Managing an IAM Password Policy </a> * in the <i>IAM User Guide</i> . * </p> * * @param updateAccountPasswordPolicyRequest Container for the necessary * parameters to execute the UpdateAccountPasswordPolicy operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * UpdateAccountPasswordPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> updateAccountPasswordPolicyAsync(final UpdateAccountPasswordPolicyRequest updateAccountPasswordPolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { updateAccountPasswordPolicy(updateAccountPasswordPolicyRequest); return null; } }); } /** * <p> * Updates the password policy settings for the AWS account. * </p> * <p> * <b>NOTE:</b> This action does not support partial updates. No * parameters are required, but if you do not specify a parameter, that * parameter's value reverts to its default value. See the Request * Parameters section for each parameter's default value. * </p> * <p> * For more information about using a password policy, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingPasswordPolicies.html"> Managing an IAM Password Policy </a> * in the <i>IAM User Guide</i> . * </p> * * @param updateAccountPasswordPolicyRequest Container for the necessary * parameters to execute the UpdateAccountPasswordPolicy operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * UpdateAccountPasswordPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> updateAccountPasswordPolicyAsync( final UpdateAccountPasswordPolicyRequest updateAccountPasswordPolicyRequest, final AsyncHandler<UpdateAccountPasswordPolicyRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { updateAccountPasswordPolicy(updateAccountPasswordPolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(updateAccountPasswordPolicyRequest, null); return null; } }); } /** * <p> * Updates the policy that grants an entity permission to assume a role. * For more information about roles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/roles-toplevel.html"> Using Roles to Delegate Permissions and Federate Identities </a> * . * </p> * * @param updateAssumeRolePolicyRequest Container for the necessary * parameters to execute the UpdateAssumeRolePolicy operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * UpdateAssumeRolePolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> updateAssumeRolePolicyAsync(final UpdateAssumeRolePolicyRequest updateAssumeRolePolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { updateAssumeRolePolicy(updateAssumeRolePolicyRequest); return null; } }); } /** * <p> * Updates the policy that grants an entity permission to assume a role. * For more information about roles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/roles-toplevel.html"> Using Roles to Delegate Permissions and Federate Identities </a> * . * </p> * * @param updateAssumeRolePolicyRequest Container for the necessary * parameters to execute the UpdateAssumeRolePolicy operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * UpdateAssumeRolePolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> updateAssumeRolePolicyAsync( final UpdateAssumeRolePolicyRequest updateAssumeRolePolicyRequest, final AsyncHandler<UpdateAssumeRolePolicyRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { updateAssumeRolePolicy(updateAssumeRolePolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(updateAssumeRolePolicyRequest, null); return null; } }); } /** * <p> * Retrieves information about the specified instance profile, including * the instance profile's path, GUID, ARN, and role. For more information * about instance profiles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html"> About Instance Profiles </a> . For more information about ARNs, go to <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html#Identifiers_ARNs"> ARNs </a> * . * </p> * * @param getInstanceProfileRequest Container for the necessary * parameters to execute the GetInstanceProfile operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * GetInstanceProfile service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetInstanceProfileResult> getInstanceProfileAsync(final GetInstanceProfileRequest getInstanceProfileRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetInstanceProfileResult>() { public GetInstanceProfileResult call() throws Exception { return getInstanceProfile(getInstanceProfileRequest); } }); } /** * <p> * Retrieves information about the specified instance profile, including * the instance profile's path, GUID, ARN, and role. For more information * about instance profiles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html"> About Instance Profiles </a> . For more information about ARNs, go to <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html#Identifiers_ARNs"> ARNs </a> * . * </p> * * @param getInstanceProfileRequest Container for the necessary * parameters to execute the GetInstanceProfile operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * GetInstanceProfile service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetInstanceProfileResult> getInstanceProfileAsync( final GetInstanceProfileRequest getInstanceProfileRequest, final AsyncHandler<GetInstanceProfileRequest, GetInstanceProfileResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetInstanceProfileResult>() { public GetInstanceProfileResult call() throws Exception { GetInstanceProfileResult result; try { result = getInstanceProfile(getInstanceProfileRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(getInstanceProfileRequest, result); return result; } }); } /** * <p> * Retrieves information about IAM entity usage and IAM quotas in the * AWS account. * </p> * <p> * For information about limitations on IAM entities, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on IAM Entities </a> * in the <i>IAM User Guide</i> . * </p> * * @param getAccountSummaryRequest Container for the necessary parameters * to execute the GetAccountSummary operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * GetAccountSummary service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetAccountSummaryResult> getAccountSummaryAsync(final GetAccountSummaryRequest getAccountSummaryRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetAccountSummaryResult>() { public GetAccountSummaryResult call() throws Exception { return getAccountSummary(getAccountSummaryRequest); } }); } /** * <p> * Retrieves information about IAM entity usage and IAM quotas in the * AWS account. * </p> * <p> * For information about limitations on IAM entities, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on IAM Entities </a> * in the <i>IAM User Guide</i> . * </p> * * @param getAccountSummaryRequest Container for the necessary parameters * to execute the GetAccountSummary operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * GetAccountSummary service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetAccountSummaryResult> getAccountSummaryAsync( final GetAccountSummaryRequest getAccountSummaryRequest, final AsyncHandler<GetAccountSummaryRequest, GetAccountSummaryResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetAccountSummaryResult>() { public GetAccountSummaryResult call() throws Exception { GetAccountSummaryResult result; try { result = getAccountSummary(getAccountSummaryRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(getAccountSummaryRequest, result); return result; } }); } /** * <p> * Creates an IAM entity to describe an identity provider (IdP) that * supports SAML 2.0. * </p> * <p> * The SAML provider that you create with this operation can be used as * a principal in a role's trust policy to establish a trust relationship * between AWS and a SAML identity provider. You can create an IAM role * that supports Web-based single sign-on (SSO) to the AWS Management * Console or one that supports API access to AWS. * </p> * <p> * When you create the SAML provider, you upload an a SAML metadata * document that you get from your IdP and that includes the issuer's * name, expiration information, and keys that can be used to validate * the SAML authentication response (assertions) that are received from * the IdP. You must generate the metadata document using the identity * management software that is used as your organization's IdP. * </p> * <p> * <b>NOTE:</b> This operation requires Signature Version 4. * </p> * <p> * For more information, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-saml.html"> Enabling SAML 2.0 Federated Users to Access the AWS Management Console </a> and <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml.html"> About SAML 2.0-based Federation </a> * in the <i>IAM User Guide</i> . * </p> * * @param createSAMLProviderRequest Container for the necessary * parameters to execute the CreateSAMLProvider operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * CreateSAMLProvider service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreateSAMLProviderResult> createSAMLProviderAsync(final CreateSAMLProviderRequest createSAMLProviderRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreateSAMLProviderResult>() { public CreateSAMLProviderResult call() throws Exception { return createSAMLProvider(createSAMLProviderRequest); } }); } /** * <p> * Creates an IAM entity to describe an identity provider (IdP) that * supports SAML 2.0. * </p> * <p> * The SAML provider that you create with this operation can be used as * a principal in a role's trust policy to establish a trust relationship * between AWS and a SAML identity provider. You can create an IAM role * that supports Web-based single sign-on (SSO) to the AWS Management * Console or one that supports API access to AWS. * </p> * <p> * When you create the SAML provider, you upload an a SAML metadata * document that you get from your IdP and that includes the issuer's * name, expiration information, and keys that can be used to validate * the SAML authentication response (assertions) that are received from * the IdP. You must generate the metadata document using the identity * management software that is used as your organization's IdP. * </p> * <p> * <b>NOTE:</b> This operation requires Signature Version 4. * </p> * <p> * For more information, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-saml.html"> Enabling SAML 2.0 Federated Users to Access the AWS Management Console </a> and <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml.html"> About SAML 2.0-based Federation </a> * in the <i>IAM User Guide</i> . * </p> * * @param createSAMLProviderRequest Container for the necessary * parameters to execute the CreateSAMLProvider operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * CreateSAMLProvider service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreateSAMLProviderResult> createSAMLProviderAsync( final CreateSAMLProviderRequest createSAMLProviderRequest, final AsyncHandler<CreateSAMLProviderRequest, CreateSAMLProviderResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreateSAMLProviderResult>() { public CreateSAMLProviderResult call() throws Exception { CreateSAMLProviderResult result; try { result = createSAMLProvider(createSAMLProviderRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(createSAMLProviderRequest, result); return result; } }); } /** * <p> * Retrieves information about the specified managed policy, including * the policy's default version and the total number of users, groups, * and roles that the policy is attached to. For a list of the specific * users, groups, and roles that the policy is attached to, use the * ListEntitiesForPolicy API. This API returns metadata about the policy. * To retrieve the policy document for a specific version of the policy, * use GetPolicyVersion. * </p> * <p> * This API retrieves information about managed policies. To retrieve * information about an inline policy that is embedded with a user, * group, or role, use the GetUserPolicy, GetGroupPolicy, or * GetRolePolicy API. * </p> * <p> * For more information about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param getPolicyRequest Container for the necessary parameters to * execute the GetPolicy operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * GetPolicy service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetPolicyResult> getPolicyAsync(final GetPolicyRequest getPolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetPolicyResult>() { public GetPolicyResult call() throws Exception { return getPolicy(getPolicyRequest); } }); } /** * <p> * Retrieves information about the specified managed policy, including * the policy's default version and the total number of users, groups, * and roles that the policy is attached to. For a list of the specific * users, groups, and roles that the policy is attached to, use the * ListEntitiesForPolicy API. This API returns metadata about the policy. * To retrieve the policy document for a specific version of the policy, * use GetPolicyVersion. * </p> * <p> * This API retrieves information about managed policies. To retrieve * information about an inline policy that is embedded with a user, * group, or role, use the GetUserPolicy, GetGroupPolicy, or * GetRolePolicy API. * </p> * <p> * For more information about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param getPolicyRequest Container for the necessary parameters to * execute the GetPolicy operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * GetPolicy service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetPolicyResult> getPolicyAsync( final GetPolicyRequest getPolicyRequest, final AsyncHandler<GetPolicyRequest, GetPolicyResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetPolicyResult>() { public GetPolicyResult call() throws Exception { GetPolicyResult result; try { result = getPolicy(getPolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(getPolicyRequest, result); return result; } }); } /** * <p> * Lists information about the versions of the specified managed policy, * including the version that is set as the policy's default version. * </p> * <p> * For more information about managed policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param listPolicyVersionsRequest Container for the necessary * parameters to execute the ListPolicyVersions operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListPolicyVersions service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListPolicyVersionsResult> listPolicyVersionsAsync(final ListPolicyVersionsRequest listPolicyVersionsRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListPolicyVersionsResult>() { public ListPolicyVersionsResult call() throws Exception { return listPolicyVersions(listPolicyVersionsRequest); } }); } /** * <p> * Lists information about the versions of the specified managed policy, * including the version that is set as the policy's default version. * </p> * <p> * For more information about managed policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param listPolicyVersionsRequest Container for the necessary * parameters to execute the ListPolicyVersions operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListPolicyVersions service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListPolicyVersionsResult> listPolicyVersionsAsync( final ListPolicyVersionsRequest listPolicyVersionsRequest, final AsyncHandler<ListPolicyVersionsRequest, ListPolicyVersionsResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListPolicyVersionsResult>() { public ListPolicyVersionsResult call() throws Exception { ListPolicyVersionsResult result; try { result = listPolicyVersions(listPolicyVersionsRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listPolicyVersionsRequest, result); return result; } }); } /** * <p> * Deletes the access key associated with the specified user. * </p> * <p> * If you do not specify a user name, IAM determines the user name * implicitly based on the AWS access key ID signing the request. Because * this action works for access keys under the AWS account, you can use * this action to manage root credentials even if the AWS account has no * associated users. * </p> * * @param deleteAccessKeyRequest Container for the necessary parameters * to execute the DeleteAccessKey operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DeleteAccessKey service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteAccessKeyAsync(final DeleteAccessKeyRequest deleteAccessKeyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { deleteAccessKey(deleteAccessKeyRequest); return null; } }); } /** * <p> * Deletes the access key associated with the specified user. * </p> * <p> * If you do not specify a user name, IAM determines the user name * implicitly based on the AWS access key ID signing the request. Because * this action works for access keys under the AWS account, you can use * this action to manage root credentials even if the AWS account has no * associated users. * </p> * * @param deleteAccessKeyRequest Container for the necessary parameters * to execute the DeleteAccessKey operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DeleteAccessKey service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteAccessKeyAsync( final DeleteAccessKeyRequest deleteAccessKeyRequest, final AsyncHandler<DeleteAccessKeyRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { deleteAccessKey(deleteAccessKeyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(deleteAccessKeyRequest, null); return null; } }); } /** * <p> * Deletes the specified inline policy that is embedded in the specified * user. * </p> * <p> * A user can also have managed policies attached to it. To detach a * managed policy from a user, use DetachUserPolicy. For more information * about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param deleteUserPolicyRequest Container for the necessary parameters * to execute the DeleteUserPolicy operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DeleteUserPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteUserPolicyAsync(final DeleteUserPolicyRequest deleteUserPolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { deleteUserPolicy(deleteUserPolicyRequest); return null; } }); } /** * <p> * Deletes the specified inline policy that is embedded in the specified * user. * </p> * <p> * A user can also have managed policies attached to it. To detach a * managed policy from a user, use DetachUserPolicy. For more information * about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param deleteUserPolicyRequest Container for the necessary parameters * to execute the DeleteUserPolicy operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DeleteUserPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteUserPolicyAsync( final DeleteUserPolicyRequest deleteUserPolicyRequest, final AsyncHandler<DeleteUserPolicyRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { deleteUserPolicy(deleteUserPolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(deleteUserPolicyRequest, null); return null; } }); } /** * <p> * Lists the server certificates that have the specified path prefix. If * none exist, the action returns an empty list. * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listServerCertificatesRequest Container for the necessary * parameters to execute the ListServerCertificates operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListServerCertificates service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListServerCertificatesResult> listServerCertificatesAsync(final ListServerCertificatesRequest listServerCertificatesRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListServerCertificatesResult>() { public ListServerCertificatesResult call() throws Exception { return listServerCertificates(listServerCertificatesRequest); } }); } /** * <p> * Lists the server certificates that have the specified path prefix. If * none exist, the action returns an empty list. * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listServerCertificatesRequest Container for the necessary * parameters to execute the ListServerCertificates operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListServerCertificates service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListServerCertificatesResult> listServerCertificatesAsync( final ListServerCertificatesRequest listServerCertificatesRequest, final AsyncHandler<ListServerCertificatesRequest, ListServerCertificatesResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListServerCertificatesResult>() { public ListServerCertificatesResult call() throws Exception { ListServerCertificatesResult result; try { result = listServerCertificates(listServerCertificatesRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listServerCertificatesRequest, result); return result; } }); } /** * <p> * Updates the name and/or the path of the specified server certificate. * </p> * <p> * <b>IMPORTANT:</b> You should understand the implications of changing * a server certificate's path or name. For more information, see * Managing Server Certificates in the IAM User Guide. * </p> * <p> * <b>NOTE:</b>To change a server certificate name the requester must * have appropriate permissions on both the source object and the target * object. For example, to change the name from ProductionCert to * ProdCert, the entity making the request must have permission on * ProductionCert and ProdCert, or must have permission on all (*). For * more information about permissions, see Permissions and Policies. * </p> * * @param updateServerCertificateRequest Container for the necessary * parameters to execute the UpdateServerCertificate operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * UpdateServerCertificate service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> updateServerCertificateAsync(final UpdateServerCertificateRequest updateServerCertificateRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { updateServerCertificate(updateServerCertificateRequest); return null; } }); } /** * <p> * Updates the name and/or the path of the specified server certificate. * </p> * <p> * <b>IMPORTANT:</b> You should understand the implications of changing * a server certificate's path or name. For more information, see * Managing Server Certificates in the IAM User Guide. * </p> * <p> * <b>NOTE:</b>To change a server certificate name the requester must * have appropriate permissions on both the source object and the target * object. For example, to change the name from ProductionCert to * ProdCert, the entity making the request must have permission on * ProductionCert and ProdCert, or must have permission on all (*). For * more information about permissions, see Permissions and Policies. * </p> * * @param updateServerCertificateRequest Container for the necessary * parameters to execute the UpdateServerCertificate operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * UpdateServerCertificate service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> updateServerCertificateAsync( final UpdateServerCertificateRequest updateServerCertificateRequest, final AsyncHandler<UpdateServerCertificateRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { updateServerCertificate(updateServerCertificateRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(updateServerCertificateRequest, null); return null; } }); } /** * <p> * Updates the name and/or the path of the specified user. * </p> * <p> * <b>IMPORTANT:</b> You should understand the implications of changing * a user's path or name. For more information, see Renaming Users and * Groups in the IAM User Guide. * </p> * <p> * <b>NOTE:</b> To change a user name the requester must have * appropriate permissions on both the source object and the target * object. For example, to change Bob to Robert, the entity making the * request must have permission on Bob and Robert, or must have * permission on all (*). For more information about permissions, see * Permissions and Policies. * </p> * * @param updateUserRequest Container for the necessary parameters to * execute the UpdateUser operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * UpdateUser service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> updateUserAsync(final UpdateUserRequest updateUserRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { updateUser(updateUserRequest); return null; } }); } /** * <p> * Updates the name and/or the path of the specified user. * </p> * <p> * <b>IMPORTANT:</b> You should understand the implications of changing * a user's path or name. For more information, see Renaming Users and * Groups in the IAM User Guide. * </p> * <p> * <b>NOTE:</b> To change a user name the requester must have * appropriate permissions on both the source object and the target * object. For example, to change Bob to Robert, the entity making the * request must have permission on Bob and Robert, or must have * permission on all (*). For more information about permissions, see * Permissions and Policies. * </p> * * @param updateUserRequest Container for the necessary parameters to * execute the UpdateUser operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * UpdateUser service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> updateUserAsync( final UpdateUserRequest updateUserRequest, final AsyncHandler<UpdateUserRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { updateUser(updateUserRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(updateUserRequest, null); return null; } }); } /** * <p> * Deletes the specified SSH public key. * </p> * <p> * The SSH public key deleted by this action is used only for * authenticating the associated IAM user to an AWS CodeCommit * repository. For more information about using SSH keys to authenticate * to an AWS CodeCommit repository, see * <a href="http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html"> Set up AWS CodeCommit for SSH Connections </a> * in the <i>AWS CodeCommit User Guide</i> . * </p> * * @param deleteSSHPublicKeyRequest Container for the necessary * parameters to execute the DeleteSSHPublicKey operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DeleteSSHPublicKey service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteSSHPublicKeyAsync(final DeleteSSHPublicKeyRequest deleteSSHPublicKeyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { deleteSSHPublicKey(deleteSSHPublicKeyRequest); return null; } }); } /** * <p> * Deletes the specified SSH public key. * </p> * <p> * The SSH public key deleted by this action is used only for * authenticating the associated IAM user to an AWS CodeCommit * repository. For more information about using SSH keys to authenticate * to an AWS CodeCommit repository, see * <a href="http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html"> Set up AWS CodeCommit for SSH Connections </a> * in the <i>AWS CodeCommit User Guide</i> . * </p> * * @param deleteSSHPublicKeyRequest Container for the necessary * parameters to execute the DeleteSSHPublicKey operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DeleteSSHPublicKey service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteSSHPublicKeyAsync( final DeleteSSHPublicKeyRequest deleteSSHPublicKeyRequest, final AsyncHandler<DeleteSSHPublicKeyRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { deleteSSHPublicKey(deleteSSHPublicKeyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(deleteSSHPublicKeyRequest, null); return null; } }); } /** * <p> * Adds (or updates) an inline policy document that is embedded in the * specified role. * </p> * <p> * When you embed an inline policy in a role, the inline policy is used * as the role's access (permissions) policy. The role's trust policy is * created at the same time as the role, using CreateRole. You can update * a role's trust policy using UpdateAssumeRolePolicy. For more * information about roles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/roles-toplevel.html"> Using Roles to Delegate Permissions and Federate Identities </a> * . * </p> * <p> * A role can also have a managed policy attached to it. To attach a * managed policy to a role, use AttachRolePolicy. To create a new * managed policy, use CreatePolicy. For information about policies, * refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * For information about limits on the number of inline policies that * you can embed with a role, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on IAM Entities </a> * in the <i>IAM User Guide</i> . * </p> * <p> * <b>NOTE:</b>Because policy documents can be large, you should use * POST rather than GET when calling PutRolePolicy. For general * information about using the Query API with IAM, go to Making Query * Requests in the Using IAM guide. * </p> * * @param putRolePolicyRequest Container for the necessary parameters to * execute the PutRolePolicy operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * PutRolePolicy service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> putRolePolicyAsync(final PutRolePolicyRequest putRolePolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { putRolePolicy(putRolePolicyRequest); return null; } }); } /** * <p> * Adds (or updates) an inline policy document that is embedded in the * specified role. * </p> * <p> * When you embed an inline policy in a role, the inline policy is used * as the role's access (permissions) policy. The role's trust policy is * created at the same time as the role, using CreateRole. You can update * a role's trust policy using UpdateAssumeRolePolicy. For more * information about roles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/roles-toplevel.html"> Using Roles to Delegate Permissions and Federate Identities </a> * . * </p> * <p> * A role can also have a managed policy attached to it. To attach a * managed policy to a role, use AttachRolePolicy. To create a new * managed policy, use CreatePolicy. For information about policies, * refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * For information about limits on the number of inline policies that * you can embed with a role, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on IAM Entities </a> * in the <i>IAM User Guide</i> . * </p> * <p> * <b>NOTE:</b>Because policy documents can be large, you should use * POST rather than GET when calling PutRolePolicy. For general * information about using the Query API with IAM, go to Making Query * Requests in the Using IAM guide. * </p> * * @param putRolePolicyRequest Container for the necessary parameters to * execute the PutRolePolicy operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * PutRolePolicy service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> putRolePolicyAsync( final PutRolePolicyRequest putRolePolicyRequest, final AsyncHandler<PutRolePolicyRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { putRolePolicy(putRolePolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(putRolePolicyRequest, null); return null; } }); } /** * <p> * Deletes the specified inline policy that is embedded in the specified * group. * </p> * <p> * A group can also have managed policies attached to it. To detach a * managed policy from a group, use DetachGroupPolicy. For more * information about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param deleteGroupPolicyRequest Container for the necessary parameters * to execute the DeleteGroupPolicy operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DeleteGroupPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteGroupPolicyAsync(final DeleteGroupPolicyRequest deleteGroupPolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { deleteGroupPolicy(deleteGroupPolicyRequest); return null; } }); } /** * <p> * Deletes the specified inline policy that is embedded in the specified * group. * </p> * <p> * A group can also have managed policies attached to it. To detach a * managed policy from a group, use DetachGroupPolicy. For more * information about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param deleteGroupPolicyRequest Container for the necessary parameters * to execute the DeleteGroupPolicy operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DeleteGroupPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteGroupPolicyAsync( final DeleteGroupPolicyRequest deleteGroupPolicyRequest, final AsyncHandler<DeleteGroupPolicyRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { deleteGroupPolicy(deleteGroupPolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(deleteGroupPolicyRequest, null); return null; } }); } /** * <p> * Updates the name and/or the path of the specified group. * </p> * <p> * <b>IMPORTANT:</b> You should understand the implications of changing * a group's path or name. For more information, see Renaming Users and * Groups in the IAM User Guide. * </p> * <p> * <b>NOTE:</b>To change a group name the requester must have * appropriate permissions on both the source object and the target * object. For example, to change Managers to MGRs, the entity making the * request must have permission on Managers and MGRs, or must have * permission on all (*). For more information about permissions, see * Permissions and Policies. * </p> * * @param updateGroupRequest Container for the necessary parameters to * execute the UpdateGroup operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * UpdateGroup service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> updateGroupAsync(final UpdateGroupRequest updateGroupRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { updateGroup(updateGroupRequest); return null; } }); } /** * <p> * Updates the name and/or the path of the specified group. * </p> * <p> * <b>IMPORTANT:</b> You should understand the implications of changing * a group's path or name. For more information, see Renaming Users and * Groups in the IAM User Guide. * </p> * <p> * <b>NOTE:</b>To change a group name the requester must have * appropriate permissions on both the source object and the target * object. For example, to change Managers to MGRs, the entity making the * request must have permission on Managers and MGRs, or must have * permission on all (*). For more information about permissions, see * Permissions and Policies. * </p> * * @param updateGroupRequest Container for the necessary parameters to * execute the UpdateGroup operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * UpdateGroup service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> updateGroupAsync( final UpdateGroupRequest updateGroupRequest, final AsyncHandler<UpdateGroupRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { updateGroup(updateGroupRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(updateGroupRequest, null); return null; } }); } /** * <p> * Sets the status of the specified SSH public key to active or * inactive. SSH public keys that are inactive cannot be used for * authentication. This action can be used to disable a user's SSH public * key as part of a key rotation work flow. * </p> * <p> * The SSH public key affected by this action is used only for * authenticating the associated IAM user to an AWS CodeCommit * repository. For more information about using SSH keys to authenticate * to an AWS CodeCommit repository, see * <a href="http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html"> Set up AWS CodeCommit for SSH Connections </a> * in the <i>AWS CodeCommit User Guide</i> . * </p> * * @param updateSSHPublicKeyRequest Container for the necessary * parameters to execute the UpdateSSHPublicKey operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * UpdateSSHPublicKey service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> updateSSHPublicKeyAsync(final UpdateSSHPublicKeyRequest updateSSHPublicKeyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { updateSSHPublicKey(updateSSHPublicKeyRequest); return null; } }); } /** * <p> * Sets the status of the specified SSH public key to active or * inactive. SSH public keys that are inactive cannot be used for * authentication. This action can be used to disable a user's SSH public * key as part of a key rotation work flow. * </p> * <p> * The SSH public key affected by this action is used only for * authenticating the associated IAM user to an AWS CodeCommit * repository. For more information about using SSH keys to authenticate * to an AWS CodeCommit repository, see * <a href="http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html"> Set up AWS CodeCommit for SSH Connections </a> * in the <i>AWS CodeCommit User Guide</i> . * </p> * * @param updateSSHPublicKeyRequest Container for the necessary * parameters to execute the UpdateSSHPublicKey operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * UpdateSSHPublicKey service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> updateSSHPublicKeyAsync( final UpdateSSHPublicKeyRequest updateSSHPublicKeyRequest, final AsyncHandler<UpdateSSHPublicKeyRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { updateSSHPublicKey(updateSSHPublicKeyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(updateSSHPublicKeyRequest, null); return null; } }); } /** * <p> * Lists all the managed policies that are available to your account, * including your own customer managed policies and all AWS managed * policies. * </p> * <p> * You can filter the list of policies that is returned using the * optional <code>OnlyAttached</code> , <code>Scope</code> , and * <code>PathPrefix</code> parameters. For example, to list only the * customer managed policies in your AWS account, set <code>Scope</code> * to <code>Local</code> . To list only AWS managed policies, set * <code>Scope</code> to <code>AWS</code> . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * <p> * For more information about managed policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param listPoliciesRequest Container for the necessary parameters to * execute the ListPolicies operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListPolicies service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListPoliciesResult> listPoliciesAsync(final ListPoliciesRequest listPoliciesRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListPoliciesResult>() { public ListPoliciesResult call() throws Exception { return listPolicies(listPoliciesRequest); } }); } /** * <p> * Lists all the managed policies that are available to your account, * including your own customer managed policies and all AWS managed * policies. * </p> * <p> * You can filter the list of policies that is returned using the * optional <code>OnlyAttached</code> , <code>Scope</code> , and * <code>PathPrefix</code> parameters. For example, to list only the * customer managed policies in your AWS account, set <code>Scope</code> * to <code>Local</code> . To list only AWS managed policies, set * <code>Scope</code> to <code>AWS</code> . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * <p> * For more information about managed policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param listPoliciesRequest Container for the necessary parameters to * execute the ListPolicies operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListPolicies service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListPoliciesResult> listPoliciesAsync( final ListPoliciesRequest listPoliciesRequest, final AsyncHandler<ListPoliciesRequest, ListPoliciesResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListPoliciesResult>() { public ListPoliciesResult call() throws Exception { ListPoliciesResult result; try { result = listPolicies(listPoliciesRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listPoliciesRequest, result); return result; } }); } /** * <p> * Creates a new user for your AWS account. * </p> * <p> * For information about limitations on the number of users you can * create, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on IAM Entities </a> * in the <i>IAM User Guide</i> . * </p> * * @param createUserRequest Container for the necessary parameters to * execute the CreateUser operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * CreateUser service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreateUserResult> createUserAsync(final CreateUserRequest createUserRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreateUserResult>() { public CreateUserResult call() throws Exception { return createUser(createUserRequest); } }); } /** * <p> * Creates a new user for your AWS account. * </p> * <p> * For information about limitations on the number of users you can * create, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on IAM Entities </a> * in the <i>IAM User Guide</i> . * </p> * * @param createUserRequest Container for the necessary parameters to * execute the CreateUser operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * CreateUser service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreateUserResult> createUserAsync( final CreateUserRequest createUserRequest, final AsyncHandler<CreateUserRequest, CreateUserResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreateUserResult>() { public CreateUserResult call() throws Exception { CreateUserResult result; try { result = createUser(createUserRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(createUserRequest, result); return result; } }); } /** * <p> * Adds a new client ID (also known as audience) to the list of client * IDs already registered for the specified IAM OpenID Connect provider. * </p> * <p> * This action is idempotent; it does not fail or return an error if you * add an existing client ID to the provider. * </p> * * @param addClientIDToOpenIDConnectProviderRequest Container for the * necessary parameters to execute the AddClientIDToOpenIDConnectProvider * operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * AddClientIDToOpenIDConnectProvider service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> addClientIDToOpenIDConnectProviderAsync(final AddClientIDToOpenIDConnectProviderRequest addClientIDToOpenIDConnectProviderRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { addClientIDToOpenIDConnectProvider(addClientIDToOpenIDConnectProviderRequest); return null; } }); } /** * <p> * Adds a new client ID (also known as audience) to the list of client * IDs already registered for the specified IAM OpenID Connect provider. * </p> * <p> * This action is idempotent; it does not fail or return an error if you * add an existing client ID to the provider. * </p> * * @param addClientIDToOpenIDConnectProviderRequest Container for the * necessary parameters to execute the AddClientIDToOpenIDConnectProvider * operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * AddClientIDToOpenIDConnectProvider service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> addClientIDToOpenIDConnectProviderAsync( final AddClientIDToOpenIDConnectProviderRequest addClientIDToOpenIDConnectProviderRequest, final AsyncHandler<AddClientIDToOpenIDConnectProviderRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { addClientIDToOpenIDConnectProvider(addClientIDToOpenIDConnectProviderRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(addClientIDToOpenIDConnectProviderRequest, null); return null; } }); } /** * <p> * Deletes a SAML provider. * </p> * <p> * Deleting the provider does not update any roles that reference the * SAML provider as a principal in their trust policies. Any attempt to * assume a role that references a SAML provider that has been deleted * will fail. * </p> * <p> * <b>NOTE:</b> This operation requires Signature Version 4. * </p> * * @param deleteSAMLProviderRequest Container for the necessary * parameters to execute the DeleteSAMLProvider operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DeleteSAMLProvider service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteSAMLProviderAsync(final DeleteSAMLProviderRequest deleteSAMLProviderRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { deleteSAMLProvider(deleteSAMLProviderRequest); return null; } }); } /** * <p> * Deletes a SAML provider. * </p> * <p> * Deleting the provider does not update any roles that reference the * SAML provider as a principal in their trust policies. Any attempt to * assume a role that references a SAML provider that has been deleted * will fail. * </p> * <p> * <b>NOTE:</b> This operation requires Signature Version 4. * </p> * * @param deleteSAMLProviderRequest Container for the necessary * parameters to execute the DeleteSAMLProvider operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DeleteSAMLProvider service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteSAMLProviderAsync( final DeleteSAMLProviderRequest deleteSAMLProviderRequest, final AsyncHandler<DeleteSAMLProviderRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { deleteSAMLProvider(deleteSAMLProviderRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(deleteSAMLProviderRequest, null); return null; } }); } /** * <p> * Gets a list of all of the context keys referenced in * <code>Condition</code> elements in all of the IAM policies attached to * the specified IAM entity. The entity can be an IAM user, group, or * role. If you specify a user, then the request also includes all of the * policies attached to groups that the user is a member of. * </p> * <p> * You can optionally include a list of one or more additional policies, * specified as strings. If you want to include only a list of policies * by string, use GetContextKeysForCustomPolicy instead. * </p> * <p> * <b>Note:</b> This API discloses information about the permissions * granted to other users. If you do not want users to see other user's * permissions, then consider allowing them to use * GetContextKeysForCustomPolicy instead. * </p> * <p> * Context keys are variables maintained by AWS and its services that * provide details about the context of an API query request, and can be * evaluated by using the <code>Condition</code> element of an IAM * policy. Use GetContextKeysForPrincipalPolicy to understand what key * names and values you must supply when you call * SimulatePrincipalPolicy. * </p> * * @param getContextKeysForPrincipalPolicyRequest Container for the * necessary parameters to execute the GetContextKeysForPrincipalPolicy * operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * GetContextKeysForPrincipalPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetContextKeysForPrincipalPolicyResult> getContextKeysForPrincipalPolicyAsync(final GetContextKeysForPrincipalPolicyRequest getContextKeysForPrincipalPolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetContextKeysForPrincipalPolicyResult>() { public GetContextKeysForPrincipalPolicyResult call() throws Exception { return getContextKeysForPrincipalPolicy(getContextKeysForPrincipalPolicyRequest); } }); } /** * <p> * Gets a list of all of the context keys referenced in * <code>Condition</code> elements in all of the IAM policies attached to * the specified IAM entity. The entity can be an IAM user, group, or * role. If you specify a user, then the request also includes all of the * policies attached to groups that the user is a member of. * </p> * <p> * You can optionally include a list of one or more additional policies, * specified as strings. If you want to include only a list of policies * by string, use GetContextKeysForCustomPolicy instead. * </p> * <p> * <b>Note:</b> This API discloses information about the permissions * granted to other users. If you do not want users to see other user's * permissions, then consider allowing them to use * GetContextKeysForCustomPolicy instead. * </p> * <p> * Context keys are variables maintained by AWS and its services that * provide details about the context of an API query request, and can be * evaluated by using the <code>Condition</code> element of an IAM * policy. Use GetContextKeysForPrincipalPolicy to understand what key * names and values you must supply when you call * SimulatePrincipalPolicy. * </p> * * @param getContextKeysForPrincipalPolicyRequest Container for the * necessary parameters to execute the GetContextKeysForPrincipalPolicy * operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * GetContextKeysForPrincipalPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetContextKeysForPrincipalPolicyResult> getContextKeysForPrincipalPolicyAsync( final GetContextKeysForPrincipalPolicyRequest getContextKeysForPrincipalPolicyRequest, final AsyncHandler<GetContextKeysForPrincipalPolicyRequest, GetContextKeysForPrincipalPolicyResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetContextKeysForPrincipalPolicyResult>() { public GetContextKeysForPrincipalPolicyResult call() throws Exception { GetContextKeysForPrincipalPolicyResult result; try { result = getContextKeysForPrincipalPolicy(getContextKeysForPrincipalPolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(getContextKeysForPrincipalPolicyRequest, result); return result; } }); } /** * <p> * Removes the specified client ID (also known as audience) from the * list of client IDs registered for the specified IAM OpenID Connect * provider. * </p> * <p> * This action is idempotent; it does not fail or return an error if you * try to remove a client ID that was removed previously. * </p> * * @param removeClientIDFromOpenIDConnectProviderRequest Container for * the necessary parameters to execute the * RemoveClientIDFromOpenIDConnectProvider operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * RemoveClientIDFromOpenIDConnectProvider service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> removeClientIDFromOpenIDConnectProviderAsync(final RemoveClientIDFromOpenIDConnectProviderRequest removeClientIDFromOpenIDConnectProviderRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { removeClientIDFromOpenIDConnectProvider(removeClientIDFromOpenIDConnectProviderRequest); return null; } }); } /** * <p> * Removes the specified client ID (also known as audience) from the * list of client IDs registered for the specified IAM OpenID Connect * provider. * </p> * <p> * This action is idempotent; it does not fail or return an error if you * try to remove a client ID that was removed previously. * </p> * * @param removeClientIDFromOpenIDConnectProviderRequest Container for * the necessary parameters to execute the * RemoveClientIDFromOpenIDConnectProvider operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * RemoveClientIDFromOpenIDConnectProvider service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> removeClientIDFromOpenIDConnectProviderAsync( final RemoveClientIDFromOpenIDConnectProviderRequest removeClientIDFromOpenIDConnectProviderRequest, final AsyncHandler<RemoveClientIDFromOpenIDConnectProviderRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { removeClientIDFromOpenIDConnectProvider(removeClientIDFromOpenIDConnectProviderRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(removeClientIDFromOpenIDConnectProviderRequest, null); return null; } }); } /** * <p> * Creates a new group. * </p> * <p> * For information about the number of groups you can create, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on IAM Entities </a> * in the <i>IAM User Guide</i> . * </p> * * @param createGroupRequest Container for the necessary parameters to * execute the CreateGroup operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * CreateGroup service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreateGroupResult> createGroupAsync(final CreateGroupRequest createGroupRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreateGroupResult>() { public CreateGroupResult call() throws Exception { return createGroup(createGroupRequest); } }); } /** * <p> * Creates a new group. * </p> * <p> * For information about the number of groups you can create, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on IAM Entities </a> * in the <i>IAM User Guide</i> . * </p> * * @param createGroupRequest Container for the necessary parameters to * execute the CreateGroup operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * CreateGroup service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreateGroupResult> createGroupAsync( final CreateGroupRequest createGroupRequest, final AsyncHandler<CreateGroupRequest, CreateGroupResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreateGroupResult>() { public CreateGroupResult call() throws Exception { CreateGroupResult result; try { result = createGroup(createGroupRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(createGroupRequest, result); return result; } }); } /** * <p> * Deletes the specified user. The user must not belong to any groups, * have any keys or signing certificates, or have any attached policies. * </p> * * @param deleteUserRequest Container for the necessary parameters to * execute the DeleteUser operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DeleteUser service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteUserAsync(final DeleteUserRequest deleteUserRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { deleteUser(deleteUserRequest); return null; } }); } /** * <p> * Deletes the specified user. The user must not belong to any groups, * have any keys or signing certificates, or have any attached policies. * </p> * * @param deleteUserRequest Container for the necessary parameters to * execute the DeleteUser operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DeleteUser service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteUserAsync( final DeleteUserRequest deleteUserRequest, final AsyncHandler<DeleteUserRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { deleteUser(deleteUserRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(deleteUserRequest, null); return null; } }); } /** * <p> * Deactivates the specified MFA device and removes it from association * with the user name for which it was originally enabled. * </p> * <p> * For more information about creating and working with virtual MFA * devices, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_VirtualMFA.html"> Using a Virtual MFA Device </a> * in the <i>Using IAM</i> guide. * </p> * * @param deactivateMFADeviceRequest Container for the necessary * parameters to execute the DeactivateMFADevice operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DeactivateMFADevice service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deactivateMFADeviceAsync(final DeactivateMFADeviceRequest deactivateMFADeviceRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { deactivateMFADevice(deactivateMFADeviceRequest); return null; } }); } /** * <p> * Deactivates the specified MFA device and removes it from association * with the user name for which it was originally enabled. * </p> * <p> * For more information about creating and working with virtual MFA * devices, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_VirtualMFA.html"> Using a Virtual MFA Device </a> * in the <i>Using IAM</i> guide. * </p> * * @param deactivateMFADeviceRequest Container for the necessary * parameters to execute the DeactivateMFADevice operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DeactivateMFADevice service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deactivateMFADeviceAsync( final DeactivateMFADeviceRequest deactivateMFADeviceRequest, final AsyncHandler<DeactivateMFADeviceRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { deactivateMFADevice(deactivateMFADeviceRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(deactivateMFADeviceRequest, null); return null; } }); } /** * <p> * Retrieves information about the specified version of the specified * managed policy, including the policy document. * </p> * <p> * To list the available versions for a policy, use ListPolicyVersions. * </p> * <p> * This API retrieves information about managed policies. To retrieve * information about an inline policy that is embedded in a user, group, * or role, use the GetUserPolicy, GetGroupPolicy, or GetRolePolicy API. * </p> * <p> * For more information about the types of policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param getPolicyVersionRequest Container for the necessary parameters * to execute the GetPolicyVersion operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * GetPolicyVersion service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetPolicyVersionResult> getPolicyVersionAsync(final GetPolicyVersionRequest getPolicyVersionRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetPolicyVersionResult>() { public GetPolicyVersionResult call() throws Exception { return getPolicyVersion(getPolicyVersionRequest); } }); } /** * <p> * Retrieves information about the specified version of the specified * managed policy, including the policy document. * </p> * <p> * To list the available versions for a policy, use ListPolicyVersions. * </p> * <p> * This API retrieves information about managed policies. To retrieve * information about an inline policy that is embedded in a user, group, * or role, use the GetUserPolicy, GetGroupPolicy, or GetRolePolicy API. * </p> * <p> * For more information about the types of policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param getPolicyVersionRequest Container for the necessary parameters * to execute the GetPolicyVersion operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * GetPolicyVersion service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetPolicyVersionResult> getPolicyVersionAsync( final GetPolicyVersionRequest getPolicyVersionRequest, final AsyncHandler<GetPolicyVersionRequest, GetPolicyVersionResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetPolicyVersionResult>() { public GetPolicyVersionResult call() throws Exception { GetPolicyVersionResult result; try { result = getPolicyVersion(getPolicyVersionRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(getPolicyVersionRequest, result); return result; } }); } /** * <p> * Generates a credential report for the AWS account. For more * information about the credential report, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/credential-reports.html"> Getting Credential Reports </a> * in the <i>IAM User Guide</i> . * </p> * * @param generateCredentialReportRequest Container for the necessary * parameters to execute the GenerateCredentialReport operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * GenerateCredentialReport service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GenerateCredentialReportResult> generateCredentialReportAsync(final GenerateCredentialReportRequest generateCredentialReportRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GenerateCredentialReportResult>() { public GenerateCredentialReportResult call() throws Exception { return generateCredentialReport(generateCredentialReportRequest); } }); } /** * <p> * Generates a credential report for the AWS account. For more * information about the credential report, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/credential-reports.html"> Getting Credential Reports </a> * in the <i>IAM User Guide</i> . * </p> * * @param generateCredentialReportRequest Container for the necessary * parameters to execute the GenerateCredentialReport operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * GenerateCredentialReport service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GenerateCredentialReportResult> generateCredentialReportAsync( final GenerateCredentialReportRequest generateCredentialReportRequest, final AsyncHandler<GenerateCredentialReportRequest, GenerateCredentialReportResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GenerateCredentialReportResult>() { public GenerateCredentialReportResult call() throws Exception { GenerateCredentialReportResult result; try { result = generateCredentialReport(generateCredentialReportRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(generateCredentialReportRequest, result); return result; } }); } /** * <p> * Removes the specified user from the specified group. * </p> * * @param removeUserFromGroupRequest Container for the necessary * parameters to execute the RemoveUserFromGroup operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * RemoveUserFromGroup service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> removeUserFromGroupAsync(final RemoveUserFromGroupRequest removeUserFromGroupRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { removeUserFromGroup(removeUserFromGroupRequest); return null; } }); } /** * <p> * Removes the specified user from the specified group. * </p> * * @param removeUserFromGroupRequest Container for the necessary * parameters to execute the RemoveUserFromGroup operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * RemoveUserFromGroup service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> removeUserFromGroupAsync( final RemoveUserFromGroupRequest removeUserFromGroupRequest, final AsyncHandler<RemoveUserFromGroupRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { removeUserFromGroup(removeUserFromGroupRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(removeUserFromGroupRequest, null); return null; } }); } /** * <p> * Lists all managed policies that are attached to the specified role. * </p> * <p> * A role can also have inline policies embedded with it. To list the * inline policies for a role, use the ListRolePolicies API. For * information about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. You can use the * <code>PathPrefix</code> parameter to limit the list of policies to * only those matching the specified path prefix. If there are no * policies attached to the specified role (or none that match the * specified path prefix), the action returns an empty list. * </p> * * @param listAttachedRolePoliciesRequest Container for the necessary * parameters to execute the ListAttachedRolePolicies operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListAttachedRolePolicies service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListAttachedRolePoliciesResult> listAttachedRolePoliciesAsync(final ListAttachedRolePoliciesRequest listAttachedRolePoliciesRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListAttachedRolePoliciesResult>() { public ListAttachedRolePoliciesResult call() throws Exception { return listAttachedRolePolicies(listAttachedRolePoliciesRequest); } }); } /** * <p> * Lists all managed policies that are attached to the specified role. * </p> * <p> * A role can also have inline policies embedded with it. To list the * inline policies for a role, use the ListRolePolicies API. For * information about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. You can use the * <code>PathPrefix</code> parameter to limit the list of policies to * only those matching the specified path prefix. If there are no * policies attached to the specified role (or none that match the * specified path prefix), the action returns an empty list. * </p> * * @param listAttachedRolePoliciesRequest Container for the necessary * parameters to execute the ListAttachedRolePolicies operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListAttachedRolePolicies service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListAttachedRolePoliciesResult> listAttachedRolePoliciesAsync( final ListAttachedRolePoliciesRequest listAttachedRolePoliciesRequest, final AsyncHandler<ListAttachedRolePoliciesRequest, ListAttachedRolePoliciesResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListAttachedRolePoliciesResult>() { public ListAttachedRolePoliciesResult call() throws Exception { ListAttachedRolePoliciesResult result; try { result = listAttachedRolePolicies(listAttachedRolePoliciesRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listAttachedRolePoliciesRequest, result); return result; } }); } /** * <p> * Deletes the specified server certificate. * </p> * <p> * <b>IMPORTANT:</b> If you are using a server certificate with Elastic * Load Balancing, deleting the certificate could have implications for * your application. If Elastic Load Balancing doesn't detect the * deletion of bound certificates, it may continue to use the * certificates. This could cause Elastic Load Balancing to stop * accepting traffic. We recommend that you remove the reference to the * certificate from Elastic Load Balancing before using this command to * delete the certificate. For more information, go to * DeleteLoadBalancerListeners in the Elastic Load Balancing API * Reference. * </p> * * @param deleteServerCertificateRequest Container for the necessary * parameters to execute the DeleteServerCertificate operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DeleteServerCertificate service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteServerCertificateAsync(final DeleteServerCertificateRequest deleteServerCertificateRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { deleteServerCertificate(deleteServerCertificateRequest); return null; } }); } /** * <p> * Deletes the specified server certificate. * </p> * <p> * <b>IMPORTANT:</b> If you are using a server certificate with Elastic * Load Balancing, deleting the certificate could have implications for * your application. If Elastic Load Balancing doesn't detect the * deletion of bound certificates, it may continue to use the * certificates. This could cause Elastic Load Balancing to stop * accepting traffic. We recommend that you remove the reference to the * certificate from Elastic Load Balancing before using this command to * delete the certificate. For more information, go to * DeleteLoadBalancerListeners in the Elastic Load Balancing API * Reference. * </p> * * @param deleteServerCertificateRequest Container for the necessary * parameters to execute the DeleteServerCertificate operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DeleteServerCertificate service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteServerCertificateAsync( final DeleteServerCertificateRequest deleteServerCertificateRequest, final AsyncHandler<DeleteServerCertificateRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { deleteServerCertificate(deleteServerCertificateRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(deleteServerCertificateRequest, null); return null; } }); } /** * <p> * Lists all users, groups, and roles that the specified managed policy * is attached to. * </p> * <p> * You can use the optional <code>EntityFilter</code> parameter to limit * the results to a particular type of entity (users, groups, or roles). * For example, to list only the roles that are attached to the specified * policy, set <code>EntityFilter</code> to <code>Role</code> . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listEntitiesForPolicyRequest Container for the necessary * parameters to execute the ListEntitiesForPolicy operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListEntitiesForPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListEntitiesForPolicyResult> listEntitiesForPolicyAsync(final ListEntitiesForPolicyRequest listEntitiesForPolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListEntitiesForPolicyResult>() { public ListEntitiesForPolicyResult call() throws Exception { return listEntitiesForPolicy(listEntitiesForPolicyRequest); } }); } /** * <p> * Lists all users, groups, and roles that the specified managed policy * is attached to. * </p> * <p> * You can use the optional <code>EntityFilter</code> parameter to limit * the results to a particular type of entity (users, groups, or roles). * For example, to list only the roles that are attached to the specified * policy, set <code>EntityFilter</code> to <code>Role</code> . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listEntitiesForPolicyRequest Container for the necessary * parameters to execute the ListEntitiesForPolicy operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListEntitiesForPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListEntitiesForPolicyResult> listEntitiesForPolicyAsync( final ListEntitiesForPolicyRequest listEntitiesForPolicyRequest, final AsyncHandler<ListEntitiesForPolicyRequest, ListEntitiesForPolicyResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListEntitiesForPolicyResult>() { public ListEntitiesForPolicyResult call() throws Exception { ListEntitiesForPolicyResult result; try { result = listEntitiesForPolicy(listEntitiesForPolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listEntitiesForPolicyRequest, result); return result; } }); } /** * <p> * Removes the specified managed policy from the specified group. * </p> * <p> * A group can also have inline policies embedded with it. To delete an * inline policy, use the DeleteGroupPolicy API. For information about * policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param detachGroupPolicyRequest Container for the necessary parameters * to execute the DetachGroupPolicy operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DetachGroupPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> detachGroupPolicyAsync(final DetachGroupPolicyRequest detachGroupPolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { detachGroupPolicy(detachGroupPolicyRequest); return null; } }); } /** * <p> * Removes the specified managed policy from the specified group. * </p> * <p> * A group can also have inline policies embedded with it. To delete an * inline policy, use the DeleteGroupPolicy API. For information about * policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param detachGroupPolicyRequest Container for the necessary parameters * to execute the DetachGroupPolicy operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DetachGroupPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> detachGroupPolicyAsync( final DetachGroupPolicyRequest detachGroupPolicyRequest, final AsyncHandler<DetachGroupPolicyRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { detachGroupPolicy(detachGroupPolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(detachGroupPolicyRequest, null); return null; } }); } /** * <p> * Lists the instance profiles that have the specified path prefix. If * there are none, the action returns an empty list. For more information * about instance profiles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html"> About Instance Profiles </a> * . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listInstanceProfilesRequest Container for the necessary * parameters to execute the ListInstanceProfiles operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListInstanceProfiles service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListInstanceProfilesResult> listInstanceProfilesAsync(final ListInstanceProfilesRequest listInstanceProfilesRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListInstanceProfilesResult>() { public ListInstanceProfilesResult call() throws Exception { return listInstanceProfiles(listInstanceProfilesRequest); } }); } /** * <p> * Lists the instance profiles that have the specified path prefix. If * there are none, the action returns an empty list. For more information * about instance profiles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html"> About Instance Profiles </a> * . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listInstanceProfilesRequest Container for the necessary * parameters to execute the ListInstanceProfiles operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListInstanceProfiles service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListInstanceProfilesResult> listInstanceProfilesAsync( final ListInstanceProfilesRequest listInstanceProfilesRequest, final AsyncHandler<ListInstanceProfilesRequest, ListInstanceProfilesResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListInstanceProfilesResult>() { public ListInstanceProfilesResult call() throws Exception { ListInstanceProfilesResult result; try { result = listInstanceProfiles(listInstanceProfilesRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listInstanceProfilesRequest, result); return result; } }); } /** * <p> * Changes the status of the specified access key from Active to * Inactive, or vice versa. This action can be used to disable a user's * key as part of a key rotation work flow. * </p> * <p> * If the <code>UserName</code> field is not specified, the UserName is * determined implicitly based on the AWS access key ID used to sign the * request. Because this action works for access keys under the AWS * account, you can use this action to manage root credentials even if * the AWS account has no associated users. * </p> * <p> * For information about rotating keys, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/ManagingCredentials.html"> Managing Keys and Certificates </a> * in the <i>IAM User Guide</i> . * </p> * * @param updateAccessKeyRequest Container for the necessary parameters * to execute the UpdateAccessKey operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * UpdateAccessKey service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> updateAccessKeyAsync(final UpdateAccessKeyRequest updateAccessKeyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { updateAccessKey(updateAccessKeyRequest); return null; } }); } /** * <p> * Changes the status of the specified access key from Active to * Inactive, or vice versa. This action can be used to disable a user's * key as part of a key rotation work flow. * </p> * <p> * If the <code>UserName</code> field is not specified, the UserName is * determined implicitly based on the AWS access key ID used to sign the * request. Because this action works for access keys under the AWS * account, you can use this action to manage root credentials even if * the AWS account has no associated users. * </p> * <p> * For information about rotating keys, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/ManagingCredentials.html"> Managing Keys and Certificates </a> * in the <i>IAM User Guide</i> . * </p> * * @param updateAccessKeyRequest Container for the necessary parameters * to execute the UpdateAccessKey operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * UpdateAccessKey service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> updateAccessKeyAsync( final UpdateAccessKeyRequest updateAccessKeyRequest, final AsyncHandler<UpdateAccessKeyRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { updateAccessKey(updateAccessKeyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(updateAccessKeyRequest, null); return null; } }); } /** * <p> * Returns information about the specified OpenID Connect provider. * </p> * * @param getOpenIDConnectProviderRequest Container for the necessary * parameters to execute the GetOpenIDConnectProvider operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * GetOpenIDConnectProvider service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetOpenIDConnectProviderResult> getOpenIDConnectProviderAsync(final GetOpenIDConnectProviderRequest getOpenIDConnectProviderRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetOpenIDConnectProviderResult>() { public GetOpenIDConnectProviderResult call() throws Exception { return getOpenIDConnectProvider(getOpenIDConnectProviderRequest); } }); } /** * <p> * Returns information about the specified OpenID Connect provider. * </p> * * @param getOpenIDConnectProviderRequest Container for the necessary * parameters to execute the GetOpenIDConnectProvider operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * GetOpenIDConnectProvider service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetOpenIDConnectProviderResult> getOpenIDConnectProviderAsync( final GetOpenIDConnectProviderRequest getOpenIDConnectProviderRequest, final AsyncHandler<GetOpenIDConnectProviderRequest, GetOpenIDConnectProviderResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetOpenIDConnectProviderResult>() { public GetOpenIDConnectProviderResult call() throws Exception { GetOpenIDConnectProviderResult result; try { result = getOpenIDConnectProvider(getOpenIDConnectProviderRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(getOpenIDConnectProviderRequest, result); return result; } }); } /** * <p> * Adds the specified user to the specified group. * </p> * * @param addUserToGroupRequest Container for the necessary parameters to * execute the AddUserToGroup operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * AddUserToGroup service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> addUserToGroupAsync(final AddUserToGroupRequest addUserToGroupRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { addUserToGroup(addUserToGroupRequest); return null; } }); } /** * <p> * Adds the specified user to the specified group. * </p> * * @param addUserToGroupRequest Container for the necessary parameters to * execute the AddUserToGroup operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * AddUserToGroup service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> addUserToGroupAsync( final AddUserToGroupRequest addUserToGroupRequest, final AsyncHandler<AddUserToGroupRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { addUserToGroup(addUserToGroupRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(addUserToGroupRequest, null); return null; } }); } /** * <p> * Returns a list of users that are in the specified group. You can * paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param getGroupRequest Container for the necessary parameters to * execute the GetGroup operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the GetGroup * service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetGroupResult> getGroupAsync(final GetGroupRequest getGroupRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetGroupResult>() { public GetGroupResult call() throws Exception { return getGroup(getGroupRequest); } }); } /** * <p> * Returns a list of users that are in the specified group. You can * paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param getGroupRequest Container for the necessary parameters to * execute the GetGroup operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the GetGroup * service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetGroupResult> getGroupAsync( final GetGroupRequest getGroupRequest, final AsyncHandler<GetGroupRequest, GetGroupResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetGroupResult>() { public GetGroupResult call() throws Exception { GetGroupResult result; try { result = getGroup(getGroupRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(getGroupRequest, result); return result; } }); } /** * <p> * Deletes the specified group. The group must not contain any users or * have any attached policies. * </p> * * @param deleteGroupRequest Container for the necessary parameters to * execute the DeleteGroup operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DeleteGroup service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteGroupAsync(final DeleteGroupRequest deleteGroupRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { deleteGroup(deleteGroupRequest); return null; } }); } /** * <p> * Deletes the specified group. The group must not contain any users or * have any attached policies. * </p> * * @param deleteGroupRequest Container for the necessary parameters to * execute the DeleteGroup operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DeleteGroup service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteGroupAsync( final DeleteGroupRequest deleteGroupRequest, final AsyncHandler<DeleteGroupRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { deleteGroup(deleteGroupRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(deleteGroupRequest, null); return null; } }); } /** * <p> * Removes the specified managed policy from the specified user. * </p> * <p> * A user can also have inline policies embedded with it. To delete an * inline policy, use the DeleteUserPolicy API. For information about * policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param detachUserPolicyRequest Container for the necessary parameters * to execute the DetachUserPolicy operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DetachUserPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> detachUserPolicyAsync(final DetachUserPolicyRequest detachUserPolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { detachUserPolicy(detachUserPolicyRequest); return null; } }); } /** * <p> * Removes the specified managed policy from the specified user. * </p> * <p> * A user can also have inline policies embedded with it. To delete an * inline policy, use the DeleteUserPolicy API. For information about * policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param detachUserPolicyRequest Container for the necessary parameters * to execute the DetachUserPolicy operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DetachUserPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> detachUserPolicyAsync( final DetachUserPolicyRequest detachUserPolicyRequest, final AsyncHandler<DetachUserPolicyRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { detachUserPolicy(detachUserPolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(detachUserPolicyRequest, null); return null; } }); } /** * <p> * Deletes the specified instance profile. The instance profile must not * have an associated role. * </p> * <p> * <b>IMPORTANT:</b> Make sure you do not have any Amazon EC2 instances * running with the instance profile you are about to delete. Deleting a * role or instance profile that is associated with a running instance * will break any applications running on the instance. * </p> * <p> * For more information about instance profiles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html"> About Instance Profiles </a> * . * </p> * * @param deleteInstanceProfileRequest Container for the necessary * parameters to execute the DeleteInstanceProfile operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DeleteInstanceProfile service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteInstanceProfileAsync(final DeleteInstanceProfileRequest deleteInstanceProfileRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { deleteInstanceProfile(deleteInstanceProfileRequest); return null; } }); } /** * <p> * Deletes the specified instance profile. The instance profile must not * have an associated role. * </p> * <p> * <b>IMPORTANT:</b> Make sure you do not have any Amazon EC2 instances * running with the instance profile you are about to delete. Deleting a * role or instance profile that is associated with a running instance * will break any applications running on the instance. * </p> * <p> * For more information about instance profiles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html"> About Instance Profiles </a> * . * </p> * * @param deleteInstanceProfileRequest Container for the necessary * parameters to execute the DeleteInstanceProfile operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DeleteInstanceProfile service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteInstanceProfileAsync( final DeleteInstanceProfileRequest deleteInstanceProfileRequest, final AsyncHandler<DeleteInstanceProfileRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { deleteInstanceProfile(deleteInstanceProfileRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(deleteInstanceProfileRequest, null); return null; } }); } /** * <p> * Returns the SAML provider metadocument that was uploaded when the * provider was created or updated. * </p> * <p> * <b>NOTE:</b>This operation requires Signature Version 4. * </p> * * @param getSAMLProviderRequest Container for the necessary parameters * to execute the GetSAMLProvider operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * GetSAMLProvider service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetSAMLProviderResult> getSAMLProviderAsync(final GetSAMLProviderRequest getSAMLProviderRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetSAMLProviderResult>() { public GetSAMLProviderResult call() throws Exception { return getSAMLProvider(getSAMLProviderRequest); } }); } /** * <p> * Returns the SAML provider metadocument that was uploaded when the * provider was created or updated. * </p> * <p> * <b>NOTE:</b>This operation requires Signature Version 4. * </p> * * @param getSAMLProviderRequest Container for the necessary parameters * to execute the GetSAMLProvider operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * GetSAMLProvider service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetSAMLProviderResult> getSAMLProviderAsync( final GetSAMLProviderRequest getSAMLProviderRequest, final AsyncHandler<GetSAMLProviderRequest, GetSAMLProviderResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetSAMLProviderResult>() { public GetSAMLProviderResult call() throws Exception { GetSAMLProviderResult result; try { result = getSAMLProvider(getSAMLProviderRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(getSAMLProviderRequest, result); return result; } }); } /** * <p> * Creates a new role for your AWS account. For more information about * roles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html"> Working with Roles </a> . For information about limitations on role names and the number of roles you can create, go to <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on IAM Entities </a> * in the <i>IAM User Guide</i> . * </p> * <p> * The policy in the following example grants permission to an EC2 * instance to assume the role. * </p> * * @param createRoleRequest Container for the necessary parameters to * execute the CreateRole operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * CreateRole service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreateRoleResult> createRoleAsync(final CreateRoleRequest createRoleRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreateRoleResult>() { public CreateRoleResult call() throws Exception { return createRole(createRoleRequest); } }); } /** * <p> * Creates a new role for your AWS account. For more information about * roles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html"> Working with Roles </a> . For information about limitations on role names and the number of roles you can create, go to <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html"> Limitations on IAM Entities </a> * in the <i>IAM User Guide</i> . * </p> * <p> * The policy in the following example grants permission to an EC2 * instance to assume the role. * </p> * * @param createRoleRequest Container for the necessary parameters to * execute the CreateRole operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * CreateRole service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreateRoleResult> createRoleAsync( final CreateRoleRequest createRoleRequest, final AsyncHandler<CreateRoleRequest, CreateRoleResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreateRoleResult>() { public CreateRoleResult call() throws Exception { CreateRoleResult result; try { result = createRole(createRoleRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(createRoleRequest, result); return result; } }); } /** * <p> * Changes the password for the specified user. * </p> * <p> * Users can change their own passwords by calling ChangePassword. For * more information about modifying passwords, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingLogins.html"> Managing Passwords </a> * in the <i>IAM User Guide</i> . * </p> * * @param updateLoginProfileRequest Container for the necessary * parameters to execute the UpdateLoginProfile operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * UpdateLoginProfile service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> updateLoginProfileAsync(final UpdateLoginProfileRequest updateLoginProfileRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { updateLoginProfile(updateLoginProfileRequest); return null; } }); } /** * <p> * Changes the password for the specified user. * </p> * <p> * Users can change their own passwords by calling ChangePassword. For * more information about modifying passwords, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingLogins.html"> Managing Passwords </a> * in the <i>IAM User Guide</i> . * </p> * * @param updateLoginProfileRequest Container for the necessary * parameters to execute the UpdateLoginProfile operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * UpdateLoginProfile service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> updateLoginProfileAsync( final UpdateLoginProfileRequest updateLoginProfileRequest, final AsyncHandler<UpdateLoginProfileRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { updateLoginProfile(updateLoginProfileRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(updateLoginProfileRequest, null); return null; } }); } /** * <p> * Deletes the password for the specified user, which terminates the * user's ability to access AWS services through the AWS Management * Console. * </p> * <p> * <b>IMPORTANT:</b> Deleting a user's password does not prevent a user * from accessing IAM through the command line interface or the API. To * prevent all user access you must also either make the access key * inactive or delete it. For more information about making keys inactive * or deleting them, see UpdateAccessKey and DeleteAccessKey. * </p> * * @param deleteLoginProfileRequest Container for the necessary * parameters to execute the DeleteLoginProfile operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DeleteLoginProfile service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteLoginProfileAsync(final DeleteLoginProfileRequest deleteLoginProfileRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { deleteLoginProfile(deleteLoginProfileRequest); return null; } }); } /** * <p> * Deletes the password for the specified user, which terminates the * user's ability to access AWS services through the AWS Management * Console. * </p> * <p> * <b>IMPORTANT:</b> Deleting a user's password does not prevent a user * from accessing IAM through the command line interface or the API. To * prevent all user access you must also either make the access key * inactive or delete it. For more information about making keys inactive * or deleting them, see UpdateAccessKey and DeleteAccessKey. * </p> * * @param deleteLoginProfileRequest Container for the necessary * parameters to execute the DeleteLoginProfile operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DeleteLoginProfile service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteLoginProfileAsync( final DeleteLoginProfileRequest deleteLoginProfileRequest, final AsyncHandler<DeleteLoginProfileRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { deleteLoginProfile(deleteLoginProfileRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(deleteLoginProfileRequest, null); return null; } }); } /** * <p> * Uploads an SSH public key and associates it with the specified IAM * user. * </p> * <p> * The SSH public key uploaded by this action can be used only for * authenticating the associated IAM user to an AWS CodeCommit * repository. For more information about using SSH keys to authenticate * to an AWS CodeCommit repository, see * <a href="http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html"> Set up AWS CodeCommit for SSH Connections </a> * in the <i>AWS CodeCommit User Guide</i> . * </p> * * @param uploadSSHPublicKeyRequest Container for the necessary * parameters to execute the UploadSSHPublicKey operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * UploadSSHPublicKey service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<UploadSSHPublicKeyResult> uploadSSHPublicKeyAsync(final UploadSSHPublicKeyRequest uploadSSHPublicKeyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<UploadSSHPublicKeyResult>() { public UploadSSHPublicKeyResult call() throws Exception { return uploadSSHPublicKey(uploadSSHPublicKeyRequest); } }); } /** * <p> * Uploads an SSH public key and associates it with the specified IAM * user. * </p> * <p> * The SSH public key uploaded by this action can be used only for * authenticating the associated IAM user to an AWS CodeCommit * repository. For more information about using SSH keys to authenticate * to an AWS CodeCommit repository, see * <a href="http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-credentials-ssh.html"> Set up AWS CodeCommit for SSH Connections </a> * in the <i>AWS CodeCommit User Guide</i> . * </p> * * @param uploadSSHPublicKeyRequest Container for the necessary * parameters to execute the UploadSSHPublicKey operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * UploadSSHPublicKey service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<UploadSSHPublicKeyResult> uploadSSHPublicKeyAsync( final UploadSSHPublicKeyRequest uploadSSHPublicKeyRequest, final AsyncHandler<UploadSSHPublicKeyRequest, UploadSSHPublicKeyResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<UploadSSHPublicKeyResult>() { public UploadSSHPublicKeyResult call() throws Exception { UploadSSHPublicKeyResult result; try { result = uploadSSHPublicKey(uploadSSHPublicKeyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(uploadSSHPublicKeyRequest, result); return result; } }); } /** * <p> * Simulate how a set of IAM policies attached to an IAM entity works * with a list of API actions and AWS resources to determine the * policies' effective permissions. The entity can be an IAM user, group, * or role. If you specify a user, then the simulation also includes all * of the policies that are attached to groups that the user belongs to . * </p> * <p> * You can optionally include a list of one or more additional policies * specified as strings to include in the simulation. If you want to * simulate only policies specified as strings, use SimulateCustomPolicy * instead. * </p> * <p> * You can also optionally include one resource-based policy to be * evaluated with each of the resources included in the simulation. * </p> * <p> * The simulation does not perform the API actions, it only checks the * authorization to determine if the simulated policies allow or deny the * actions. * </p> * <p> * <b>Note:</b> This API discloses information about the permissions * granted to other users. If you do not want users to see other user's * permissions, then consider allowing them to use SimulateCustomPolicy * instead. * </p> * <p> * Context keys are variables maintained by AWS and its services that * provide details about the context of an API query request. You can use * the <code>Condition</code> element of an IAM policy to evaluate * context keys. To get the list of context keys that the policies * require for correct simulation, use GetContextKeysForPrincipalPolicy. * </p> * <p> * If the output is long, you can use the <code>MaxItems</code> and * <code>Marker</code> parameters to paginate the results. * </p> * Example This example simulates calling the Amazon S3 APIs GetObject, * PutObject, and DeleteObject for a specific S3 bucket. The simulation * includes all policies that are attached to the user Jill. In this * example, the user Jill has only the managed policy * "AmazonS3ReadOnlyAccess" attached. Note that all parameters are shown * in unencoded form here for clarity but must be URL encoded to be * included as a part of a real HTML request. In the results, the * simulation shows that Jill can add new files to the bucket because of * the additional policy specified as a string parameter. In addition, * she can read from the bucket because of the managed policy attached to * the user. However, she cannot delete anything from the S3 bucket * because of the default implicitDeny. * https://iam.amazonaws.com/Action=SimulatePrincipalPolicy * &ActionNames.member.1=s3:PutObject &ActionNames.member.2=s3:GetObject * &ActionNames.member.3=s3:DeleteObject * &ResourceArns.member.1="arn:aws:s3:::my-test-bucket" * &PolicySourceArn=arn:aws:iam:::user/Jill &PolicyInputList.member.1='{ * "Version":"2012-10-17", "Statement":{ "Effect":"Allow", * "Action":"s3:PutObject", "Resource":"arn:aws:s3:::my-test-bucket" } }' * &Version=2010-05-08 &AUTHPARAMS <SimulatePrincipalPolicyResponse * xmlns="https://iam.amazonaws.com/doc/2010-05-08/"> * <SimulatePrincipalPolicyResult> <IsTruncated>false</IsTruncated> * <EvaluationResults> <member> <MatchedStatements> <member> * <SourcePolicyId>PolicyInputList.1</SourcePolicyId> <EndPosition> * <Column>2</Column> <Line>8</Line> </EndPosition> <StartPosition> * <Column>14</Column> <Line>3</Line> </StartPosition> </member> * </MatchedStatements> <MissingContextValues/> * <EvalResourceName>arn:aws:s3:::my-test-bucket</EvalResourceName> * <EvalDecision>allowed</EvalDecision> * <EvalActionName>s3:PutObject</EvalActionName> </member> <member> * <MatchedStatements> <member> * <SourcePolicyId>AmazonS3ReadOnlyAccess</SourcePolicyId> <EndPosition> * <Column>6</Column> <Line>11</Line> </EndPosition> <StartPosition> * <Column>17</Column> <Line>3</Line> </StartPosition> </member> * </MatchedStatements> <MissingContextValues/> * <EvalResourceName>arn:aws:s3:::my-test-bucket</EvalResourceName> * <EvalDecision>allowed</EvalDecision> * <EvalActionName>s3:GetObject</EvalActionName> </member> <member> * <MatchedStatements/> <MissingContextValues/> * <EvalResourceName>arn:aws:s3:::my-test-bucket</EvalResourceName> * <EvalDecision>implicitDeny</EvalDecision> * <EvalActionName>s3:DeleteObject</EvalActionName> </member> * </EvaluationResults> </SimulatePrincipalPolicyResult> * <ResponseMetadata> * <RequestId>004d7059-4c14-11e5-b121-bd8c7EXAMPLE</RequestId> * </ResponseMetadata> </SimulatePrincipalPolicyResponse> * * @param simulatePrincipalPolicyRequest Container for the necessary * parameters to execute the SimulatePrincipalPolicy operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * SimulatePrincipalPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<SimulatePrincipalPolicyResult> simulatePrincipalPolicyAsync(final SimulatePrincipalPolicyRequest simulatePrincipalPolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<SimulatePrincipalPolicyResult>() { public SimulatePrincipalPolicyResult call() throws Exception { return simulatePrincipalPolicy(simulatePrincipalPolicyRequest); } }); } /** * <p> * Simulate how a set of IAM policies attached to an IAM entity works * with a list of API actions and AWS resources to determine the * policies' effective permissions. The entity can be an IAM user, group, * or role. If you specify a user, then the simulation also includes all * of the policies that are attached to groups that the user belongs to . * </p> * <p> * You can optionally include a list of one or more additional policies * specified as strings to include in the simulation. If you want to * simulate only policies specified as strings, use SimulateCustomPolicy * instead. * </p> * <p> * You can also optionally include one resource-based policy to be * evaluated with each of the resources included in the simulation. * </p> * <p> * The simulation does not perform the API actions, it only checks the * authorization to determine if the simulated policies allow or deny the * actions. * </p> * <p> * <b>Note:</b> This API discloses information about the permissions * granted to other users. If you do not want users to see other user's * permissions, then consider allowing them to use SimulateCustomPolicy * instead. * </p> * <p> * Context keys are variables maintained by AWS and its services that * provide details about the context of an API query request. You can use * the <code>Condition</code> element of an IAM policy to evaluate * context keys. To get the list of context keys that the policies * require for correct simulation, use GetContextKeysForPrincipalPolicy. * </p> * <p> * If the output is long, you can use the <code>MaxItems</code> and * <code>Marker</code> parameters to paginate the results. * </p> * Example This example simulates calling the Amazon S3 APIs GetObject, * PutObject, and DeleteObject for a specific S3 bucket. The simulation * includes all policies that are attached to the user Jill. In this * example, the user Jill has only the managed policy * "AmazonS3ReadOnlyAccess" attached. Note that all parameters are shown * in unencoded form here for clarity but must be URL encoded to be * included as a part of a real HTML request. In the results, the * simulation shows that Jill can add new files to the bucket because of * the additional policy specified as a string parameter. In addition, * she can read from the bucket because of the managed policy attached to * the user. However, she cannot delete anything from the S3 bucket * because of the default implicitDeny. * https://iam.amazonaws.com/Action=SimulatePrincipalPolicy * &ActionNames.member.1=s3:PutObject &ActionNames.member.2=s3:GetObject * &ActionNames.member.3=s3:DeleteObject * &ResourceArns.member.1="arn:aws:s3:::my-test-bucket" * &PolicySourceArn=arn:aws:iam:::user/Jill &PolicyInputList.member.1='{ * "Version":"2012-10-17", "Statement":{ "Effect":"Allow", * "Action":"s3:PutObject", "Resource":"arn:aws:s3:::my-test-bucket" } }' * &Version=2010-05-08 &AUTHPARAMS <SimulatePrincipalPolicyResponse * xmlns="https://iam.amazonaws.com/doc/2010-05-08/"> * <SimulatePrincipalPolicyResult> <IsTruncated>false</IsTruncated> * <EvaluationResults> <member> <MatchedStatements> <member> * <SourcePolicyId>PolicyInputList.1</SourcePolicyId> <EndPosition> * <Column>2</Column> <Line>8</Line> </EndPosition> <StartPosition> * <Column>14</Column> <Line>3</Line> </StartPosition> </member> * </MatchedStatements> <MissingContextValues/> * <EvalResourceName>arn:aws:s3:::my-test-bucket</EvalResourceName> * <EvalDecision>allowed</EvalDecision> * <EvalActionName>s3:PutObject</EvalActionName> </member> <member> * <MatchedStatements> <member> * <SourcePolicyId>AmazonS3ReadOnlyAccess</SourcePolicyId> <EndPosition> * <Column>6</Column> <Line>11</Line> </EndPosition> <StartPosition> * <Column>17</Column> <Line>3</Line> </StartPosition> </member> * </MatchedStatements> <MissingContextValues/> * <EvalResourceName>arn:aws:s3:::my-test-bucket</EvalResourceName> * <EvalDecision>allowed</EvalDecision> * <EvalActionName>s3:GetObject</EvalActionName> </member> <member> * <MatchedStatements/> <MissingContextValues/> * <EvalResourceName>arn:aws:s3:::my-test-bucket</EvalResourceName> * <EvalDecision>implicitDeny</EvalDecision> * <EvalActionName>s3:DeleteObject</EvalActionName> </member> * </EvaluationResults> </SimulatePrincipalPolicyResult> * <ResponseMetadata> * <RequestId>004d7059-4c14-11e5-b121-bd8c7EXAMPLE</RequestId> * </ResponseMetadata> </SimulatePrincipalPolicyResponse> * * @param simulatePrincipalPolicyRequest Container for the necessary * parameters to execute the SimulatePrincipalPolicy operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * SimulatePrincipalPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<SimulatePrincipalPolicyResult> simulatePrincipalPolicyAsync( final SimulatePrincipalPolicyRequest simulatePrincipalPolicyRequest, final AsyncHandler<SimulatePrincipalPolicyRequest, SimulatePrincipalPolicyResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<SimulatePrincipalPolicyResult>() { public SimulatePrincipalPolicyResult call() throws Exception { SimulatePrincipalPolicyResult result; try { result = simulatePrincipalPolicy(simulatePrincipalPolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(simulatePrincipalPolicyRequest, result); return result; } }); } /** * <p> * Attaches the specified managed policy to the specified user. * </p> * <p> * You use this API to attach a managed policy to a user. To embed an * inline policy in a user, use PutUserPolicy. * </p> * <p> * For more information about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param attachUserPolicyRequest Container for the necessary parameters * to execute the AttachUserPolicy operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * AttachUserPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> attachUserPolicyAsync(final AttachUserPolicyRequest attachUserPolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { attachUserPolicy(attachUserPolicyRequest); return null; } }); } /** * <p> * Attaches the specified managed policy to the specified user. * </p> * <p> * You use this API to attach a managed policy to a user. To embed an * inline policy in a user, use PutUserPolicy. * </p> * <p> * For more information about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param attachUserPolicyRequest Container for the necessary parameters * to execute the AttachUserPolicy operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * AttachUserPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> attachUserPolicyAsync( final AttachUserPolicyRequest attachUserPolicyRequest, final AsyncHandler<AttachUserPolicyRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { attachUserPolicy(attachUserPolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(attachUserPolicyRequest, null); return null; } }); } /** * <p> * Retrieves information about the specified server certificate. * </p> * * @param getServerCertificateRequest Container for the necessary * parameters to execute the GetServerCertificate operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * GetServerCertificate service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetServerCertificateResult> getServerCertificateAsync(final GetServerCertificateRequest getServerCertificateRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetServerCertificateResult>() { public GetServerCertificateResult call() throws Exception { return getServerCertificate(getServerCertificateRequest); } }); } /** * <p> * Retrieves information about the specified server certificate. * </p> * * @param getServerCertificateRequest Container for the necessary * parameters to execute the GetServerCertificate operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * GetServerCertificate service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetServerCertificateResult> getServerCertificateAsync( final GetServerCertificateRequest getServerCertificateRequest, final AsyncHandler<GetServerCertificateRequest, GetServerCertificateResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetServerCertificateResult>() { public GetServerCertificateResult call() throws Exception { GetServerCertificateResult result; try { result = getServerCertificate(getServerCertificateRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(getServerCertificateRequest, result); return result; } }); } /** * <p> * Attaches the specified managed policy to the specified group. * </p> * <p> * You use this API to attach a managed policy to a group. To embed an * inline policy in a group, use PutGroupPolicy. * </p> * <p> * For more information about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param attachGroupPolicyRequest Container for the necessary parameters * to execute the AttachGroupPolicy operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * AttachGroupPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> attachGroupPolicyAsync(final AttachGroupPolicyRequest attachGroupPolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { attachGroupPolicy(attachGroupPolicyRequest); return null; } }); } /** * <p> * Attaches the specified managed policy to the specified group. * </p> * <p> * You use this API to attach a managed policy to a group. To embed an * inline policy in a group, use PutGroupPolicy. * </p> * <p> * For more information about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param attachGroupPolicyRequest Container for the necessary parameters * to execute the AttachGroupPolicy operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * AttachGroupPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> attachGroupPolicyAsync( final AttachGroupPolicyRequest attachGroupPolicyRequest, final AsyncHandler<AttachGroupPolicyRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { attachGroupPolicy(attachGroupPolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(attachGroupPolicyRequest, null); return null; } }); } /** * <p> * Sets the specified version of the specified policy as the policy's * default (operative) version. * </p> * <p> * This action affects all users, groups, and roles that the policy is * attached to. To list the users, groups, and roles that the policy is * attached to, use the ListEntitiesForPolicy API. * </p> * <p> * For information about managed policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param setDefaultPolicyVersionRequest Container for the necessary * parameters to execute the SetDefaultPolicyVersion operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * SetDefaultPolicyVersion service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> setDefaultPolicyVersionAsync(final SetDefaultPolicyVersionRequest setDefaultPolicyVersionRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { setDefaultPolicyVersion(setDefaultPolicyVersionRequest); return null; } }); } /** * <p> * Sets the specified version of the specified policy as the policy's * default (operative) version. * </p> * <p> * This action affects all users, groups, and roles that the policy is * attached to. To list the users, groups, and roles that the policy is * attached to, use the ListEntitiesForPolicy API. * </p> * <p> * For information about managed policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param setDefaultPolicyVersionRequest Container for the necessary * parameters to execute the SetDefaultPolicyVersion operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * SetDefaultPolicyVersion service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> setDefaultPolicyVersionAsync( final SetDefaultPolicyVersionRequest setDefaultPolicyVersionRequest, final AsyncHandler<SetDefaultPolicyVersionRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { setDefaultPolicyVersion(setDefaultPolicyVersionRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(setDefaultPolicyVersionRequest, null); return null; } }); } /** * <p> * Lists the names of the inline policies embedded in the specified * user. * </p> * <p> * A user can also have managed policies attached to it. To list the * managed policies that are attached to a user, use * ListAttachedUserPolicies. For more information about policies, refer * to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. If there are no inline policies * embedded with the specified user, the action returns an empty list. * </p> * * @param listUserPoliciesRequest Container for the necessary parameters * to execute the ListUserPolicies operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListUserPolicies service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListUserPoliciesResult> listUserPoliciesAsync(final ListUserPoliciesRequest listUserPoliciesRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListUserPoliciesResult>() { public ListUserPoliciesResult call() throws Exception { return listUserPolicies(listUserPoliciesRequest); } }); } /** * <p> * Lists the names of the inline policies embedded in the specified * user. * </p> * <p> * A user can also have managed policies attached to it. To list the * managed policies that are attached to a user, use * ListAttachedUserPolicies. For more information about policies, refer * to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. If there are no inline policies * embedded with the specified user, the action returns an empty list. * </p> * * @param listUserPoliciesRequest Container for the necessary parameters * to execute the ListUserPolicies operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListUserPolicies service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListUserPoliciesResult> listUserPoliciesAsync( final ListUserPoliciesRequest listUserPoliciesRequest, final AsyncHandler<ListUserPoliciesRequest, ListUserPoliciesResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListUserPoliciesResult>() { public ListUserPoliciesResult call() throws Exception { ListUserPoliciesResult result; try { result = listUserPolicies(listUserPoliciesRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listUserPoliciesRequest, result); return result; } }); } /** * <p> * Retrieves information about when the specified access key was last * used. The information includes the date and time of last use, along * with the AWS service and region that were specified in the last * request made with that key. * </p> * * @param getAccessKeyLastUsedRequest Container for the necessary * parameters to execute the GetAccessKeyLastUsed operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * GetAccessKeyLastUsed service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetAccessKeyLastUsedResult> getAccessKeyLastUsedAsync(final GetAccessKeyLastUsedRequest getAccessKeyLastUsedRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetAccessKeyLastUsedResult>() { public GetAccessKeyLastUsedResult call() throws Exception { return getAccessKeyLastUsed(getAccessKeyLastUsedRequest); } }); } /** * <p> * Retrieves information about when the specified access key was last * used. The information includes the date and time of last use, along * with the AWS service and region that were specified in the last * request made with that key. * </p> * * @param getAccessKeyLastUsedRequest Container for the necessary * parameters to execute the GetAccessKeyLastUsed operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * GetAccessKeyLastUsed service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetAccessKeyLastUsedResult> getAccessKeyLastUsedAsync( final GetAccessKeyLastUsedRequest getAccessKeyLastUsedRequest, final AsyncHandler<GetAccessKeyLastUsedRequest, GetAccessKeyLastUsedResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetAccessKeyLastUsedResult>() { public GetAccessKeyLastUsedResult call() throws Exception { GetAccessKeyLastUsedResult result; try { result = getAccessKeyLastUsed(getAccessKeyLastUsedRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(getAccessKeyLastUsedRequest, result); return result; } }); } /** * <p> * Lists the groups the specified user belongs to. * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listGroupsForUserRequest Container for the necessary parameters * to execute the ListGroupsForUser operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListGroupsForUser service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListGroupsForUserResult> listGroupsForUserAsync(final ListGroupsForUserRequest listGroupsForUserRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListGroupsForUserResult>() { public ListGroupsForUserResult call() throws Exception { return listGroupsForUser(listGroupsForUserRequest); } }); } /** * <p> * Lists the groups the specified user belongs to. * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listGroupsForUserRequest Container for the necessary parameters * to execute the ListGroupsForUser operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListGroupsForUser service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListGroupsForUserResult> listGroupsForUserAsync( final ListGroupsForUserRequest listGroupsForUserRequest, final AsyncHandler<ListGroupsForUserRequest, ListGroupsForUserResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListGroupsForUserResult>() { public ListGroupsForUserResult call() throws Exception { ListGroupsForUserResult result; try { result = listGroupsForUser(listGroupsForUserRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listGroupsForUserRequest, result); return result; } }); } /** * <p> * Creates a new version of the specified managed policy. To update a * managed policy, you create a new policy version. A managed policy can * have up to five versions. If the policy has five versions, you must * delete an existing version using DeletePolicyVersion before you create * a new version. * </p> * <p> * Optionally, you can set the new version as the policy's default * version. The default version is the operative version; that is, the * version that is in effect for the IAM users, groups, and roles that * the policy is attached to. * </p> * <p> * For more information about managed policy versions, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html"> Versioning for Managed Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param createPolicyVersionRequest Container for the necessary * parameters to execute the CreatePolicyVersion operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * CreatePolicyVersion service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreatePolicyVersionResult> createPolicyVersionAsync(final CreatePolicyVersionRequest createPolicyVersionRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreatePolicyVersionResult>() { public CreatePolicyVersionResult call() throws Exception { return createPolicyVersion(createPolicyVersionRequest); } }); } /** * <p> * Creates a new version of the specified managed policy. To update a * managed policy, you create a new policy version. A managed policy can * have up to five versions. If the policy has five versions, you must * delete an existing version using DeletePolicyVersion before you create * a new version. * </p> * <p> * Optionally, you can set the new version as the policy's default * version. The default version is the operative version; that is, the * version that is in effect for the IAM users, groups, and roles that * the policy is attached to. * </p> * <p> * For more information about managed policy versions, see * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html"> Versioning for Managed Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param createPolicyVersionRequest Container for the necessary * parameters to execute the CreatePolicyVersion operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * CreatePolicyVersion service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<CreatePolicyVersionResult> createPolicyVersionAsync( final CreatePolicyVersionRequest createPolicyVersionRequest, final AsyncHandler<CreatePolicyVersionRequest, CreatePolicyVersionResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<CreatePolicyVersionResult>() { public CreatePolicyVersionResult call() throws Exception { CreatePolicyVersionResult result; try { result = createPolicyVersion(createPolicyVersionRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(createPolicyVersionRequest, result); return result; } }); } /** * <p> * Adds the specified role to the specified instance profile. For more * information about roles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html"> Working with Roles </a> . For more information about instance profiles, go to <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html"> About Instance Profiles </a> * . * </p> * * @param addRoleToInstanceProfileRequest Container for the necessary * parameters to execute the AddRoleToInstanceProfile operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * AddRoleToInstanceProfile service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> addRoleToInstanceProfileAsync(final AddRoleToInstanceProfileRequest addRoleToInstanceProfileRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { addRoleToInstanceProfile(addRoleToInstanceProfileRequest); return null; } }); } /** * <p> * Adds the specified role to the specified instance profile. For more * information about roles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html"> Working with Roles </a> . For more information about instance profiles, go to <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html"> About Instance Profiles </a> * . * </p> * * @param addRoleToInstanceProfileRequest Container for the necessary * parameters to execute the AddRoleToInstanceProfile operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * AddRoleToInstanceProfile service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> addRoleToInstanceProfileAsync( final AddRoleToInstanceProfileRequest addRoleToInstanceProfileRequest, final AsyncHandler<AddRoleToInstanceProfileRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { addRoleToInstanceProfile(addRoleToInstanceProfileRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(addRoleToInstanceProfileRequest, null); return null; } }); } /** * <p> * Retrieves the specified inline policy document that is embedded in * the specified group. * </p> * <p> * A group can also have managed policies attached to it. To retrieve a * managed policy document that is attached to a group, use GetPolicy to * determine the policy's default version, then use GetPolicyVersion to * retrieve the policy document. * </p> * <p> * For more information about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param getGroupPolicyRequest Container for the necessary parameters to * execute the GetGroupPolicy operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * GetGroupPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetGroupPolicyResult> getGroupPolicyAsync(final GetGroupPolicyRequest getGroupPolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetGroupPolicyResult>() { public GetGroupPolicyResult call() throws Exception { return getGroupPolicy(getGroupPolicyRequest); } }); } /** * <p> * Retrieves the specified inline policy document that is embedded in * the specified group. * </p> * <p> * A group can also have managed policies attached to it. To retrieve a * managed policy document that is attached to a group, use GetPolicy to * determine the policy's default version, then use GetPolicyVersion to * retrieve the policy document. * </p> * <p> * For more information about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param getGroupPolicyRequest Container for the necessary parameters to * execute the GetGroupPolicy operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * GetGroupPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetGroupPolicyResult> getGroupPolicyAsync( final GetGroupPolicyRequest getGroupPolicyRequest, final AsyncHandler<GetGroupPolicyRequest, GetGroupPolicyResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetGroupPolicyResult>() { public GetGroupPolicyResult call() throws Exception { GetGroupPolicyResult result; try { result = getGroupPolicy(getGroupPolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(getGroupPolicyRequest, result); return result; } }); } /** * <p> * Retrieves the specified inline policy document that is embedded with * the specified role. * </p> * <p> * A role can also have managed policies attached to it. To retrieve a * managed policy document that is attached to a role, use GetPolicy to * determine the policy's default version, then use GetPolicyVersion to * retrieve the policy document. * </p> * <p> * For more information about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * For more information about roles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/roles-toplevel.html"> Using Roles to Delegate Permissions and Federate Identities </a> * . * </p> * * @param getRolePolicyRequest Container for the necessary parameters to * execute the GetRolePolicy operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * GetRolePolicy service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetRolePolicyResult> getRolePolicyAsync(final GetRolePolicyRequest getRolePolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetRolePolicyResult>() { public GetRolePolicyResult call() throws Exception { return getRolePolicy(getRolePolicyRequest); } }); } /** * <p> * Retrieves the specified inline policy document that is embedded with * the specified role. * </p> * <p> * A role can also have managed policies attached to it. To retrieve a * managed policy document that is attached to a role, use GetPolicy to * determine the policy's default version, then use GetPolicyVersion to * retrieve the policy document. * </p> * <p> * For more information about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * For more information about roles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/roles-toplevel.html"> Using Roles to Delegate Permissions and Federate Identities </a> * . * </p> * * @param getRolePolicyRequest Container for the necessary parameters to * execute the GetRolePolicy operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * GetRolePolicy service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetRolePolicyResult> getRolePolicyAsync( final GetRolePolicyRequest getRolePolicyRequest, final AsyncHandler<GetRolePolicyRequest, GetRolePolicyResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetRolePolicyResult>() { public GetRolePolicyResult call() throws Exception { GetRolePolicyResult result; try { result = getRolePolicy(getRolePolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(getRolePolicyRequest, result); return result; } }); } /** * <p> * Lists the instance profiles that have the specified associated role. * If there are none, the action returns an empty list. For more * information about instance profiles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html"> About Instance Profiles </a> * . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listInstanceProfilesForRoleRequest Container for the necessary * parameters to execute the ListInstanceProfilesForRole operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListInstanceProfilesForRole service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListInstanceProfilesForRoleResult> listInstanceProfilesForRoleAsync(final ListInstanceProfilesForRoleRequest listInstanceProfilesForRoleRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListInstanceProfilesForRoleResult>() { public ListInstanceProfilesForRoleResult call() throws Exception { return listInstanceProfilesForRole(listInstanceProfilesForRoleRequest); } }); } /** * <p> * Lists the instance profiles that have the specified associated role. * If there are none, the action returns an empty list. For more * information about instance profiles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html"> About Instance Profiles </a> * . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listInstanceProfilesForRoleRequest Container for the necessary * parameters to execute the ListInstanceProfilesForRole operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListInstanceProfilesForRole service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListInstanceProfilesForRoleResult> listInstanceProfilesForRoleAsync( final ListInstanceProfilesForRoleRequest listInstanceProfilesForRoleRequest, final AsyncHandler<ListInstanceProfilesForRoleRequest, ListInstanceProfilesForRoleResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListInstanceProfilesForRoleResult>() { public ListInstanceProfilesForRoleResult call() throws Exception { ListInstanceProfilesForRoleResult result; try { result = listInstanceProfilesForRole(listInstanceProfilesForRoleRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listInstanceProfilesForRoleRequest, result); return result; } }); } /** * <p> * Deletes the specified inline policy that is embedded in the specified * role. * </p> * <p> * A role can also have managed policies attached to it. To detach a * managed policy from a role, use DetachRolePolicy. For more information * about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param deleteRolePolicyRequest Container for the necessary parameters * to execute the DeleteRolePolicy operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * DeleteRolePolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteRolePolicyAsync(final DeleteRolePolicyRequest deleteRolePolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { deleteRolePolicy(deleteRolePolicyRequest); return null; } }); } /** * <p> * Deletes the specified inline policy that is embedded in the specified * role. * </p> * <p> * A role can also have managed policies attached to it. To detach a * managed policy from a role, use DetachRolePolicy. For more information * about policies, refer to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * * @param deleteRolePolicyRequest Container for the necessary parameters * to execute the DeleteRolePolicy operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * DeleteRolePolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<Void> deleteRolePolicyAsync( final DeleteRolePolicyRequest deleteRolePolicyRequest, final AsyncHandler<DeleteRolePolicyRequest, Void> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<Void>() { public Void call() throws Exception { try { deleteRolePolicy(deleteRolePolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(deleteRolePolicyRequest, null); return null; } }); } /** * <p> * Lists the virtual MFA devices under the AWS account by assignment * status. If you do not specify an assignment status, the action returns * a list of all virtual MFA devices. Assignment status can be * <code>Assigned</code> , <code>Unassigned</code> , or <code>Any</code> * . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listVirtualMFADevicesRequest Container for the necessary * parameters to execute the ListVirtualMFADevices operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListVirtualMFADevices service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListVirtualMFADevicesResult> listVirtualMFADevicesAsync(final ListVirtualMFADevicesRequest listVirtualMFADevicesRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListVirtualMFADevicesResult>() { public ListVirtualMFADevicesResult call() throws Exception { return listVirtualMFADevices(listVirtualMFADevicesRequest); } }); } /** * <p> * Lists the virtual MFA devices under the AWS account by assignment * status. If you do not specify an assignment status, the action returns * a list of all virtual MFA devices. Assignment status can be * <code>Assigned</code> , <code>Unassigned</code> , or <code>Any</code> * . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listVirtualMFADevicesRequest Container for the necessary * parameters to execute the ListVirtualMFADevices operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListVirtualMFADevices service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListVirtualMFADevicesResult> listVirtualMFADevicesAsync( final ListVirtualMFADevicesRequest listVirtualMFADevicesRequest, final AsyncHandler<ListVirtualMFADevicesRequest, ListVirtualMFADevicesResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListVirtualMFADevicesResult>() { public ListVirtualMFADevicesResult call() throws Exception { ListVirtualMFADevicesResult result; try { result = listVirtualMFADevices(listVirtualMFADevicesRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listVirtualMFADevicesRequest, result); return result; } }); } /** * <p> * Lists the names of the inline policies that are embedded in the * specified group. * </p> * <p> * A group can also have managed policies attached to it. To list the * managed policies that are attached to a group, use * ListAttachedGroupPolicies. For more information about policies, refer * to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. If there are no inline policies * embedded with the specified group, the action returns an empty list. * </p> * * @param listGroupPoliciesRequest Container for the necessary parameters * to execute the ListGroupPolicies operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListGroupPolicies service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListGroupPoliciesResult> listGroupPoliciesAsync(final ListGroupPoliciesRequest listGroupPoliciesRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListGroupPoliciesResult>() { public ListGroupPoliciesResult call() throws Exception { return listGroupPolicies(listGroupPoliciesRequest); } }); } /** * <p> * Lists the names of the inline policies that are embedded in the * specified group. * </p> * <p> * A group can also have managed policies attached to it. To list the * managed policies that are attached to a group, use * ListAttachedGroupPolicies. For more information about policies, refer * to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html"> Managed Policies and Inline Policies </a> * in the <i>IAM User Guide</i> . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. If there are no inline policies * embedded with the specified group, the action returns an empty list. * </p> * * @param listGroupPoliciesRequest Container for the necessary parameters * to execute the ListGroupPolicies operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListGroupPolicies service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListGroupPoliciesResult> listGroupPoliciesAsync( final ListGroupPoliciesRequest listGroupPoliciesRequest, final AsyncHandler<ListGroupPoliciesRequest, ListGroupPoliciesResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListGroupPoliciesResult>() { public ListGroupPoliciesResult call() throws Exception { ListGroupPoliciesResult result; try { result = listGroupPolicies(listGroupPoliciesRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listGroupPoliciesRequest, result); return result; } }); } /** * <p> * Lists the roles that have the specified path prefix. If there are * none, the action returns an empty list. For more information about * roles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html"> Working with Roles </a> * . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listRolesRequest Container for the necessary parameters to * execute the ListRoles operation on AmazonIdentityManagement. * * @return A Java Future object containing the response from the * ListRoles service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListRolesResult> listRolesAsync(final ListRolesRequest listRolesRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListRolesResult>() { public ListRolesResult call() throws Exception { return listRoles(listRolesRequest); } }); } /** * <p> * Lists the roles that have the specified path prefix. If there are * none, the action returns an empty list. For more information about * roles, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html"> Working with Roles </a> * . * </p> * <p> * You can paginate the results using the <code>MaxItems</code> and * <code>Marker</code> parameters. * </p> * * @param listRolesRequest Container for the necessary parameters to * execute the ListRoles operation on AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * ListRoles service method, as returned by AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<ListRolesResult> listRolesAsync( final ListRolesRequest listRolesRequest, final AsyncHandler<ListRolesRequest, ListRolesResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<ListRolesResult>() { public ListRolesResult call() throws Exception { ListRolesResult result; try { result = listRoles(listRolesRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(listRolesRequest, result); return result; } }); } /** * <p> * Retrieves the password policy for the AWS account. For more * information about using a password policy, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingPasswordPolicies.html"> Managing an IAM Password Policy </a> * . * </p> * * @param getAccountPasswordPolicyRequest Container for the necessary * parameters to execute the GetAccountPasswordPolicy operation on * AmazonIdentityManagement. * * @return A Java Future object containing the response from the * GetAccountPasswordPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetAccountPasswordPolicyResult> getAccountPasswordPolicyAsync(final GetAccountPasswordPolicyRequest getAccountPasswordPolicyRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetAccountPasswordPolicyResult>() { public GetAccountPasswordPolicyResult call() throws Exception { return getAccountPasswordPolicy(getAccountPasswordPolicyRequest); } }); } /** * <p> * Retrieves the password policy for the AWS account. For more * information about using a password policy, go to * <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingPasswordPolicies.html"> Managing an IAM Password Policy </a> * . * </p> * * @param getAccountPasswordPolicyRequest Container for the necessary * parameters to execute the GetAccountPasswordPolicy operation on * AmazonIdentityManagement. * @param asyncHandler Asynchronous callback handler for events in the * life-cycle of the request. Users could provide the implementation of * the four callback methods in this interface to process the operation * result or handle the exception. * * @return A Java Future object containing the response from the * GetAccountPasswordPolicy service method, as returned by * AmazonIdentityManagement. * * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonIdentityManagement indicating * either a problem with the data in the request, or a server side issue. */ public Future<GetAccountPasswordPolicyResult> getAccountPasswordPolicyAsync( final GetAccountPasswordPolicyRequest getAccountPasswordPolicyRequest, final AsyncHandler<GetAccountPasswordPolicyRequest, GetAccountPasswordPolicyResult> asyncHandler) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<GetAccountPasswordPolicyResult>() { public GetAccountPasswordPolicyResult call() throws Exception { GetAccountPasswordPolicyResult result; try { result = getAccountPasswordPolicy(getAccountPasswordPolicyRequest); } catch (Exception ex) { asyncHandler.onError(ex); throw ex; } asyncHandler.onSuccess(getAccountPasswordPolicyRequest, result); return result; } }); } }
sdole/aws-sdk-java
aws-java-sdk-iam/src/main/java/com/amazonaws/services/identitymanagement/AmazonIdentityManagementAsyncClient.java
Java
apache-2.0
531,838
/* * Copyright 2008 The Microlog project @sourceforge.net * 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.github.lisicnu.log4android.format.command; import com.github.lisicnu.log4android.Level; /** * Convert the <code>Level</code> to message. * * @author Johan Karlsson (johan.karlsson@jayway.se) */ public class PriorityFormatCommand implements FormatCommandInterface { /** * @see com.github.lisicnu.log4android.format.command.FormatCommandInterface#init(String) */ public void init(String initString){ // Do nothing. } /** * @see com.github.lisicnu.log4android.format.command.FormatCommandInterface#execute(String, * String, long, com.github.lisicnu.log4android.Level, Object, * Throwable) */ public String execute(String clientID, String name, long time, Level level, Object message, Throwable throwable){ String levelString = ""; if (level != null) { levelString = level.toString(); } return levelString; } }
lisicnu/Log4Android
src/main/java/com/github/lisicnu/log4android/format/command/PriorityFormatCommand.java
Java
apache-2.0
1,498
package com.logginghub.logging.frontend.configuration; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; @XmlAccessorType(XmlAccessType.FIELD) public class HighlighterConfiguration { @XmlAttribute private String colourHex; @XmlAttribute private String phrase; public String getColourHex() { return colourHex; } public String getPhrase() { return phrase; } public void setColourHex(String colourHex) { this.colourHex = colourHex; } public void setPhrase(String phrase) { this.phrase = phrase; } }
logginghub/core
logginghub-frontend/src/main/java/com/logginghub/logging/frontend/configuration/HighlighterConfiguration.java
Java
apache-2.0
719
/* * Copyright (C) 2014, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The Java Pathfinder core (jpf-core) platform is 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 gov.nasa.jpf.vm.bytecode; import gov.nasa.jpf.vm.*; /** * common machine independent type for all instance field access instructions */ public abstract class InstanceFieldInstruction extends FieldInstruction { protected int lastThis = MJIEnv.NULL; protected InstanceFieldInstruction (String fieldName, String classType, String fieldDescriptor){ super(fieldName, classType, fieldDescriptor); } public abstract int getObjectSlot (StackFrame frame); @Override public ElementInfo getElementInfo (ThreadInfo ti){ if (isCompleted(ti)){ return ti.getElementInfo(lastThis); } else { return peekElementInfo(ti); } } @Override public String toPostExecString(){ StringBuilder sb = new StringBuilder(); sb.append(getMnemonic()); sb.append(' '); sb.append( getLastElementInfo()); sb.append('.'); sb.append(fname); return sb.toString(); } @Override public FieldInfo getFieldInfo () { if (fi == null) { ClassInfo ci = ClassLoaderInfo.getCurrentResolvedClassInfo(className); if (ci != null) { fi = ci.getInstanceField(fname); } } return fi; } /** * NOTE - the return value is *only* valid in a instructionExecuted() context, since * the same instruction can be executed from different threads */ public int getLastThis() { return lastThis; } /** * since this is based on getLastThis(), the same context restrictions apply */ @Override public ElementInfo getLastElementInfo () { if (lastThis != MJIEnv.NULL) { return VM.getVM().getHeap().get(lastThis); // <2do> remove - should be in clients } return null; } public String getFieldDescriptor () { ElementInfo ei = getLastElementInfo(); FieldInfo fi = getFieldInfo(); return ei.toString() + '.' + fi.getName(); } }
parasoft-pl/jpf-core
main/src/main/java/gov/nasa/jpf/vm/bytecode/InstanceFieldInstruction.java
Java
apache-2.0
2,654
/** * 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.fuerve.villageelder.search; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.document.DateTools; import org.apache.lucene.queryparser.classic.CharStream; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.queryparser.classic.QueryParserTokenManager; import org.apache.lucene.search.NumericRangeQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermRangeQuery; import org.apache.lucene.util.Version; /** * This class parses Lucene-syntax search queries with special handling * for particular fields that behave a little differently than * QueryParser can understand on its own. Specifically, numeric and * date ranges are beyond Lucene's own QueryParser, so this thin wrapper * is necessary in order to implement them. * @author lparker * */ public class SearchQueryParser extends QueryParser { /** * Initializes a new instance of SearchQueryParser with an input stream. * @param stream The character stream from which to derive the query. */ public SearchQueryParser(CharStream stream) { super(stream); } /** * Initializes a new instance of SearchQueryParser with a token manager. * @param tm The token manager from which to parse the query. */ public SearchQueryParser(QueryParserTokenManager tm) { super(tm); } /** * Initializes a new instance of SearchQueryParser with a Lucene version, * a default field and an analyzer instance. * @param matchVersion The version of Lucene for which this query * should match expected behavior. * @param f The default field to search. * @param a The default analyzer to use when searching. */ public SearchQueryParser(Version matchVersion, String f, Analyzer a) { super(matchVersion, f, a); } /** * Called by Lucene's {@link QueryParserBase} to compose a range query when * a range field is detected in the input. This is overridden here in order * to provide special handling for specific fields. * @param field The name of the field for which the query is being composed. * @param part1 The lower bound of the specified numeric range. * @param part2 The upper bound of the specified numeric range. * @param startInclusive Determines whether the lower bound is inclusive. * @param endInclusive Determines whether the upper bound is inclusive. * @return The Lucene {@link Query} object appropriate for the requested * field. */ public Query getRangeQuery( final String field, final String part1, final String part2, final boolean startInclusive, final boolean endInclusive) throws ParseException { TermRangeQuery query = (TermRangeQuery) super.getRangeQuery( field, part1, part2, startInclusive, endInclusive); if ("RevisionNumber".equals(field)) { try { return NumericRangeQuery.newLongRange( field, Long.parseLong(part1), Long.parseLong(part2), startInclusive, endInclusive); } catch (NumberFormatException e) { return query; } } else if ("Date".equals(field)) { try { return NumericRangeQuery.newLongRange( field, DateTools.stringToTime(part1), DateTools.stringToTime(part2), startInclusive, endInclusive); } catch (java.text.ParseException e) { return query; } } return query; } }
fuerve/VillageElder
src/main/java/com/fuerve/villageelder/search/SearchQueryParser.java
Java
apache-2.0
4,626
/* * 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.ignite.internal.processors.odbc.jdbc; import java.sql.BatchUpdateException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Set; import java.util.SortedSet; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import javax.cache.configuration.Factory; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.cache.query.BulkLoadContextCursor; import org.apache.ignite.cache.query.FieldsQueryCursor; import org.apache.ignite.cache.query.QueryCancelledException; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.internal.IgniteInterruptedCheckedException; import org.apache.ignite.internal.IgniteVersionUtils; import org.apache.ignite.internal.binary.BinaryWriterExImpl; import org.apache.ignite.internal.jdbc.thin.JdbcThinPartitionAwarenessMappingGroup; import org.apache.ignite.internal.processors.affinity.AffinityAssignment; import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion; import org.apache.ignite.internal.processors.authentication.AuthorizationContext; import org.apache.ignite.internal.processors.bulkload.BulkLoadAckClientParameters; import org.apache.ignite.internal.processors.bulkload.BulkLoadProcessor; import org.apache.ignite.internal.processors.cache.DynamicCacheDescriptor; import org.apache.ignite.internal.processors.cache.GridCacheContext; import org.apache.ignite.internal.processors.cache.QueryCursorImpl; import org.apache.ignite.internal.processors.cache.mvcc.MvccUtils; import org.apache.ignite.internal.processors.cache.query.IgniteQueryErrorCode; import org.apache.ignite.internal.processors.cache.query.SqlFieldsQueryEx; import org.apache.ignite.internal.processors.odbc.ClientListenerProtocolVersion; import org.apache.ignite.internal.processors.odbc.ClientListenerRequest; import org.apache.ignite.internal.processors.odbc.ClientListenerRequestHandler; import org.apache.ignite.internal.processors.odbc.ClientListenerResponse; import org.apache.ignite.internal.processors.odbc.ClientListenerResponseSender; import org.apache.ignite.internal.processors.query.GridQueryCancel; import org.apache.ignite.internal.processors.query.IgniteSQLException; import org.apache.ignite.internal.processors.query.NestedTxMode; import org.apache.ignite.internal.processors.query.QueryUtils; import org.apache.ignite.internal.processors.query.SqlClientContext; import org.apache.ignite.internal.sql.optimizer.affinity.PartitionResult; import org.apache.ignite.internal.util.GridSpinBusyLock; import org.apache.ignite.internal.util.future.GridFutureAdapter; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.X; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.internal.util.worker.GridWorker; import org.apache.ignite.lang.IgniteBiTuple; import org.apache.ignite.transactions.TransactionAlreadyCompletedException; import org.apache.ignite.transactions.TransactionDuplicateKeyException; import org.apache.ignite.transactions.TransactionMixedModeException; import org.apache.ignite.transactions.TransactionSerializationException; import org.apache.ignite.transactions.TransactionUnsupportedConcurrencyException; import org.jetbrains.annotations.Nullable; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcBulkLoadBatchRequest.CMD_CONTINUE; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcBulkLoadBatchRequest.CMD_FINISHED_EOF; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcBulkLoadBatchRequest.CMD_FINISHED_ERROR; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcConnectionContext.VER_2_3_0; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcConnectionContext.VER_2_4_0; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcConnectionContext.VER_2_7_0; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcConnectionContext.VER_2_8_0; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequest.BATCH_EXEC; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequest.BATCH_EXEC_ORDERED; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequest.BULK_LOAD_BATCH; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequest.CACHE_PARTITIONS; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequest.META_COLUMNS; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequest.META_INDEXES; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequest.META_PARAMS; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequest.META_PRIMARY_KEYS; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequest.META_SCHEMAS; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequest.META_TABLES; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequest.QRY_CANCEL; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequest.QRY_CLOSE; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequest.QRY_EXEC; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequest.QRY_FETCH; import static org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequest.QRY_META; /** * JDBC request handler. */ public class JdbcRequestHandler implements ClientListenerRequestHandler { /** Jdbc query cancelled response. */ private static final JdbcResponse JDBC_QUERY_CANCELLED_RESPONSE = new JdbcResponse(IgniteQueryErrorCode.QUERY_CANCELED, QueryCancelledException.ERR_MSG); /** JDBC connection context. */ private final JdbcConnectionContext connCtx; /** Client context. */ private final SqlClientContext cliCtx; /** Logger. */ private final IgniteLogger log; /** Busy lock. */ private final GridSpinBusyLock busyLock; /** Worker. */ private final JdbcRequestHandlerWorker worker; /** Maximum allowed cursors. */ private final int maxCursors; /** Current JDBC cursors. */ private final ConcurrentHashMap<Long, JdbcCursor> jdbcCursors = new ConcurrentHashMap<>(); /** Ordered batches queue. */ private final PriorityQueue<JdbcOrderedBatchExecuteRequest> orderedBatchesQueue = new PriorityQueue<>(); /** Ordered batches mutex. */ private final Object orderedBatchesMux = new Object(); /** Request mutex. */ private final Object reqMux = new Object(); /** Response sender. */ private final ClientListenerResponseSender sender; /** Automatic close of cursors. */ private final boolean autoCloseCursors; /** Nested transactions handling mode. */ private final NestedTxMode nestedTxMode; /** Protocol version. */ private final ClientListenerProtocolVersion protocolVer; /** Authentication context */ private AuthorizationContext actx; /** Facade that hides transformations internal cache api entities -> jdbc metadata. */ private final JdbcMetadataInfo meta; /** Register that keeps non-cancelled requests. */ private Map<Long, JdbcQueryDescriptor> reqRegister = new HashMap<>(); /** * Constructor. * @param busyLock Shutdown latch. * @param sender Results sender. * @param maxCursors Maximum allowed cursors. * @param distributedJoins Distributed joins flag. * @param enforceJoinOrder Enforce join order flag. * @param collocated Collocated flag. * @param replicatedOnly Replicated only flag. * @param autoCloseCursors Flag to automatically close server cursors. * @param lazy Lazy query execution flag. * @param skipReducerOnUpdate Skip reducer on update flag. * @param dataPageScanEnabled Enable scan data page mode. * @param updateBatchSize Size of internal batch for DML queries. * @param actx Authentication context. * @param protocolVer Protocol version. * @param connCtx Jdbc connection context. */ public JdbcRequestHandler( GridSpinBusyLock busyLock, ClientListenerResponseSender sender, int maxCursors, boolean distributedJoins, boolean enforceJoinOrder, boolean collocated, boolean replicatedOnly, boolean autoCloseCursors, boolean lazy, boolean skipReducerOnUpdate, NestedTxMode nestedTxMode, @Nullable Boolean dataPageScanEnabled, @Nullable Integer updateBatchSize, AuthorizationContext actx, ClientListenerProtocolVersion protocolVer, JdbcConnectionContext connCtx ) { this.connCtx = connCtx; this.sender = sender; meta = new JdbcMetadataInfo(connCtx.kernalContext()); Factory<GridWorker> orderedFactory = new Factory<GridWorker>() { @Override public GridWorker create() { return new OrderedBatchWorker(); } }; cliCtx = new SqlClientContext( connCtx.kernalContext(), orderedFactory, distributedJoins, enforceJoinOrder, collocated, replicatedOnly, lazy, skipReducerOnUpdate, dataPageScanEnabled, updateBatchSize ); this.busyLock = busyLock; this.maxCursors = maxCursors; this.autoCloseCursors = autoCloseCursors; this.nestedTxMode = nestedTxMode; this.protocolVer = protocolVer; this.actx = actx; log = connCtx.kernalContext().log(getClass()); // TODO IGNITE-9484 Do not create worker if there is a possibility to unbind TX from threads. worker = new JdbcRequestHandlerWorker(connCtx.kernalContext().igniteInstanceName(), log, this, connCtx.kernalContext()); } /** {@inheritDoc} */ @Override public ClientListenerResponse handle(ClientListenerRequest req0) { assert req0 != null; assert req0 instanceof JdbcRequest; JdbcRequest req = (JdbcRequest)req0; if (!MvccUtils.mvccEnabled(connCtx.kernalContext())) return doHandle(req); else { GridFutureAdapter<ClientListenerResponse> fut = worker.process(req); try { return fut.get(); } catch (IgniteCheckedException e) { return exceptionToResult(e); } } } /** {@inheritDoc} */ @Override public boolean isCancellationCommand(int cmdId) { return cmdId == JdbcRequest.QRY_CANCEL; } /** {@inheritDoc} */ @Override public void registerRequest(long reqId, int cmdType) { assert reqId != 0; synchronized (reqMux) { if (isCancellationSupported() && (cmdType == QRY_EXEC || cmdType == BATCH_EXEC)) reqRegister.put(reqId, new JdbcQueryDescriptor()); } } /** {@inheritDoc} */ @Override public void unregisterRequest(long reqId) { assert reqId != 0; synchronized (reqMux) { if (isCancellationSupported()) reqRegister.remove(reqId); } } /** * Start worker, if it's present. */ void start() { if (worker != null) worker.start(); } /** * Actually handle the request. * @param req Request. * @return Request handling result. */ JdbcResponse doHandle(JdbcRequest req) { if (!busyLock.enterBusy()) return new JdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to handle JDBC request because node is stopping."); if (actx != null) AuthorizationContext.context(actx); JdbcResponse resp; try { switch (req.type()) { case QRY_EXEC: resp = executeQuery((JdbcQueryExecuteRequest)req); break; case QRY_FETCH: resp = fetchQuery((JdbcQueryFetchRequest)req); break; case QRY_CLOSE: resp = closeQuery((JdbcQueryCloseRequest)req); break; case QRY_META: resp = getQueryMeta((JdbcQueryMetadataRequest)req); break; case BATCH_EXEC: resp = executeBatch((JdbcBatchExecuteRequest)req); break; case BATCH_EXEC_ORDERED: resp = dispatchBatchOrdered((JdbcOrderedBatchExecuteRequest)req); break; case META_TABLES: resp = getTablesMeta((JdbcMetaTablesRequest)req); break; case META_COLUMNS: resp = getColumnsMeta((JdbcMetaColumnsRequest)req); break; case META_INDEXES: resp = getIndexesMeta((JdbcMetaIndexesRequest)req); break; case META_PARAMS: resp = getParametersMeta((JdbcMetaParamsRequest)req); break; case META_PRIMARY_KEYS: resp = getPrimaryKeys((JdbcMetaPrimaryKeysRequest)req); break; case META_SCHEMAS: resp = getSchemas((JdbcMetaSchemasRequest)req); break; case BULK_LOAD_BATCH: resp = processBulkLoadFileBatch((JdbcBulkLoadBatchRequest)req); break; case QRY_CANCEL: resp = cancelQuery((JdbcQueryCancelRequest)req); break; case CACHE_PARTITIONS: resp = getCachePartitions((JdbcCachePartitionsRequest)req); break; default: resp = new JdbcResponse(IgniteQueryErrorCode.UNSUPPORTED_OPERATION, "Unsupported JDBC request [req=" + req + ']'); } if (resp != null) resp.activeTransaction(connCtx.kernalContext().cache().context().tm().inUserTx()); return resp; } finally { AuthorizationContext.clear(); busyLock.leaveBusy(); } } /** * @param req Ordered batch request. * @return Response. */ private JdbcResponse dispatchBatchOrdered(JdbcOrderedBatchExecuteRequest req) { if (!cliCtx.isStreamOrdered()) executeBatchOrdered(req); else { synchronized (orderedBatchesMux) { orderedBatchesQueue.add(req); orderedBatchesMux.notifyAll(); } } return null; } /** * @param req Ordered batch request. * @return Response. */ private ClientListenerResponse executeBatchOrdered(JdbcOrderedBatchExecuteRequest req) { try { if (req.isLastStreamBatch()) cliCtx.waitTotalProcessedOrderedRequests(req.order()); JdbcResponse resp = executeBatch(req); if (resp.response() instanceof JdbcBatchExecuteResult) { resp = new JdbcResponse( new JdbcOrderedBatchExecuteResult((JdbcBatchExecuteResult)resp.response(), req.order())); } sender.send(resp); } catch (Exception e) { U.error(null, "Error processing file batch", e); sender.send(new JdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Server error: " + e)); } cliCtx.orderedRequestProcessed(); return null; } /** * Processes a file batch sent from client as part of bulk load COPY command. * * @param req Request object with a batch of a file received from client. * @return Response to send to the client. */ private JdbcResponse processBulkLoadFileBatch(JdbcBulkLoadBatchRequest req) { if (connCtx.kernalContext() == null) return new JdbcResponse(IgniteQueryErrorCode.UNEXPECTED_OPERATION, "Unknown query ID: " + req.cursorId() + ". Bulk load session may have been reclaimed due to timeout."); JdbcBulkLoadProcessor processor = (JdbcBulkLoadProcessor)jdbcCursors.get(req.cursorId()); if (!prepareQueryCancellationMeta(processor)) return JDBC_QUERY_CANCELLED_RESPONSE; boolean unregisterReq = false; try { processor.processBatch(req); switch (req.cmd()) { case CMD_FINISHED_ERROR: case CMD_FINISHED_EOF: jdbcCursors.remove(req.cursorId()); processor.close(); unregisterReq = true; break; case CMD_CONTINUE: break; default: throw new IllegalArgumentException(); } return resultToResonse(new JdbcQueryExecuteResult(req.cursorId(), processor.updateCnt(), null)); } catch (Exception e) { U.error(null, "Error processing file batch", e); if (X.cause(e, QueryCancelledException.class) != null) return exceptionToResult(new QueryCancelledException()); else return new JdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Server error: " + e); } finally { cleanupQueryCancellationMeta(unregisterReq, processor.requestId()); } } /** {@inheritDoc} */ @Override public ClientListenerResponse handleException(Exception e, ClientListenerRequest req) { return exceptionToResult(e); } /** {@inheritDoc} */ @Override public void writeHandshake(BinaryWriterExImpl writer) { // Handshake OK. writer.writeBoolean(true); // Write server version. writer.writeByte(IgniteVersionUtils.VER.major()); writer.writeByte(IgniteVersionUtils.VER.minor()); writer.writeByte(IgniteVersionUtils.VER.maintenance()); writer.writeString(IgniteVersionUtils.VER.stage()); writer.writeLong(IgniteVersionUtils.VER.revisionTimestamp()); writer.writeByteArray(IgniteVersionUtils.VER.revisionHash()); // Write node id. if (protocolVer.compareTo(VER_2_8_0) >= 0) writer.writeUuid(connCtx.kernalContext().localNodeId()); } /** * Called whenever client is disconnected due to correct connection close * or due to {@code IOException} during network operations. */ public void onDisconnect() { if (worker != null) { worker.cancel(); try { worker.join(); } catch (InterruptedException e) { // No-op. } } for (JdbcCursor cursor : jdbcCursors.values()) U.close(cursor, log); jdbcCursors.clear(); synchronized (reqMux) { reqRegister.clear(); } U.close(cliCtx, log); } /** * {@link JdbcQueryExecuteRequest} command handler. * * @param req Execute query request. * @return Response. */ @SuppressWarnings("unchecked") private JdbcResponse executeQuery(JdbcQueryExecuteRequest req) { GridQueryCancel cancel = null; boolean unregisterReq = false; if (isCancellationSupported()) { synchronized (reqMux) { JdbcQueryDescriptor desc = reqRegister.get(req.requestId()); // Query was already cancelled and unregistered. if (desc == null) return null; cancel = desc.cancelHook(); desc.incrementUsageCount(); } } try { int cursorCnt = jdbcCursors.size(); if (maxCursors > 0 && cursorCnt >= maxCursors) return new JdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Too many open cursors (either close other " + "open cursors or increase the limit through " + "ClientConnectorConfiguration.maxOpenCursorsPerConnection) [maximum=" + maxCursors + ", current=" + cursorCnt + ']'); assert !cliCtx.isStream(); String sql = req.sqlQuery(); SqlFieldsQueryEx qry; switch (req.expectedStatementType()) { case ANY_STATEMENT_TYPE: qry = new SqlFieldsQueryEx(sql, null); break; case SELECT_STATEMENT_TYPE: qry = new SqlFieldsQueryEx(sql, true); break; default: assert req.expectedStatementType() == JdbcStatementType.UPDATE_STMT_TYPE; qry = new SqlFieldsQueryEx(sql, false); if (cliCtx.isSkipReducerOnUpdate()) ((SqlFieldsQueryEx)qry).setSkipReducerOnUpdate(true); } setupQuery(qry, prepareSchemaName(req.schemaName())); qry.setArgs(req.arguments()); qry.setAutoCommit(req.autoCommit()); if (req.pageSize() <= 0) return new JdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Invalid fetch size: " + req.pageSize()); qry.setPageSize(req.pageSize()); String schemaName = req.schemaName(); if (F.isEmpty(schemaName)) schemaName = QueryUtils.DFLT_SCHEMA; qry.setSchema(schemaName); List<FieldsQueryCursor<List<?>>> results = connCtx.kernalContext().query().querySqlFields(null, qry, cliCtx, true, protocolVer.compareTo(VER_2_3_0) < 0, cancel); FieldsQueryCursor<List<?>> fieldsCur = results.get(0); if (fieldsCur instanceof BulkLoadContextCursor) { BulkLoadContextCursor blCur = (BulkLoadContextCursor)fieldsCur; BulkLoadProcessor blProcessor = blCur.bulkLoadProcessor(); BulkLoadAckClientParameters clientParams = blCur.clientParams(); JdbcBulkLoadProcessor processor = new JdbcBulkLoadProcessor(blProcessor, req.requestId()); jdbcCursors.put(processor.cursorId(), processor); // responses for the same query on the client side return resultToResonse(new JdbcBulkLoadAckResult(processor.cursorId(), clientParams)); } if (results.size() == 1) { JdbcQueryCursor cur = new JdbcQueryCursor(req.pageSize(), req.maxRows(), (QueryCursorImpl)fieldsCur, req.requestId()); jdbcCursors.put(cur.cursorId(), cur); cur.openIterator(); JdbcQueryExecuteResult res; PartitionResult partRes = ((QueryCursorImpl<List<?>>)fieldsCur).partitionResult(); if (cur.isQuery()) res = new JdbcQueryExecuteResult(cur.cursorId(), cur.fetchRows(), !cur.hasNext(), isClientPartitionAwarenessApplicable(req.partitionResponseRequest(), partRes) ? partRes : null); else { List<List<Object>> items = cur.fetchRows(); assert items != null && items.size() == 1 && items.get(0).size() == 1 && items.get(0).get(0) instanceof Long : "Invalid result set for not-SELECT query. [qry=" + sql + ", res=" + S.toString(List.class, items) + ']'; res = new JdbcQueryExecuteResult(cur.cursorId(), (Long)items.get(0).get(0), isClientPartitionAwarenessApplicable(req.partitionResponseRequest(), partRes) ? partRes : null); } if (res.last() && (!res.isQuery() || autoCloseCursors)) { jdbcCursors.remove(cur.cursorId()); unregisterReq = true; cur.close(); } return resultToResonse(res); } else { List<JdbcResultInfo> jdbcResults = new ArrayList<>(results.size()); List<List<Object>> items = null; boolean last = true; for (FieldsQueryCursor<List<?>> c : results) { QueryCursorImpl qryCur = (QueryCursorImpl)c; JdbcResultInfo jdbcRes; if (qryCur.isQuery()) { JdbcQueryCursor cur = new JdbcQueryCursor(req.pageSize(), req.maxRows(), qryCur, req.requestId()); jdbcCursors.put(cur.cursorId(), cur); jdbcRes = new JdbcResultInfo(true, -1, cur.cursorId()); cur.openIterator(); if (items == null) { items = cur.fetchRows(); last = cur.hasNext(); } } else jdbcRes = new JdbcResultInfo(false, (Long)((List<?>)qryCur.getAll().get(0)).get(0), -1); jdbcResults.add(jdbcRes); } return resultToResonse(new JdbcQueryExecuteMultipleStatementsResult(jdbcResults, items, last)); } } catch (Exception e) { // Trying to close all cursors of current request. clearCursors(req.requestId()); unregisterReq = true; U.error(log, "Failed to execute SQL query [reqId=" + req.requestId() + ", req=" + req + ']', e); if (X.cause(e, QueryCancelledException.class) != null) return exceptionToResult(new QueryCancelledException()); else return exceptionToResult(e); } finally { cleanupQueryCancellationMeta(unregisterReq, req.requestId()); } } /** * {@link JdbcQueryCloseRequest} command handler. * * @param req Execute query request. * @return Response. */ private JdbcResponse closeQuery(JdbcQueryCloseRequest req) { JdbcCursor cur = jdbcCursors.get(req.cursorId()); if (!prepareQueryCancellationMeta(cur)) return new JdbcResponse(null); try { cur = jdbcCursors.remove(req.cursorId()); if (cur == null) return new JdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to find query cursor with ID: " + req.cursorId()); cur.close(); return new JdbcResponse(null); } catch (Exception e) { jdbcCursors.remove(req.cursorId()); U.error(log, "Failed to close SQL query [reqId=" + req.requestId() + ", req=" + req + ']', e); if (X.cause(e, QueryCancelledException.class) != null) return new JdbcResponse(null); else return exceptionToResult(e); } finally { if (isCancellationSupported()) { boolean clearCursors = false; synchronized (reqMux) { assert cur != null; JdbcQueryDescriptor desc = reqRegister.get(cur.requestId()); if (desc != null) { // Query was cancelled during execution. if (desc.isCanceled()) { clearCursors = true; unregisterRequest(req.requestId()); } else { tryUnregisterRequest(cur.requestId()); desc.decrementUsageCount(); } } } if (clearCursors) clearCursors(cur.requestId()); } } } /** * {@link JdbcQueryFetchRequest} command handler. * * @param req Execute query request. * @return Response. */ private JdbcResponse fetchQuery(JdbcQueryFetchRequest req) { final JdbcQueryCursor cur = (JdbcQueryCursor)jdbcCursors.get(req.cursorId()); if (!prepareQueryCancellationMeta(cur)) return JDBC_QUERY_CANCELLED_RESPONSE; boolean unregisterReq = false; try { if (cur == null) return new JdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to find query cursor with ID: " + req.cursorId()); if (req.pageSize() <= 0) return new JdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Invalid fetch size : [fetchSize=" + req.pageSize() + ']'); cur.pageSize(req.pageSize()); JdbcQueryFetchResult res = new JdbcQueryFetchResult(cur.fetchRows(), !cur.hasNext()); if (res.last() && (!cur.isQuery() || autoCloseCursors)) { jdbcCursors.remove(req.cursorId()); unregisterReq = true; cur.close(); } return resultToResonse(res); } catch (Exception e) { U.error(log, "Failed to fetch SQL query result [reqId=" + req.requestId() + ", req=" + req + ']', e); if (X.cause(e, QueryCancelledException.class) != null) return exceptionToResult(new QueryCancelledException()); else return exceptionToResult(e); } finally { assert cur != null; cleanupQueryCancellationMeta(unregisterReq, cur.requestId()); } } /** * @param req Request. * @return Response. */ private JdbcResponse getQueryMeta(JdbcQueryMetadataRequest req) { final JdbcQueryCursor cur = (JdbcQueryCursor)jdbcCursors.get(req.cursorId()); if (!prepareQueryCancellationMeta(cur)) return JDBC_QUERY_CANCELLED_RESPONSE; try { if (cur == null) return new JdbcResponse(IgniteQueryErrorCode.UNKNOWN, "Failed to find query cursor with ID: " + req.cursorId()); JdbcQueryMetadataResult res = new JdbcQueryMetadataResult(req.cursorId(), cur.meta()); return resultToResonse(res); } catch (Exception e) { U.error(log, "Failed to fetch SQL query result [reqId=" + req.requestId() + ", req=" + req + ']', e); return exceptionToResult(e); } finally { assert cur != null; cleanupQueryCancellationMeta(false, cur.requestId()); } } /** * @param req Request. * @return Response. */ private JdbcResponse executeBatch(JdbcBatchExecuteRequest req) { GridQueryCancel cancel = null; // Skip request register check for ORDERED batches (JDBC streams) // because ordered batch requests are processed asynchronously at the // separate thread. if (isCancellationSupported() && req.type() == BATCH_EXEC) { synchronized (reqMux) { JdbcQueryDescriptor desc = reqRegister.get(req.requestId()); // Query was already cancelled and unregisterd. if (desc == null) return null; cancel = desc.cancelHook(); desc.incrementUsageCount(); } } try { String schemaName = prepareSchemaName(req.schemaName()); int qryCnt = req.queries().size(); List<Integer> updCntsAcc = new ArrayList<>(qryCnt); // Send back only the first error. Others will be written to the log. IgniteBiTuple<Integer, String> firstErr = new IgniteBiTuple<>(); SqlFieldsQueryEx qry = null; for (JdbcQuery q : req.queries()) { if (q.sql() != null) { // If we have a new query string in the batch, if (qry != null) // then execute the previous sub-batch and create a new SqlFieldsQueryEx. executeBatchedQuery(qry, updCntsAcc, firstErr, cancel); qry = new SqlFieldsQueryEx(q.sql(), false); setupQuery(qry, schemaName); qry.setAutoCommit(req.autoCommit()); } assert qry != null; qry.addBatchedArgs(q.args()); } if (qry != null) executeBatchedQuery(qry, updCntsAcc, firstErr, cancel); if (req.isLastStreamBatch()) cliCtx.disableStreaming(); int updCnts[] = U.toIntArray(updCntsAcc); return firstErr.isEmpty() ? resultToResonse( new JdbcBatchExecuteResult(updCnts, ClientListenerResponse.STATUS_SUCCESS, null)) : resultToResonse(new JdbcBatchExecuteResult(updCnts, firstErr.getKey(), firstErr.getValue())); } catch (QueryCancelledException e) { return exceptionToResult(e); } finally { cleanupQueryCancellationMeta(true, req.requestId()); } } /** * Normalize schema name. * * @param schemaName Schema name. * @return Normalized schema name. */ private static String prepareSchemaName(@Nullable String schemaName) { if (F.isEmpty(schemaName)) schemaName = QueryUtils.DFLT_SCHEMA; return schemaName; } /** * Sets up query object with settings from current client context state and handler state. * * @param qry Query to setup. * @param schemaName Schema name. */ private void setupQuery(SqlFieldsQueryEx qry, String schemaName) { qry.setDistributedJoins(cliCtx.isDistributedJoins()); qry.setEnforceJoinOrder(cliCtx.isEnforceJoinOrder()); qry.setCollocated(cliCtx.isCollocated()); qry.setReplicatedOnly(cliCtx.isReplicatedOnly()); qry.setLazy(cliCtx.isLazy()); qry.setNestedTxMode(nestedTxMode); qry.setSchema(schemaName); qry.setTimeout(0, TimeUnit.MILLISECONDS); if (cliCtx.updateBatchSize() != null) qry.setUpdateBatchSize(cliCtx.updateBatchSize()); } /** * Executes query and updates result counters. * * @param qry Query. * @param updCntsAcc Per query rows updates counter. * @param firstErr First error data - code and message. * @param cancel Hook for query cancellation. * @throws QueryCancelledException If query was cancelled during execution. */ @SuppressWarnings({"ForLoopReplaceableByForEach"}) private void executeBatchedQuery(SqlFieldsQueryEx qry, List<Integer> updCntsAcc, IgniteBiTuple<Integer, String> firstErr, GridQueryCancel cancel) throws QueryCancelledException { try { if (cliCtx.isStream()) { List<Long> cnt = connCtx.kernalContext().query().streamBatchedUpdateQuery( qry.getSchema(), cliCtx, qry.getSql(), qry.batchedArguments() ); for (int i = 0; i < cnt.size(); i++) updCntsAcc.add(cnt.get(i).intValue()); return; } List<FieldsQueryCursor<List<?>>> qryRes = connCtx.kernalContext().query().querySqlFields( null, qry, cliCtx, true, true, cancel); for (FieldsQueryCursor<List<?>> cur : qryRes) { if (cur instanceof BulkLoadContextCursor) throw new IgniteSQLException("COPY command cannot be executed in batch mode."); assert !((QueryCursorImpl)cur).isQuery(); Iterator<List<?>> it = cur.iterator(); if (it.hasNext()) { int val = ((Long)it.next().get(0)).intValue(); updCntsAcc.add(val); } } } catch (Exception e) { int code; String msg; if (X.cause(e, QueryCancelledException.class) != null) throw new QueryCancelledException(); else if (e instanceof IgniteSQLException) { BatchUpdateException batchCause = X.cause(e, BatchUpdateException.class); if (batchCause != null) { int[] updCntsOnErr = batchCause.getUpdateCounts(); for (int i = 0; i < updCntsOnErr.length; i++) updCntsAcc.add(updCntsOnErr[i]); msg = batchCause.getMessage(); code = batchCause.getErrorCode(); } else { for (int i = 0; i < qry.batchedArguments().size(); i++) updCntsAcc.add(Statement.EXECUTE_FAILED); msg = e.getMessage(); code = ((IgniteSQLException)e).statusCode(); } } else { for (int i = 0; i < qry.batchedArguments().size(); i++) updCntsAcc.add(Statement.EXECUTE_FAILED); msg = e.getMessage(); code = IgniteQueryErrorCode.UNKNOWN; } if (firstErr.isEmpty()) firstErr.set(code, msg); else U.error(log, "Failed to execute batch query [qry=" + qry + ']', e); } } /** * @param req Get tables metadata request. * @return Response. */ private JdbcResponse getTablesMeta(JdbcMetaTablesRequest req) { try { List<JdbcTableMeta> tabMetas = meta.getTablesMeta(req.schemaName(), req.tableName(), req.tableTypes()); JdbcMetaTablesResult res = new JdbcMetaTablesResult(tabMetas); return resultToResonse(res); } catch (Exception e) { U.error(log, "Failed to get tables metadata [reqId=" + req.requestId() + ", req=" + req + ']', e); return exceptionToResult(e); } } /** * @param req Get columns metadata request. * @return Response. */ private JdbcResponse getColumnsMeta(JdbcMetaColumnsRequest req) { try { Collection<JdbcColumnMeta> colsMeta = meta.getColumnsMeta(protocolVer, req.schemaName(), req.tableName(), req.columnName()); JdbcMetaColumnsResult res; if (protocolVer.compareTo(VER_2_7_0) >= 0) res = new JdbcMetaColumnsResultV4(colsMeta); else if (protocolVer.compareTo(VER_2_4_0) >= 0) res = new JdbcMetaColumnsResultV3(colsMeta); else if (protocolVer.compareTo(VER_2_3_0) >= 0) res = new JdbcMetaColumnsResultV2(colsMeta); else res = new JdbcMetaColumnsResult(colsMeta); return resultToResonse(res); } catch (Exception e) { U.error(log, "Failed to get columns metadata [reqId=" + req.requestId() + ", req=" + req + ']', e); return exceptionToResult(e); } } /** * @param req Request. * @return Response. */ private JdbcResponse getIndexesMeta(JdbcMetaIndexesRequest req) { try { Collection<JdbcIndexMeta> idxInfos = meta.getIndexesMeta(req.schemaName(), req.tableName()); return resultToResonse(new JdbcMetaIndexesResult(idxInfos)); } catch (Exception e) { U.error(log, "Failed to get parameters metadata [reqId=" + req.requestId() + ", req=" + req + ']', e); return exceptionToResult(e); } } /** * @param req Request. * @return Response. */ private JdbcResponse getParametersMeta(JdbcMetaParamsRequest req) { String schemaName = prepareSchemaName(req.schemaName()); SqlFieldsQueryEx qry = new SqlFieldsQueryEx(req.sql(), null); setupQuery(qry, schemaName); try { List<JdbcParameterMeta> meta = connCtx.kernalContext().query().getIndexing(). parameterMetaData(schemaName, qry); JdbcMetaParamsResult res = new JdbcMetaParamsResult(meta); return resultToResonse(res); } catch (Exception e) { U.error(log, "Failed to get parameters metadata [reqId=" + req.requestId() + ", req=" + req + ']', e); return exceptionToResult(e); } } /** * @param req Request. * @return Response. */ private JdbcResponse getPrimaryKeys(JdbcMetaPrimaryKeysRequest req) { try { Collection<JdbcPrimaryKeyMeta> pkMeta = meta.getPrimaryKeys(req.schemaName(), req.tableName()); return resultToResonse(new JdbcMetaPrimaryKeysResult(pkMeta)); } catch (Exception e) { U.error(log, "Failed to get parameters metadata [reqId=" + req.requestId() + ", req=" + req + ']', e); return exceptionToResult(e); } } /** * @param req Request. * @return Response. */ private JdbcResponse getSchemas(JdbcMetaSchemasRequest req) { try { String schemaPtrn = req.schemaName(); SortedSet<String> schemas = meta.getSchemasMeta(schemaPtrn); return resultToResonse(new JdbcMetaSchemasResult(schemas)); } catch (Exception e) { U.error(log, "Failed to get schemas metadata [reqId=" + req.requestId() + ", req=" + req + ']', e); return exceptionToResult(e); } } /** * Create {@link JdbcResponse} bearing appropriate Ignite specific result code if possible * from given {@link Exception}. * * @param e Exception to convert. * @return resulting {@link JdbcResponse}. */ private JdbcResponse exceptionToResult(Exception e) { if (e instanceof QueryCancelledException) return new JdbcResponse(IgniteQueryErrorCode.QUERY_CANCELED, e.getMessage()); if (e instanceof TransactionSerializationException) return new JdbcResponse(IgniteQueryErrorCode.TRANSACTION_SERIALIZATION_ERROR, e.getMessage()); if (e instanceof TransactionAlreadyCompletedException) return new JdbcResponse(IgniteQueryErrorCode.TRANSACTION_COMPLETED, e.getMessage()); if (e instanceof TransactionDuplicateKeyException) return new JdbcResponse(IgniteQueryErrorCode.DUPLICATE_KEY, e.getMessage()); if (e instanceof TransactionMixedModeException) return new JdbcResponse(IgniteQueryErrorCode.TRANSACTION_TYPE_MISMATCH, e.getMessage()); if (e instanceof TransactionUnsupportedConcurrencyException) return new JdbcResponse(IgniteQueryErrorCode.UNSUPPORTED_OPERATION, e.getMessage()); if (e instanceof IgniteSQLException) return new JdbcResponse(((IgniteSQLException)e).statusCode(), e.getMessage()); else return new JdbcResponse(IgniteQueryErrorCode.UNKNOWN, e.getMessage()); } /** * Ordered batch worker. */ private class OrderedBatchWorker extends GridWorker { /** * Constructor. */ OrderedBatchWorker() { super(connCtx.kernalContext().igniteInstanceName(), "ordered-batch", JdbcRequestHandler.this.log); } /** {@inheritDoc} */ @Override protected void body() throws InterruptedException, IgniteInterruptedCheckedException { long nextBatchOrder = 0; while (true) { if (!cliCtx.isStream()) return; JdbcOrderedBatchExecuteRequest req; synchronized (orderedBatchesMux) { req = orderedBatchesQueue.peek(); if (req == null || req.order() != nextBatchOrder) { orderedBatchesMux.wait(); continue; } else orderedBatchesQueue.poll(); } executeBatchOrdered(req); nextBatchOrder++; } } } /** * Cancels query with specified request id; * * @param req Query cancellation request; * @return <code>QueryCancelledException</code> wrapped with <code>JdbcResponse</code> */ private JdbcResponse cancelQuery(JdbcQueryCancelRequest req) { boolean clearCursors = false; GridQueryCancel cancelHook; synchronized (reqMux) { JdbcQueryDescriptor desc = reqRegister.get(req.requestIdToBeCancelled()); // Query was already executed. if (desc == null) return null; // Query was registered, however execution didn't start yet. else if (!desc.isExecutionStarted()) { unregisterRequest(req.requestId()); return exceptionToResult(new QueryCancelledException()); } else { cancelHook = desc.cancelHook(); desc.markCancelled(); if (desc.usageCount() == 0) { clearCursors = true; unregisterRequest(req.requestIdToBeCancelled()); } } } cancelHook.cancel(); if (clearCursors) clearCursors(req.requestIdToBeCancelled()); return null; } /** * Retrieve cache partitions distributions for given cache Ids. * * @param req <code>JdbcCachePartitionsRequest</code> that incapsulates set of cache Ids. * @return Partitions distributions. */ private JdbcResponse getCachePartitions(JdbcCachePartitionsRequest req) { List<JdbcThinPartitionAwarenessMappingGroup> mappings = new ArrayList<>(); AffinityTopologyVersion topVer = connCtx.kernalContext().cache().context().exchange().readyAffinityVersion(); for (int cacheId : req.cacheIds()) { Map<UUID, Set<Integer>> partitionsMap = getPartitionsMap( connCtx.kernalContext().cache().cacheDescriptor(cacheId), topVer); mappings.add(new JdbcThinPartitionAwarenessMappingGroup(cacheId, partitionsMap)); } return new JdbcResponse(new JdbcCachePartitionsResult(mappings), topVer); } /** * Get partition map for a cache. * @param cacheDesc Cache descriptor. * @return Partitions mapping for cache. */ private Map<UUID, Set<Integer>> getPartitionsMap(DynamicCacheDescriptor cacheDesc, AffinityTopologyVersion affVer) { GridCacheContext cacheCtx = connCtx.kernalContext().cache().context().cacheContext(cacheDesc.cacheId()); AffinityAssignment assignment = cacheCtx.affinity().assignment(affVer); Set<ClusterNode> nodes = assignment.primaryPartitionNodes(); HashMap<UUID, Set<Integer>> res = new HashMap<>(nodes.size()); for (ClusterNode node : nodes) { UUID nodeId = node.id(); Set<Integer> parts = assignment.primaryPartitions(nodeId); res.put(nodeId, parts); } return res; } /** * Checks whether query cancellation is supported whithin given version of protocal. * * @return True if supported, false otherwise. */ @Override public boolean isCancellationSupported() { return (protocolVer.compareTo(VER_2_8_0) >= 0); } /** * Unregisters request if there are no cursors binded to it. * * @param reqId Reuest to unregist. */ private void tryUnregisterRequest(long reqId) { assert isCancellationSupported(); boolean unregisterReq = true; for (JdbcCursor cursor : jdbcCursors.values()) { if (cursor.requestId() == reqId) { unregisterReq = false; break; } } if (unregisterReq) unregisterRequest(reqId); } /** * Tries to close all cursors of request with given id and removes them from jdbcCursors map. * * @param reqId Request ID. */ private void clearCursors(long reqId) { for (Iterator<Map.Entry<Long, JdbcCursor>> it = jdbcCursors.entrySet().iterator(); it.hasNext(); ) { Map.Entry<Long, JdbcCursor> entry = it.next(); JdbcCursor cursor = entry.getValue(); if (cursor.requestId() == reqId) { try { cursor.close(); } catch (Exception e) { U.error(log, "Failed to close cursor [reqId=" + reqId + ", cursor=" + cursor + ']', e); } it.remove(); } } } /** * Checks whether query was cancelled - returns null if true, otherwise increments query descriptor usage count. * * @param cur Jdbc Cursor. * @return False, if query was already cancelled. */ private boolean prepareQueryCancellationMeta(JdbcCursor cur) { if (isCancellationSupported()) { // Nothing to do - cursor was already removed. if (cur == null) return false; synchronized (reqMux) { JdbcQueryDescriptor desc = reqRegister.get(cur.requestId()); // Query was already cancelled and unregisterd. if (desc == null) return false; desc.incrementUsageCount(); } } return true; } /** * Cleanups cursors or processors and unregistered request if necessary. * * @param unregisterReq Flag, that detecs whether it's necessary to unregister request. * @param reqId Request Id. */ private void cleanupQueryCancellationMeta(boolean unregisterReq, long reqId) { if (isCancellationSupported()) { boolean clearCursors = false; synchronized (reqMux) { JdbcQueryDescriptor desc = reqRegister.get(reqId); if (desc != null) { // Query was cancelled during execution. if (desc.isCanceled()) { clearCursors = true; unregisterReq = true; } else desc.decrementUsageCount(); if (unregisterReq) unregisterRequest(reqId); } } if (clearCursors) clearCursors(reqId); } } /** * Create {@link JdbcResponse} wrapping given result and attaching affinity topology version to it if chaned. * * @param res Jdbc result. * @return esulting {@link JdbcResponse}. */ private JdbcResponse resultToResonse(JdbcResult res) { return new JdbcResponse(res, connCtx.getAffinityTopologyVersionIfChanged()); } /** * @param partResRequested Boolean flag that signals whether client requested partiton result. * @param partRes Direved partition result. * @return True if applicable to jdbc thin client side partition awareness: * 1. Partitoin result was requested; * 2. Partition result either null or * a. Rendezvous affinity function without map filters was used; * b. Partition result tree neither PartitoinAllNode nor PartitionNoneNode; */ private static boolean isClientPartitionAwarenessApplicable(boolean partResRequested, PartitionResult partRes) { return partResRequested && (partRes == null || partRes.isClientPartitionAwarenessApplicable()); } /** {@inheritDoc} */ @Override public ClientListenerProtocolVersion protocolVersion() { return protocolVer; } }
andrey-kuznetsov/ignite
modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/jdbc/JdbcRequestHandler.java
Java
apache-2.0
53,003
/* * Copyright 2014-2016 See AUTHORS file. * * 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.kotcrab.vis.editor.module.project; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; /** * Generic editor project, that does not really on any game framework. * @author Kotcrab */ public class ProjectGeneric extends Project { /** absolute path */ private transient String visDirectory; /** absolute path */ private String assetsOutput; public ProjectGeneric (String visDirectory, String assetsOutput) { this.visDirectory = visDirectory; this.assetsOutput = assetsOutput; } @Override public void updateRoot (FileHandle projectDataFile) { visDirectory = projectDataFile.parent().path(); } @Override public String verifyIfCorrect () { return null; } @Override public FileHandle getVisDirectory () { return Gdx.files.absolute(visDirectory); } @Override public FileHandle getAssetOutputDirectory () { return Gdx.files.absolute(assetsOutput); } @Override public String getRecentProjectDisplayName () { return Gdx.files.absolute(visDirectory).name(); } }
piotr-j/VisEditor
editor/src/main/java/com/kotcrab/vis/editor/module/project/ProjectGeneric.java
Java
apache-2.0
1,630
/** * Copyright Notice * * This is a work of the U.S. Government and is not subject to copyright * protection in the United States. Foreign copyrights may apply. * * 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 gov.va.isaac.interfaces.gui.constants; /** * {@link SharedServiceNames} * * These values are used as the @Named annotation on some service implementations - they are useful while distinguishing * when there are multiple implementations of a particular service - for example - a docked view, and a stand-along popup * view. * * @author <a href="mailto:daniel.armbrust.list@gmail.com">Dan Armbrust</a> */ public class SharedServiceNames { public static final String DOCKED = "Docked"; public static final String MODERN_STYLE = "ModernStyle"; public static final String LEGACY_STYLE = "LegacyStyle"; public static final String USCRS = "USCRS"; public static final String LOINC = "LOINC"; }
DongwonChoi/ISAAC
isaac-app-interfaces/src/main/java/gov/va/isaac/interfaces/gui/constants/SharedServiceNames.java
Java
apache-2.0
1,448
package org.henjue.library.share.manager; import android.content.Context; import android.text.TextUtils; import android.widget.Toast; import com.tencent.mm.opensdk.modelmsg.SendAuth; import com.tencent.mm.opensdk.openapi.IWXAPI; import com.tencent.mm.opensdk.openapi.WXAPIFactory; import org.henjue.library.share.AuthListener; import org.henjue.library.share.R; import org.henjue.library.share.ShareSDK; /** * Created by echo on 5/19/15. */ public class WechatAuthManager implements IAuthManager { private static final String SCOPE = "snsapi_userinfo"; private static final String STATE = "lls_engzo_wechat_login"; private String mWeChatAppId; private static IWXAPI mIWXAPI; private static AuthListener mAuthListener; WechatAuthManager(Context context) { mWeChatAppId = ShareSDK.getInstance().getWechatAppId(); if (!TextUtils.isEmpty(mWeChatAppId)) { mIWXAPI = WXAPIFactory.createWXAPI(context, mWeChatAppId, true); if (!mIWXAPI.isWXAppInstalled()) { Toast.makeText(context, R.string.share_install_wechat_tips, Toast.LENGTH_SHORT).show(); return; } else { mIWXAPI.registerApp(mWeChatAppId); } } } public static IWXAPI getIWXAPI() { return mIWXAPI; } public static AuthListener getPlatformActionListener() { return mAuthListener; } @Override public void login(AuthListener authListener) { if (mIWXAPI != null) { final SendAuth.Req req = new SendAuth.Req(); req.scope = SCOPE; req.state = STATE; mIWXAPI.sendReq(req); mAuthListener = authListener; } } }
henjue/sharesdk
library/src/main/java/org/henjue/library/share/manager/WechatAuthManager.java
Java
apache-2.0
1,806
package org.bibi.boot03; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class Boot03ApplicationTests { @Test public void contextLoads() { } }
bibi-git/springboot
boot03/src/test/java/org/bibi/boot03/Boot03ApplicationTests.java
Java
apache-2.0
332
/** * NumberValue.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.google.api.ads.dfp.v201208; /** * Contains a numeric value. */ public class NumberValue extends com.google.api.ads.dfp.v201208.Value implements java.io.Serializable { /* The numeric value represented as a string. */ private java.lang.String value; public NumberValue() { } public NumberValue( java.lang.String valueType, java.lang.String value) { super( valueType); this.value = value; } /** * Gets the value value for this NumberValue. * * @return value * The numeric value represented as a string. */ public java.lang.String getValue() { return value; } /** * Sets the value value for this NumberValue. * * @param value * The numeric value represented as a string. */ public void setValue(java.lang.String value) { this.value = value; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof NumberValue)) return false; NumberValue other = (NumberValue) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj) && ((this.value==null && other.getValue()==null) || (this.value!=null && this.value.equals(other.getValue()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); if (getValue() != null) { _hashCode += getValue().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(NumberValue.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201208", "NumberValue")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("value"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201208", "value")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
google-code-export/google-api-dfp-java
src/com/google/api/ads/dfp/v201208/NumberValue.java
Java
apache-2.0
3,839
package com.vijaysharma.ehyo.core.models; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.List; import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.ByteArrayOutputStream; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import com.vijaysharma.ehyo.core.utils.UncheckedIoException; public class ResourceDocument implements AsListOfStrings { public static ResourceDocument read( File file ) { try { SAXBuilder builder = new SAXBuilder(); if ( file.exists() ) { return new ResourceDocument(builder.build(file)); } else { StringBuilder empty = new StringBuilder(); empty.append("<resources>"); empty.append("</resources>"); ByteArrayInputStream inputStream = new ByteArrayInputStream(empty.toString().getBytes()); return new ResourceDocument(builder.build(inputStream)); } } catch (IOException ioe) { throw new UncheckedIoException(ioe); } catch (JDOMException jde) { throw new RuntimeException(jde); } } private final Document resource; public ResourceDocument(Document resource) { this.resource = resource; } public void add(ResourceDocument toMerge) { Element root = resource.getRootElement(); for( Element element : toMerge.resource.getRootElement().getChildren() ) { root.addContent(element.clone()); } } @Override public List<String> toListOfStrings() { try { XMLOutputter xmlOutput = new XMLOutputter(); xmlOutput.setFormat(Format.getPrettyFormat()); ByteArrayOutputStream stream = new ByteArrayOutputStream(); xmlOutput.output(resource, stream); return IOUtils.readLines(new ByteArrayInputStream(stream.toByteArray())); } catch ( IOException ioe ) { throw new UncheckedIoException(ioe); } } }
vijaysharm/ehyo-android
src/main/java/com/vijaysharma/ehyo/core/models/ResourceDocument.java
Java
apache-2.0
1,930
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.documentation; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.ex.http.HttpFileSystem; import com.intellij.util.SmartList; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; public class PlatformDocumentationUtil { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.documentation.PlatformDocumentationUtil"); private static final @NonNls Pattern ourLtFixupPattern = Pattern.compile("<([^/^\\w^!])"); private static final @NonNls Pattern ourToQuote = Pattern.compile("[\\\\\\.\\^\\$\\?\\*\\+\\|\\)\\}\\]\\{\\(\\[]"); private static final @NonNls String LT_ENTITY = "&lt;"; @Nullable public static List<String> getHttpRoots(@NotNull String[] roots, String relPath) { List<String> result = new SmartList<String>(); for (String root : roots) { VirtualFile virtualFile = VirtualFileManager.getInstance().findFileByUrl(root); if (virtualFile != null) { if (virtualFile.getFileSystem() instanceof HttpFileSystem) { String url = virtualFile.getUrl(); if (!url.endsWith("/")) { url += "/"; } result.add(url + relPath); } else { VirtualFile file = virtualFile.findFileByRelativePath(relPath); if (file != null) { result.add(file.getUrl()); } } } } return result.isEmpty() ? null : result; } private static String quote(String x) { if (ourToQuote.matcher(x).find()) { return "\\" + x; } return x; } public static String fixupText(String docText) { Matcher fixupMatcher = ourLtFixupPattern.matcher(docText); LinkedList<String> secondSymbols = new LinkedList<String>(); while (fixupMatcher.find()) { String s = fixupMatcher.group(1); //[db] that's workaround to avoid internal bug if (!s.equals("\\") && !secondSymbols.contains(s)) { secondSymbols.addFirst(s); } } for (String s : secondSymbols) { String pattern = "<" + quote(s); try { docText = Pattern.compile(pattern).matcher(docText).replaceAll(LT_ENTITY + pattern); } catch (PatternSyntaxException e) { LOG.error("Pattern syntax exception on " + pattern); } } return docText; } }
diorcety/intellij-community
platform/core-impl/src/com/intellij/codeInsight/documentation/PlatformDocumentationUtil.java
Java
apache-2.0
3,272
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.amplifybackend.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.amplifybackend.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * GetTokenResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetTokenResultJsonUnmarshaller implements Unmarshaller<GetTokenResult, JsonUnmarshallerContext> { public GetTokenResult unmarshall(JsonUnmarshallerContext context) throws Exception { GetTokenResult getTokenResult = new GetTokenResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return getTokenResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("appId", targetDepth)) { context.nextToken(); getTokenResult.setAppId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("challengeCode", targetDepth)) { context.nextToken(); getTokenResult.setChallengeCode(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("sessionId", targetDepth)) { context.nextToken(); getTokenResult.setSessionId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("ttl", targetDepth)) { context.nextToken(); getTokenResult.setTtl(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return getTokenResult; } private static GetTokenResultJsonUnmarshaller instance; public static GetTokenResultJsonUnmarshaller getInstance() { if (instance == null) instance = new GetTokenResultJsonUnmarshaller(); return instance; } }
aws/aws-sdk-java
aws-java-sdk-amplifybackend/src/main/java/com/amazonaws/services/amplifybackend/model/transform/GetTokenResultJsonUnmarshaller.java
Java
apache-2.0
3,455
package de.holisticon.servlet4demo.serverglassfish; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.PushBuilder; @WebServlet(value = {"/http2"}) public class Http2Servlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=UTF-8"); PushBuilder pushBuilder = req.newPushBuilder(); if (pushBuilder != null) { pushBuilder .path("images/cat.jpg") .addHeader("content-type", "image/jpeg") .push(); pushBuilder .path("http2-json") .addHeader("content-type", "application/json") .push(); } try (PrintWriter respWriter = resp.getWriter()) { respWriter.write(new StringBuilder() .append("<html>") .append("<img src='images/cat.jpg'>") .append("<p>Image by <a href=\"https://flic.kr/p/HPf9R1\">") .append("Andy Miccone</a></p>") .append("<p>License: <a href=\"https://creativecommons.org/") .append("publicdomain/zero/1.0/\">") .append("CC0 1.0 Universal (CC0 1.0) \n") .append("Public Domain Dedication</a></p>") .append("</html>") .toString()); } } }
janweinschenker/servlet4-demo
server-glassfish/src/main/java/de/holisticon/servlet4demo/serverglassfish/Http2Servlet.java
Java
apache-2.0
1,539
/** * 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.camel.spring.processor.tracing; import java.util.List; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.processor.interceptor.TraceHandlerTestHandler; import org.apache.camel.processor.interceptor.Tracer; import org.apache.camel.spring.SpringTestSupport; public abstract class TracingTestBase extends SpringTestSupport { protected List<StringBuilder> getTracedMessages() { Tracer tracer = (Tracer) this.applicationContext.getBean("tracer"); TraceHandlerTestHandler handler = (TraceHandlerTestHandler) tracer.getTraceHandler(); return handler.getEventMessages(); } protected void prepareTestTracerExceptionInOut() { } protected void validateTestTracerExceptionInOut() { List<StringBuilder> tracedMessages = getTracedMessages(); assertEquals(7, tracedMessages.size()); for (StringBuilder tracedMessage : tracedMessages) { String message = tracedMessage.toString(); assertTrue(message.startsWith("In")); assertTrue(message.contains("Out:")); } assertTrue(tracedMessages.get(4).toString().contains("Ex:")); } protected int getMessageCount() { return getTracedMessages().size(); } public void testTracerExceptionInOut() throws Exception { MockEndpoint result = getMockEndpoint("mock:result"); ((Tracer) context.getDefaultTracer()).setTraceOutExchanges(true); result.expectedMessageCount(3); prepareTestTracerExceptionInOut(); template.sendBody("direct:start", "Hello World"); template.sendBody("direct:start", "Bye World"); try { template.sendBody("direct:start", "Kaboom"); fail("Should have thrown exception"); } catch (Exception e) { // expected } template.sendBody("direct:start", "Hello Camel"); assertMockEndpointsSatisfied(); validateTestTracerExceptionInOut(); } }
everttigchelaar/camel-svn
components/camel-spring/src/test/java/org/apache/camel/spring/processor/tracing/TracingTestBase.java
Java
apache-2.0
2,882
package com.seiche.strike; import java.util.ArrayList; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; public class Player { //Player Parameters //Movement and position private int x = 100; private int y = 100; private int dx = 0; private int dy = 0; private boolean firstRun = true; //Animation private Bitmap myShip[] = new Bitmap[3]; private int cell = 0; //Shooting variables private boolean shoot = false; private int canShoot = 50; private Bitmap bulletImg; private ArrayList<PlayerBullet> bulletArray; //Constructor takes in the view as a condition to allocate resources public Player(Surface v){ myShip[0] = BitmapFactory.decodeResource(v.getResources(), R.drawable.plane01); myShip[1] = BitmapFactory.decodeResource(v.getResources(), R.drawable.plane02); myShip[2] = BitmapFactory.decodeResource(v.getResources(), R.drawable.plane03); bulletImg = BitmapFactory.decodeResource(v.getResources(), R.drawable.bullet); bulletArray = new ArrayList<PlayerBullet>(); } //Moves and draws the player bitmap public void draw(Canvas c, int w, int h){ if(firstRun){ x = w/2; y = h/2; firstRun = false; } x += dx; y += dy; if(y < 0) y = 0; cell++; if(cell > 2) cell = 0; c.drawBitmap(myShip[cell], x-32, y-32, null); shoot(c); } public void shoot(Canvas c){ canShoot++; if(shoot && canShoot > 5){ canShoot = 0; bulletArray.add(new PlayerBullet(x, y-20)); } for(int i = 0; i < bulletArray.size(); i++){ bulletArray.get(i).move(); int yTemp = bulletArray.get(i).getY(); c.drawBitmap(bulletImg, bulletArray.get(i).getX()-16, yTemp, null); if(yTemp < -16) bulletArray.remove(i); } } //Sets the movement variables depending on the input of the touch screen x and y //values by dividing the displacement by the hypotenuse of the resulting triangle public void setDisplace(int xInput, int yInput){ int hypo = (int)Math.sqrt(xInput*xInput + yInput*yInput); hypo = hypo/50; dx = (int)(xInput - x)/hypo; dy = (int)(yInput - y)/hypo; } //Sets the plane to shooting state or not depending on ACTION_DOWN or ACTION_UP state public void setShoot(boolean set){ shoot = set; } //Returns the movement vector to zero on ACTION_UP public void setImobile(){ dx = 0; dy = 0; } public ArrayList<PlayerBullet> getArray(){ return bulletArray; } public void removeBullet(int index){ bulletArray.get(index).remove(); } }
seiche/SimpleConcept
src/com/seiche/strike/Player.java
Java
apache-2.0
2,645
package org.deeplearning4j.parallelism; import lombok.NonNull; import org.deeplearning4j.datasets.iterator.AsyncDataSetIterator; import org.deeplearning4j.datasets.iterator.AsyncMultiDataSetIterator; import org.deeplearning4j.datasets.iterator.impl.ListDataSetIterator; import org.deeplearning4j.nn.api.Model; import org.deeplearning4j.nn.api.Updater; import org.deeplearning4j.nn.conf.MultiLayerConfiguration; import org.deeplearning4j.nn.graph.ComputationGraph; import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; import org.deeplearning4j.nn.updater.graph.ComputationGraphUpdater; import org.deeplearning4j.optimize.api.IterationListener; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.api.ops.executioner.GridExecutioner; import org.nd4j.linalg.dataset.api.DataSet; import org.nd4j.linalg.dataset.api.MultiDataSet; import org.nd4j.linalg.dataset.api.iterator.DataSetIterator; import org.nd4j.linalg.dataset.api.iterator.MultiDataSetIterator; import org.nd4j.linalg.factory.Nd4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** * This is simple data-parallel wrapper suitable for multi-cpu/multi-gpu environments. * * @author raver119@gmail.com */ public class ParallelWrapper implements AutoCloseable { private static Logger logger = LoggerFactory.getLogger(ParallelWrapper.class); private Model model; private int workers = 2; private int prefetchSize = 2; private int averagingFrequency = 1; private Trainer zoo[]; private AtomicLong iterationsCounter = new AtomicLong(0); private boolean reportScore = false; private boolean averageUpdaters = true; private boolean legacyAveraging = false; protected ParallelWrapper(Model model, int workers, int prefetchSize) { this.model = model; this.workers = workers; this.prefetchSize = prefetchSize; if (this.model instanceof MultiLayerNetwork) { ((MultiLayerNetwork) this.model).getUpdater(); } else if (this.model instanceof ComputationGraph) { ((ComputationGraph) this.model).getUpdater(); } zoo = new Trainer[workers]; for (int cnt = 0; cnt < workers; cnt++) { zoo[cnt] = new Trainer(cnt, model); zoo[cnt].start(); } } @Override public void close() throws Exception { if (zoo != null) { for (int i = 0; i < zoo.length; i++) { if (zoo[i] != null) zoo[i].shutdown(); } zoo = null; } } /** * This method causes all threads used for parallel training to stop */ public synchronized void shutdown() { try { close(); } catch (Exception e) { throw new RuntimeException(e); } } public synchronized void fit(@NonNull MultiDataSetIterator source) { if (zoo == null) { zoo = new Trainer[workers]; for (int cnt = 0; cnt < workers; cnt++) { // we pass true here, to tell Trainer to use MultiDataSet queue for training zoo[cnt] = new Trainer(cnt, model, true); zoo[cnt].start(); } } else { for (int cnt = 0; cnt < workers; cnt++) { zoo[cnt].useMDS = true; } } source.reset(); MultiDataSetIterator iterator; if (prefetchSize > 0 && source.asyncSupported()) { iterator = new AsyncMultiDataSetIterator(source, prefetchSize); } else iterator = source; AtomicInteger locker = new AtomicInteger(0); while (iterator.hasNext()) { MultiDataSet dataSet = iterator.next(); /* now dataSet should be dispatched to next free workers, until all workers are busy. And then we should block till all finished. */ int pos = locker.getAndIncrement(); zoo[pos].feedMultiDataSet(dataSet); /* if all workers are dispatched now, join till all are finished */ if (pos + 1 == workers || !iterator.hasNext()) { iterationsCounter.incrementAndGet(); for (int cnt = 0; cnt < workers && cnt < locker.get(); cnt ++) { try { zoo[cnt].waitTillRunning(); } catch (Exception e) { throw new RuntimeException(e); } } /* average model, and propagate it to whole */ if (iterationsCounter.get() % averagingFrequency == 0 && pos + 1 == workers) { double score = 0.0; if (!legacyAveraging || Nd4j.getAffinityManager().getNumberOfDevices() == 1) { List<INDArray> params = new ArrayList<>(); for (int cnt = 0; cnt < workers && cnt < locker.get(); cnt++) { params.add(zoo[cnt].getModel().params()); score += zoo[cnt].getModel().score(); } Nd4j.averageAndPropagate(model.params(), params); } else { INDArray params = Nd4j.zeros(model.params().shape()); int cnt = 0; for (; cnt < workers && cnt < locker.get(); cnt++) { params.addi(zoo[cnt].getModel().params()); score += zoo[cnt].getModel().score(); } params.divi(cnt); model.setParams(params); } score /= Math.min(workers, locker.get()); // TODO: improve this if (reportScore) logger.info("Averaged score: " + score); // averaging updaters state if (model instanceof ComputationGraph) { if (averageUpdaters) { ComputationGraphUpdater updater = ((ComputationGraph) model).getUpdater(); if (updater != null && updater.getStateViewArray() != null) { if (!legacyAveraging || Nd4j.getAffinityManager().getNumberOfDevices() == 1) { List<INDArray> updaters = new ArrayList<>(); for (int cnt = 0; cnt < workers && cnt < locker.get(); cnt++) { updaters.add(((ComputationGraph) zoo[cnt].getModel()).getUpdater().getStateViewArray()); } Nd4j.averageAndPropagate(updater.getStateViewArray(), updaters); } else { INDArray state = Nd4j.zeros(updater.getStateViewArray().shape()); int cnt = 0; for (; cnt < workers && cnt < locker.get(); cnt++) { state.addi(((ComputationGraph) zoo[cnt].getModel()).getUpdater().getStateViewArray()); } state.divi(cnt); updater.setStateViewArray(state); } } } ((ComputationGraph) model).setScore(score); } else throw new RuntimeException("MultiDataSet might be used only with ComputationGraph model"); if (legacyAveraging && Nd4j.getAffinityManager().getNumberOfDevices() > 1) { for (int cnt = 0; cnt < workers; cnt++) { zoo[cnt].updateModel(model); } } } locker.set(0); } } logger.debug("Iterations passed: {}", iterationsCounter.get()); iterationsCounter.set(0); } /** * This method takes DataSetIterator, and starts training over it by scheduling DataSets to different executors * * @param source */ public synchronized void fit(@NonNull DataSetIterator source) { if (zoo == null) { zoo = new Trainer[workers]; for (int cnt = 0; cnt < workers; cnt++) { zoo[cnt] = new Trainer(cnt, model); zoo[cnt].start(); } } source.reset(); DataSetIterator iterator; if (prefetchSize > 0 && source.asyncSupported()) { iterator = new AsyncDataSetIterator(source, prefetchSize); } else iterator = source; AtomicInteger locker = new AtomicInteger(0); while (iterator.hasNext()) { DataSet dataSet = iterator.next(); /* now dataSet should be dispatched to next free workers, until all workers are busy. And then we should block till all finished. */ int pos = locker.getAndIncrement(); zoo[pos].feedDataSet(dataSet); /* if all workers are dispatched now, join till all are finished */ if (pos + 1 == workers || !iterator.hasNext()) { iterationsCounter.incrementAndGet(); for (int cnt = 0; cnt < workers && cnt < locker.get(); cnt ++) { try { zoo[cnt].waitTillRunning(); } catch (Exception e) { throw new RuntimeException(e); } } /* average model, and propagate it to whole */ if (iterationsCounter.get() % averagingFrequency == 0 && pos + 1 == workers) { double score = 0.0; if (!legacyAveraging || Nd4j.getAffinityManager().getNumberOfDevices() == 1) { List<INDArray> params = new ArrayList<>(); for (int cnt = 0; cnt < workers && cnt < locker.get(); cnt++) { params.add(zoo[cnt].getModel().params()); score += zoo[cnt].getModel().score(); } Nd4j.averageAndPropagate(model.params(), params); } else { INDArray params = Nd4j.zeros(model.params().shape()); int cnt = 0; for (; cnt < workers && cnt < locker.get(); cnt++) { params.addi(zoo[cnt].getModel().params()); score += zoo[cnt].getModel().score(); } params.divi(cnt); model.setParams(params); } score /= Math.min(workers, locker.get()); // TODO: improve this if (reportScore) logger.info("Averaged score: " + score); // averaging updaters state if (model instanceof MultiLayerNetwork) { if (averageUpdaters) { Updater updater = ((MultiLayerNetwork) model).getUpdater(); if (updater != null && updater.getStateViewArray() != null) { if (!legacyAveraging || Nd4j.getAffinityManager().getNumberOfDevices() == 1) { List<INDArray> updaters = new ArrayList<>(); for (int cnt = 0; cnt < workers && cnt < locker.get(); cnt++) { updaters.add(((MultiLayerNetwork) zoo[cnt].getModel()).getUpdater().getStateViewArray()); } Nd4j.averageAndPropagate(updater.getStateViewArray(), updaters); } else { INDArray state = Nd4j.zeros(updater.getStateViewArray().shape()); int cnt = 0; for (; cnt < workers && cnt < locker.get(); cnt++) { state.addi(((MultiLayerNetwork) zoo[cnt].getModel()).getUpdater().getStateViewArray().dup()); } state.divi(cnt); updater.setStateViewArray((MultiLayerNetwork) model, state, false); } } } ((MultiLayerNetwork) model).setScore(score); } else if (model instanceof ComputationGraph) { if (averageUpdaters) { ComputationGraphUpdater updater = ((ComputationGraph) model).getUpdater(); if (updater != null && updater.getStateViewArray() != null) { if (!legacyAveraging || Nd4j.getAffinityManager().getNumberOfDevices() == 1) { List<INDArray> updaters = new ArrayList<>(); for (int cnt = 0; cnt < workers && cnt < locker.get(); cnt++) { updaters.add(((ComputationGraph) zoo[cnt].getModel()).getUpdater().getStateViewArray()); } Nd4j.averageAndPropagate(updater.getStateViewArray(), updaters); } else { INDArray state = Nd4j.zeros(updater.getStateViewArray().shape()); int cnt = 0; for (; cnt < workers && cnt < locker.get(); cnt++) { state.addi(((ComputationGraph) zoo[cnt].getModel()).getUpdater().getStateViewArray()); } state.divi(cnt); updater.setStateViewArray(state); } } } ((ComputationGraph) model).setScore(score); } if (legacyAveraging && Nd4j.getAffinityManager().getNumberOfDevices() > 1) { for (int cnt = 0; cnt < workers; cnt++) { zoo[cnt].updateModel(model); } } } locker.set(0); } } logger.debug("Iterations passed: {}", iterationsCounter.get()); iterationsCounter.set(0); } public static class Builder { private Model model; private int workers = 2; private int prefetchSize = 16; private int averagingFrequency = 1; private boolean reportScore = false; private boolean averageUpdaters = true; private boolean legacyAveraging = true; /** * Build ParallelWrapper for MultiLayerNetwork * * @param mln */ public Builder(@NonNull MultiLayerNetwork mln) { model = mln; } /** * Build ParallelWrapper for ComputationGraph * * @param graph */ public Builder(@NonNull ComputationGraph graph) { model = graph; } /** * This method allows to configure number of workers that'll be used for parallel training * * @param num * @return */ public Builder workers(int num) { if (num < 2) throw new RuntimeException("Number of workers can't be lower then 2!"); this.workers = num; return this; } /** * Model averaging frequency. * * @param freq number of iterations between averagin * @return */ public Builder averagingFrequency(int freq) { this.averagingFrequency = freq; return this; } /** * This method enables/disables updaters averaging. * * Default value: TRUE * * PLEASE NOTE: This method is suitable for debugging purposes mostly. So don't change default value, unless you're sure why you need it. * * @param reallyAverage * @return */ public Builder averageUpdaters(boolean reallyAverage) { this.averageUpdaters = reallyAverage; return this; } /** * Size of prefetch buffer that will be used for background data prefetching. * Usually it's better to keep this value equal to the number of workers. * * Default value: 2 * * @param size 0 to disable prefetching, any positive number * @return */ public Builder prefetchBuffer(int size) { if (size < 0) size = 0; this.prefetchSize = size; return this; } /** * If set to true, legacy averaging method is used. This might be used as fallback on multi-gpu systems without P2P access available. * * Default value: false * * @param reallyUse * @return */ public Builder useLegacyAveraging(boolean reallyUse) { this.legacyAveraging = reallyUse; return this; } /** * This method enables/disables averaged model score reporting * * @param reallyReport * @return */ public Builder reportScoreAfterAveraging(boolean reallyReport) { this.reportScore = reallyReport; return this; } /** * This method returns ParallelWrapper instance * * @return */ public ParallelWrapper build() { ParallelWrapper wrapper = new ParallelWrapper(model, workers, prefetchSize); wrapper.averagingFrequency = this.averagingFrequency; wrapper.reportScore = this.reportScore; wrapper.averageUpdaters = this.averageUpdaters; wrapper.legacyAveraging = this.legacyAveraging; return wrapper; } } private static class Trainer extends Thread implements Runnable { private Model originalModel; private Model replicatedModel; private LinkedBlockingQueue<DataSet> queue = new LinkedBlockingQueue<>(); private LinkedBlockingQueue<MultiDataSet> queueMDS = new LinkedBlockingQueue<>(); private AtomicInteger running = new AtomicInteger(0); private int threadId; private AtomicBoolean shouldUpdate = new AtomicBoolean(false); private AtomicBoolean shouldStop = new AtomicBoolean(false); private Exception thrownException; private volatile boolean useMDS = false; public Trainer(int threadId, Model model, boolean useMDS) { this(threadId, model); this.useMDS = useMDS; } public Trainer(int threadId, Model model) { this.threadId = threadId; this.setDaemon(true); this.setName("ParallelWrapper trainer " + threadId); this.originalModel = model; if (model instanceof MultiLayerNetwork) { // if (threadId != 0) // ((MultiLayerNetwork)this.replicatedModel).setListeners(new ArrayList<IterationListener>()); } else if (model instanceof ComputationGraph) { this.replicatedModel = ((ComputationGraph) model).clone(); if (threadId != 0) ((ComputationGraph)this.replicatedModel).setListeners(new ArrayList<IterationListener>()); } } public void feedMultiDataSet(@NonNull MultiDataSet dataSet) { running.incrementAndGet(); queueMDS.add(dataSet); } public void feedDataSet(@NonNull DataSet dataSet) { running.incrementAndGet(); queue.add(dataSet); } public Model getModel() { return replicatedModel; } public void updateModel(@NonNull Model model) { this.shouldUpdate.set(true); if (replicatedModel instanceof MultiLayerNetwork) { replicatedModel.setParams(model.params().dup()); Updater updater = ((MultiLayerNetwork) model).getUpdater(); INDArray view = updater.getStateViewArray(); if (view != null) { updater = ((MultiLayerNetwork) replicatedModel).getUpdater(); INDArray viewD = view.dup(); if (Nd4j.getExecutioner() instanceof GridExecutioner) ((GridExecutioner) Nd4j.getExecutioner()).flushQueueBlocking(); updater.setStateViewArray((MultiLayerNetwork) replicatedModel, viewD, false); } } else if (replicatedModel instanceof ComputationGraph) { replicatedModel.setParams(model.params().dup()); ComputationGraphUpdater updater = ((ComputationGraph) model).getUpdater(); INDArray view = updater.getStateViewArray(); if (view != null) { INDArray viewD = view.dup(); if (Nd4j.getExecutioner() instanceof GridExecutioner) ((GridExecutioner) Nd4j.getExecutioner()).flushQueueBlocking(); updater = ((ComputationGraph) replicatedModel).getUpdater(); updater.setStateViewArray(viewD); } } if (Nd4j.getExecutioner() instanceof GridExecutioner) ((GridExecutioner) Nd4j.getExecutioner()).flushQueueBlocking(); } public boolean isRunning(){ // if Trainer thread got exception during training - rethrow it here if (thrownException != null) throw new RuntimeException(thrownException); return running.get() == 0; } public void shutdown() { shouldStop.set(true); } @Override public void run() { try { // we create fresh network, with the same configuration, as initially created by user // however, we don't need clone or anything here if (originalModel instanceof MultiLayerNetwork) { MultiLayerConfiguration conf = ((MultiLayerNetwork) originalModel).getLayerWiseConfigurations().clone(); this.replicatedModel = new MultiLayerNetwork(conf); ((MultiLayerNetwork) replicatedModel).init(); } else if (originalModel instanceof ComputationGraph) { this.replicatedModel = new ComputationGraph(((ComputationGraph) originalModel).getConfiguration().clone()); ((ComputationGraph) this.replicatedModel).init(); } if (!useMDS) { while (!shouldStop.get()) { DataSet dataSet = queue.poll(100, TimeUnit.MILLISECONDS); if (dataSet != null) { if (replicatedModel instanceof MultiLayerNetwork) { ((MultiLayerNetwork) replicatedModel).fit(dataSet); } else if (replicatedModel instanceof ComputationGraph) { ((ComputationGraph) replicatedModel).fit(dataSet); } if (Nd4j.getExecutioner() instanceof GridExecutioner) ((GridExecutioner) Nd4j.getExecutioner()).flushQueueBlocking(); running.decrementAndGet(); } } } else { // loop for MultiDataSet while (!shouldStop.get()) { MultiDataSet dataSet = queueMDS.poll(100, TimeUnit.MILLISECONDS); if (dataSet != null) { if (replicatedModel instanceof ComputationGraph) { ((ComputationGraph) replicatedModel).fit(dataSet); } else throw new RuntimeException("MultiDataSet can be fit into ComputationGraph only"); if (Nd4j.getExecutioner() instanceof GridExecutioner) ((GridExecutioner) Nd4j.getExecutioner()).flushQueueBlocking(); running.decrementAndGet(); } } } } catch (Exception e) { this.thrownException = e; } } public void waitTillRunning() { while (running.get() != 0) { // if Trainer thread got exception during training - rethrow it here if (thrownException != null) throw new RuntimeException(thrownException); try { Thread.sleep(10); } catch (Exception e) { ; } } } } }
xuzhongxing/deeplearning4j
deeplearning4j-core/src/main/java/org/deeplearning4j/parallelism/ParallelWrapper.java
Java
apache-2.0
25,921
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.directconnect.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Information about a public virtual interface. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/directconnect-2012-10-25/NewPublicVirtualInterface" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class NewPublicVirtualInterface implements Serializable, Cloneable, StructuredPojo { /** * <p> * The name of the virtual interface assigned by the customer network. * </p> */ private String virtualInterfaceName; /** * <p> * The ID of the VLAN. * </p> */ private Integer vlan; /** * <p> * The autonomous system (AS) number for Border Gateway Protocol (BGP) configuration. * </p> */ private Integer asn; /** * <p> * The authentication key for BGP configuration. This string has a minimum length of 6 characters and and a maximun * lenth of 80 characters. * </p> */ private String authKey; /** * <p> * The IP address assigned to the Amazon interface. * </p> */ private String amazonAddress; /** * <p> * The IP address assigned to the customer interface. * </p> */ private String customerAddress; /** * <p> * The address family for the BGP peer. * </p> */ private String addressFamily; /** * <p> * The routes to be advertised to the AWS network in this Region. Applies to public virtual interfaces. * </p> */ private com.amazonaws.internal.SdkInternalList<RouteFilterPrefix> routeFilterPrefixes; /** * <p> * Any tags assigned to the public virtual interface. * </p> */ private com.amazonaws.internal.SdkInternalList<Tag> tags; /** * <p> * The name of the virtual interface assigned by the customer network. * </p> * * @param virtualInterfaceName * The name of the virtual interface assigned by the customer network. */ public void setVirtualInterfaceName(String virtualInterfaceName) { this.virtualInterfaceName = virtualInterfaceName; } /** * <p> * The name of the virtual interface assigned by the customer network. * </p> * * @return The name of the virtual interface assigned by the customer network. */ public String getVirtualInterfaceName() { return this.virtualInterfaceName; } /** * <p> * The name of the virtual interface assigned by the customer network. * </p> * * @param virtualInterfaceName * The name of the virtual interface assigned by the customer network. * @return Returns a reference to this object so that method calls can be chained together. */ public NewPublicVirtualInterface withVirtualInterfaceName(String virtualInterfaceName) { setVirtualInterfaceName(virtualInterfaceName); return this; } /** * <p> * The ID of the VLAN. * </p> * * @param vlan * The ID of the VLAN. */ public void setVlan(Integer vlan) { this.vlan = vlan; } /** * <p> * The ID of the VLAN. * </p> * * @return The ID of the VLAN. */ public Integer getVlan() { return this.vlan; } /** * <p> * The ID of the VLAN. * </p> * * @param vlan * The ID of the VLAN. * @return Returns a reference to this object so that method calls can be chained together. */ public NewPublicVirtualInterface withVlan(Integer vlan) { setVlan(vlan); return this; } /** * <p> * The autonomous system (AS) number for Border Gateway Protocol (BGP) configuration. * </p> * * @param asn * The autonomous system (AS) number for Border Gateway Protocol (BGP) configuration. */ public void setAsn(Integer asn) { this.asn = asn; } /** * <p> * The autonomous system (AS) number for Border Gateway Protocol (BGP) configuration. * </p> * * @return The autonomous system (AS) number for Border Gateway Protocol (BGP) configuration. */ public Integer getAsn() { return this.asn; } /** * <p> * The autonomous system (AS) number for Border Gateway Protocol (BGP) configuration. * </p> * * @param asn * The autonomous system (AS) number for Border Gateway Protocol (BGP) configuration. * @return Returns a reference to this object so that method calls can be chained together. */ public NewPublicVirtualInterface withAsn(Integer asn) { setAsn(asn); return this; } /** * <p> * The authentication key for BGP configuration. This string has a minimum length of 6 characters and and a maximun * lenth of 80 characters. * </p> * * @param authKey * The authentication key for BGP configuration. This string has a minimum length of 6 characters and and a * maximun lenth of 80 characters. */ public void setAuthKey(String authKey) { this.authKey = authKey; } /** * <p> * The authentication key for BGP configuration. This string has a minimum length of 6 characters and and a maximun * lenth of 80 characters. * </p> * * @return The authentication key for BGP configuration. This string has a minimum length of 6 characters and and a * maximun lenth of 80 characters. */ public String getAuthKey() { return this.authKey; } /** * <p> * The authentication key for BGP configuration. This string has a minimum length of 6 characters and and a maximun * lenth of 80 characters. * </p> * * @param authKey * The authentication key for BGP configuration. This string has a minimum length of 6 characters and and a * maximun lenth of 80 characters. * @return Returns a reference to this object so that method calls can be chained together. */ public NewPublicVirtualInterface withAuthKey(String authKey) { setAuthKey(authKey); return this; } /** * <p> * The IP address assigned to the Amazon interface. * </p> * * @param amazonAddress * The IP address assigned to the Amazon interface. */ public void setAmazonAddress(String amazonAddress) { this.amazonAddress = amazonAddress; } /** * <p> * The IP address assigned to the Amazon interface. * </p> * * @return The IP address assigned to the Amazon interface. */ public String getAmazonAddress() { return this.amazonAddress; } /** * <p> * The IP address assigned to the Amazon interface. * </p> * * @param amazonAddress * The IP address assigned to the Amazon interface. * @return Returns a reference to this object so that method calls can be chained together. */ public NewPublicVirtualInterface withAmazonAddress(String amazonAddress) { setAmazonAddress(amazonAddress); return this; } /** * <p> * The IP address assigned to the customer interface. * </p> * * @param customerAddress * The IP address assigned to the customer interface. */ public void setCustomerAddress(String customerAddress) { this.customerAddress = customerAddress; } /** * <p> * The IP address assigned to the customer interface. * </p> * * @return The IP address assigned to the customer interface. */ public String getCustomerAddress() { return this.customerAddress; } /** * <p> * The IP address assigned to the customer interface. * </p> * * @param customerAddress * The IP address assigned to the customer interface. * @return Returns a reference to this object so that method calls can be chained together. */ public NewPublicVirtualInterface withCustomerAddress(String customerAddress) { setCustomerAddress(customerAddress); return this; } /** * <p> * The address family for the BGP peer. * </p> * * @param addressFamily * The address family for the BGP peer. * @see AddressFamily */ public void setAddressFamily(String addressFamily) { this.addressFamily = addressFamily; } /** * <p> * The address family for the BGP peer. * </p> * * @return The address family for the BGP peer. * @see AddressFamily */ public String getAddressFamily() { return this.addressFamily; } /** * <p> * The address family for the BGP peer. * </p> * * @param addressFamily * The address family for the BGP peer. * @return Returns a reference to this object so that method calls can be chained together. * @see AddressFamily */ public NewPublicVirtualInterface withAddressFamily(String addressFamily) { setAddressFamily(addressFamily); return this; } /** * <p> * The address family for the BGP peer. * </p> * * @param addressFamily * The address family for the BGP peer. * @see AddressFamily */ public void setAddressFamily(AddressFamily addressFamily) { withAddressFamily(addressFamily); } /** * <p> * The address family for the BGP peer. * </p> * * @param addressFamily * The address family for the BGP peer. * @return Returns a reference to this object so that method calls can be chained together. * @see AddressFamily */ public NewPublicVirtualInterface withAddressFamily(AddressFamily addressFamily) { this.addressFamily = addressFamily.toString(); return this; } /** * <p> * The routes to be advertised to the AWS network in this Region. Applies to public virtual interfaces. * </p> * * @return The routes to be advertised to the AWS network in this Region. Applies to public virtual interfaces. */ public java.util.List<RouteFilterPrefix> getRouteFilterPrefixes() { if (routeFilterPrefixes == null) { routeFilterPrefixes = new com.amazonaws.internal.SdkInternalList<RouteFilterPrefix>(); } return routeFilterPrefixes; } /** * <p> * The routes to be advertised to the AWS network in this Region. Applies to public virtual interfaces. * </p> * * @param routeFilterPrefixes * The routes to be advertised to the AWS network in this Region. Applies to public virtual interfaces. */ public void setRouteFilterPrefixes(java.util.Collection<RouteFilterPrefix> routeFilterPrefixes) { if (routeFilterPrefixes == null) { this.routeFilterPrefixes = null; return; } this.routeFilterPrefixes = new com.amazonaws.internal.SdkInternalList<RouteFilterPrefix>(routeFilterPrefixes); } /** * <p> * The routes to be advertised to the AWS network in this Region. Applies to public virtual interfaces. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setRouteFilterPrefixes(java.util.Collection)} or {@link #withRouteFilterPrefixes(java.util.Collection)} * if you want to override the existing values. * </p> * * @param routeFilterPrefixes * The routes to be advertised to the AWS network in this Region. Applies to public virtual interfaces. * @return Returns a reference to this object so that method calls can be chained together. */ public NewPublicVirtualInterface withRouteFilterPrefixes(RouteFilterPrefix... routeFilterPrefixes) { if (this.routeFilterPrefixes == null) { setRouteFilterPrefixes(new com.amazonaws.internal.SdkInternalList<RouteFilterPrefix>(routeFilterPrefixes.length)); } for (RouteFilterPrefix ele : routeFilterPrefixes) { this.routeFilterPrefixes.add(ele); } return this; } /** * <p> * The routes to be advertised to the AWS network in this Region. Applies to public virtual interfaces. * </p> * * @param routeFilterPrefixes * The routes to be advertised to the AWS network in this Region. Applies to public virtual interfaces. * @return Returns a reference to this object so that method calls can be chained together. */ public NewPublicVirtualInterface withRouteFilterPrefixes(java.util.Collection<RouteFilterPrefix> routeFilterPrefixes) { setRouteFilterPrefixes(routeFilterPrefixes); return this; } /** * <p> * Any tags assigned to the public virtual interface. * </p> * * @return Any tags assigned to the public virtual interface. */ public java.util.List<Tag> getTags() { if (tags == null) { tags = new com.amazonaws.internal.SdkInternalList<Tag>(); } return tags; } /** * <p> * Any tags assigned to the public virtual interface. * </p> * * @param tags * Any tags assigned to the public virtual interface. */ public void setTags(java.util.Collection<Tag> tags) { if (tags == null) { this.tags = null; return; } this.tags = new com.amazonaws.internal.SdkInternalList<Tag>(tags); } /** * <p> * Any tags assigned to the public virtual interface. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setTags(java.util.Collection)} or {@link #withTags(java.util.Collection)} if you want to override the * existing values. * </p> * * @param tags * Any tags assigned to the public virtual interface. * @return Returns a reference to this object so that method calls can be chained together. */ public NewPublicVirtualInterface withTags(Tag... tags) { if (this.tags == null) { setTags(new com.amazonaws.internal.SdkInternalList<Tag>(tags.length)); } for (Tag ele : tags) { this.tags.add(ele); } return this; } /** * <p> * Any tags assigned to the public virtual interface. * </p> * * @param tags * Any tags assigned to the public virtual interface. * @return Returns a reference to this object so that method calls can be chained together. */ public NewPublicVirtualInterface withTags(java.util.Collection<Tag> tags) { setTags(tags); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getVirtualInterfaceName() != null) sb.append("VirtualInterfaceName: ").append(getVirtualInterfaceName()).append(","); if (getVlan() != null) sb.append("Vlan: ").append(getVlan()).append(","); if (getAsn() != null) sb.append("Asn: ").append(getAsn()).append(","); if (getAuthKey() != null) sb.append("AuthKey: ").append(getAuthKey()).append(","); if (getAmazonAddress() != null) sb.append("AmazonAddress: ").append(getAmazonAddress()).append(","); if (getCustomerAddress() != null) sb.append("CustomerAddress: ").append(getCustomerAddress()).append(","); if (getAddressFamily() != null) sb.append("AddressFamily: ").append(getAddressFamily()).append(","); if (getRouteFilterPrefixes() != null) sb.append("RouteFilterPrefixes: ").append(getRouteFilterPrefixes()).append(","); if (getTags() != null) sb.append("Tags: ").append(getTags()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof NewPublicVirtualInterface == false) return false; NewPublicVirtualInterface other = (NewPublicVirtualInterface) obj; if (other.getVirtualInterfaceName() == null ^ this.getVirtualInterfaceName() == null) return false; if (other.getVirtualInterfaceName() != null && other.getVirtualInterfaceName().equals(this.getVirtualInterfaceName()) == false) return false; if (other.getVlan() == null ^ this.getVlan() == null) return false; if (other.getVlan() != null && other.getVlan().equals(this.getVlan()) == false) return false; if (other.getAsn() == null ^ this.getAsn() == null) return false; if (other.getAsn() != null && other.getAsn().equals(this.getAsn()) == false) return false; if (other.getAuthKey() == null ^ this.getAuthKey() == null) return false; if (other.getAuthKey() != null && other.getAuthKey().equals(this.getAuthKey()) == false) return false; if (other.getAmazonAddress() == null ^ this.getAmazonAddress() == null) return false; if (other.getAmazonAddress() != null && other.getAmazonAddress().equals(this.getAmazonAddress()) == false) return false; if (other.getCustomerAddress() == null ^ this.getCustomerAddress() == null) return false; if (other.getCustomerAddress() != null && other.getCustomerAddress().equals(this.getCustomerAddress()) == false) return false; if (other.getAddressFamily() == null ^ this.getAddressFamily() == null) return false; if (other.getAddressFamily() != null && other.getAddressFamily().equals(this.getAddressFamily()) == false) return false; if (other.getRouteFilterPrefixes() == null ^ this.getRouteFilterPrefixes() == null) return false; if (other.getRouteFilterPrefixes() != null && other.getRouteFilterPrefixes().equals(this.getRouteFilterPrefixes()) == false) return false; if (other.getTags() == null ^ this.getTags() == null) return false; if (other.getTags() != null && other.getTags().equals(this.getTags()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getVirtualInterfaceName() == null) ? 0 : getVirtualInterfaceName().hashCode()); hashCode = prime * hashCode + ((getVlan() == null) ? 0 : getVlan().hashCode()); hashCode = prime * hashCode + ((getAsn() == null) ? 0 : getAsn().hashCode()); hashCode = prime * hashCode + ((getAuthKey() == null) ? 0 : getAuthKey().hashCode()); hashCode = prime * hashCode + ((getAmazonAddress() == null) ? 0 : getAmazonAddress().hashCode()); hashCode = prime * hashCode + ((getCustomerAddress() == null) ? 0 : getCustomerAddress().hashCode()); hashCode = prime * hashCode + ((getAddressFamily() == null) ? 0 : getAddressFamily().hashCode()); hashCode = prime * hashCode + ((getRouteFilterPrefixes() == null) ? 0 : getRouteFilterPrefixes().hashCode()); hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode()); return hashCode; } @Override public NewPublicVirtualInterface clone() { try { return (NewPublicVirtualInterface) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.directconnect.model.transform.NewPublicVirtualInterfaceMarshaller.getInstance().marshall(this, protocolMarshaller); } }
jentfoo/aws-sdk-java
aws-java-sdk-directconnect/src/main/java/com/amazonaws/services/directconnect/model/NewPublicVirtualInterface.java
Java
apache-2.0
21,420
package test; import sun.servlet.http.*; import javax.servlet.*; import javax.swing.*; import java.awt.*; public class ServletServer { // static public void main(String[] args) { boolean portSet = false; boolean servletDirSet = false; for(int i = 0; i < args.length; i++) { if(args[i].equals("-p")) { portSet = true; } if(args[i].equals("-d")) { servletDirSet = true; } } int i = 0; String[] arguments = new String[args.length + (servletDirSet ? 0 : 2) + (portSet ? 0 : 2)]; for(; i < args.length; i++) { arguments[i] = args[i]; } if(!portSet) { arguments[i++] = "-p"; arguments[i++] = "8080"; } String servletDir = ""; if(!servletDirSet) { arguments[i++] = "-d"; servletDir = System.getProperty("java.class.path"); servletDir = servletDir.substring(0,servletDir.indexOf(java.io.File.pathSeparator)); String pack; pack = java.io.File.separator + "test.Module1" + java.io.File.separator + "Module1" + java.io.File.separator + "clienthtml"; System.out.println(servletDir + pack); arguments[i++] = servletDir + pack; } ServletServerFrame frame = new ServletServerFrame("8080",servletDir); frame.show(); HttpServer.main(arguments); } } class ServletServerFrame extends JFrame { java.awt.FlowLayout flowLayout1 = new java.awt.FlowLayout(); java.awt.GridBagLayout gridBagLayout1 = new java.awt.GridBagLayout(); JLabel jLabel1 = new JLabel(); JTextField jTextField1 = new JTextField(); JLabel jLabel2 = new JLabel(); JTextField jTextField2 = new JTextField(); JLabel jLabel3 = new JLabel(); JTextField jTextField3 = new JTextField(); JLabel jLabel4 = new JLabel(); String _port; String _servletDir; public ServletServerFrame(String port, String servletDir) { enableEvents(java.awt.AWTEvent.WINDOW_EVENT_MASK); _servletDir = servletDir; _port = port; try { jbInit(); } catch (Exception e) { e.printStackTrace(); } } private void jbInit() throws Exception { this.setTitle("ServletServer"); this.getContentPane().setLayout(gridBagLayout1); this.setSize(new java.awt.Dimension(200, 200)); jLabel1.setText("Port: "); jTextField1.setText(_port); jLabel2.setText("ServletDir: "); jTextField2.setText(_servletDir); jLabel3.setText("Paste the following URL into a web browser to load the SHTML file"); String pack; pack = "test.Module1.clienthtml"; jTextField3.setText("http://localhost:8080/servlet/" + pack + ".ShtmlLoader"); this.getContentPane().add(jLabel1, new GridBagConstraints(0, 0, 1, 2, 0.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(25, 24, 0, 0), 37, 10)); this.getContentPane().add(jLabel2, new GridBagConstraints(0, 2, 2, 1, 0.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(11, 24, 0, 0), 20, 8)); this.getContentPane().add(jTextField1, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(25, 20, 0, 0), 40, 1)); this.getContentPane().add(jTextField2, new GridBagConstraints(1, 2, 3, 1, 1.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(13, 20, 0, 32), 161, 1)); this.getContentPane().add(jLabel3, new GridBagConstraints(0, 3, 4, 1, 0.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(24, 24, 0, 0), 22, 11)); this.getContentPane().add(jTextField3, new GridBagConstraints(0, 4, 7, 1, 1.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 24, 0, 32), 274, 1)); this.getContentPane().add(jLabel4, new GridBagConstraints(0, 5, 6, 1, 0.0, 0.0 ,GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(14, 24, 63, 32), 22, 15)); jTextField1.setEnabled(false); jTextField2.setEnabled(false); this.setSize(new java.awt.Dimension(500, 250)); } protected void processWindowEvent(java.awt.event.WindowEvent e) { super.processWindowEvent(e); if (e.getID() == java.awt.event.WindowEvent.WINDOW_CLOSING) { System.exit(0); } } }
FJplant/AntIDE
src/test/ServletServer.java
Java
apache-2.0
4,464
package com.example.kanalearner; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import java.util.List; public class TestSettingsActivity extends OptionsActivity implements AdapterView.OnItemSelectedListener { Spinner typeSpinner; Spinner testSpinner; Spinner difficultySpinner; DbHelper dbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_testsettings); getActionBar().setDisplayHomeAsUpEnabled(true); typeSpinner = (Spinner) findViewById(R.id.spinner_type); testSpinner = (Spinner) findViewById(R.id.spinner_test); difficultySpinner = (Spinner) findViewById(R.id.spinner_difficulty); typeSpinner.setOnItemSelectedListener(this); testSpinner.setOnItemSelectedListener(this); difficultySpinner.setOnItemSelectedListener(this); dbHelper = new DbHelper(this); updateTypeList(); updateTestList(); updateDifficultyList(); } public void startClicked(View view) { Intent i = new Intent(this, TestActivity.class); i.putExtra("typeId", ((DbHelper.Type)typeSpinner.getSelectedItem()).getId()); i.putExtra("testId", ((DbHelper.Test)testSpinner.getSelectedItem()).getId()); i.putExtra("difficultyId", ((DbHelper.Difficulty) difficultySpinner.getSelectedItem()).getId()); startActivity(i); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (parent == typeSpinner) { updateTestList(); } } @Override public void onNothingSelected(AdapterView<?> parent) { } private void updateTypeList() { ArrayAdapter<DbHelper.Type> adapter = new ArrayAdapter<DbHelper.Type>(this, android.R.layout.simple_spinner_item, dbHelper.getAllTypes()); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); typeSpinner.setAdapter(adapter); } private void updateTestList() { List<DbHelper.Test> items = dbHelper.getTestsForType(((DbHelper.Type) typeSpinner.getSelectedItem()).getId()); ArrayAdapter<DbHelper.Test> adapter = new ArrayAdapter<DbHelper.Test>(this, android.R.layout.simple_spinner_item, items); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); testSpinner.setAdapter(adapter); } private void updateDifficultyList() { ArrayAdapter<DbHelper.Difficulty> adapter = new ArrayAdapter<DbHelper.Difficulty>(this, android.R.layout.simple_spinner_item, dbHelper.getAllDifficulties()); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); difficultySpinner.setAdapter(adapter); } }
JouperCoding/KanaLearner
KanaLearner/app/src/main/java/com/example/kanalearner/TestSettingsActivity.java
Java
apache-2.0
2,958
/** * generated by Xtext 2.10.0 */ package com.laegler.stubbr.lang.stubbrLang; import org.eclipse.emf.common.util.EList; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Activity</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link com.laegler.stubbr.lang.stubbrLang.Activity#getAttachments <em>Attachments</em>}</li> * </ul> * * @see com.laegler.stubbr.lang.stubbrLang.StubbrLangPackage#getActivity() * @model * @generated */ public interface Activity extends FlowNode, OptionFlowNode { /** * Returns the value of the '<em><b>Attachments</b></em>' containment reference list. * The list contents are of type {@link com.laegler.stubbr.lang.stubbrLang.Attachment}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Attachments</em>' containment reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Attachments</em>' containment reference list. * @see com.laegler.stubbr.lang.stubbrLang.StubbrLangPackage#getActivity_Attachments() * @model containment="true" * @generated */ EList<Attachment> getAttachments(); } // Activity
thlaegler/stubbr
com.laegler.stubbr.lang/src-gen/com/laegler/stubbr/lang/stubbrLang/Activity.java
Java
apache-2.0
1,319
/* Copyright 2010 Radu Cernuta 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 serene.bind; import java.util.Map; /** * The context of the current element task. Used when executing the queued * tasks, so it assumes that the order is known and no arguments are passed to * the getter methods. */ public interface ElementTaskContext extends TaskContext{ /*String getStartLocation(); String getEndLocation(); NameInfo getElementNameInfo();// TODO Consider replacing with getElementRecordIndex AttributeInfo[] getAttributeInfo(SAttribute attribute);// TODO Consider replacing with getAttributeRecordIndex String getCharacterContent();*/ int getElementInputRecordIndex(); String getCharacterContent(); /*Map<String, String> getDeclaredXmlns();*/ }
TheProjecter/serene
src/serene/bind/ElementTaskContext.java
Java
apache-2.0
1,289
package com.epam.ta.reportportal.core.events.handler; import com.epam.ta.reportportal.commons.querygen.Filter; import com.epam.ta.reportportal.core.events.widget.GenerateWidgetViewEvent; import com.epam.ta.reportportal.core.widget.content.BuildFilterStrategy; import com.epam.ta.reportportal.core.widget.content.loader.materialized.generator.ViewGenerator; import com.epam.ta.reportportal.core.widget.content.materialized.generator.MaterializedViewNameGenerator; import com.epam.ta.reportportal.dao.WidgetRepository; import com.epam.ta.reportportal.entity.widget.WidgetType; import com.epam.ta.reportportal.exception.ReportPortalException; import com.epam.ta.reportportal.ws.model.ErrorType; import org.apache.commons.lang3.BooleanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.core.task.TaskExecutor; import org.springframework.data.domain.Sort; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.event.TransactionalEventListener; import java.util.Map; import static com.epam.ta.reportportal.commons.validation.Suppliers.formattedSupplier; import static com.epam.ta.reportportal.core.widget.content.loader.materialized.handler.MaterializedWidgetStateHandler.REFRESH; import static com.epam.ta.reportportal.core.widget.util.WidgetFilterUtil.GROUP_FILTERS; import static com.epam.ta.reportportal.core.widget.util.WidgetFilterUtil.GROUP_SORTS; import static java.util.Optional.ofNullable; /** * @author <a href="mailto:ivan_budayeu@epam.com">Ivan Budayeu</a> */ @Service public class GenerateWidgetViewEventHandler { private final WidgetRepository widgetRepository; private final Map<WidgetType, BuildFilterStrategy> buildFilterStrategyMapping; private final MaterializedViewNameGenerator materializedViewNameGenerator; private final TaskExecutor widgetViewExecutor; private final Map<WidgetType, ViewGenerator> viewGeneratorMapping; @Autowired public GenerateWidgetViewEventHandler(WidgetRepository widgetRepository, @Qualifier("buildFilterStrategy") Map<WidgetType, BuildFilterStrategy> buildFilterStrategyMapping, MaterializedViewNameGenerator materializedViewNameGenerator, @Qualifier("widgetViewExecutor") TaskExecutor widgetViewExecutor, @Qualifier("viewGeneratorMapping") Map<WidgetType, ViewGenerator> viewGeneratorMapping) { this.widgetRepository = widgetRepository; this.buildFilterStrategyMapping = buildFilterStrategyMapping; this.materializedViewNameGenerator = materializedViewNameGenerator; this.widgetViewExecutor = widgetViewExecutor; this.viewGeneratorMapping = viewGeneratorMapping; } @Async @Transactional(propagation = Propagation.REQUIRES_NEW) @TransactionalEventListener public void onApplicationEvent(GenerateWidgetViewEvent event) { widgetRepository.findById(event.getWidgetId()).ifPresent(widget -> { WidgetType widgetType = WidgetType.findByName(widget.getWidgetType()) .orElseThrow(() -> new ReportPortalException(ErrorType.UNABLE_TO_CREATE_WIDGET, formattedSupplier("Unsupported widget type '{}'", widget.getWidgetType()) )); Map<Filter, Sort> filterSortMapping = buildFilterStrategyMapping.get(widgetType).buildFilter(widget); Filter launchesFilter = GROUP_FILTERS.apply(filterSortMapping.keySet()); Sort launchesSort = GROUP_SORTS.apply(filterSortMapping.values()); ofNullable(viewGeneratorMapping.get(widgetType)).ifPresent(viewGenerator -> widgetViewExecutor.execute(() -> viewGenerator.generate( BooleanUtils.toBoolean(event.getParams().getFirst(REFRESH)), materializedViewNameGenerator.generate(widget), widget, launchesFilter, launchesSort, event.getParams() ))); }); } }
reportportal/service-api
src/main/java/com/epam/ta/reportportal/core/events/handler/GenerateWidgetViewEventHandler.java
Java
apache-2.0
3,952
/* * PackList is an open-source packing-list for Android * * Copyright (c) 2017 Nicolas Bossard and other contributors. * * 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.nbossard.packlist.model; import java.util.Comparator; /* @startuml class com.nbossard.packlist.model.ItemComparatorPacking { } @enduml */ /** * Comparator to sort Items based on unpacked first, then use alphabetical order. * * @author Created by nbossard on 02/05/16. */ public class ItemComparatorPacking implements Comparator<TripItem> { @Override public final int compare(final TripItem parItem, final TripItem parAnother) { int res = 0; if (!parItem.isPacked() && parAnother.isPacked()) { //noinspection CheckStyle res = -2; } else if (parItem.isPacked() && !parAnother.isPacked()) { res = 2; } else if ((!parItem.isPacked() && !parAnother.isPacked()) || (parItem.isPacked() && parAnother.isPacked())) { // both are unpacked, or both are packed, then using alphabetical order if ((parItem.getName() != null) && (parAnother.getName() != null)) { ItemComparatorCategoryAlphabetical tmp = new ItemComparatorCategoryAlphabetical(); res = tmp.compare(parItem, parAnother); } } return res; } }
nbossard/packlist
app/src/main/java/com/nbossard/packlist/model/ItemComparatorPacking.java
Java
apache-2.0
1,891
/* * Copyright 2000-2010 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.usages; import javax.annotation.Nonnull; /** * @author traff */ public interface NamedPresentably { @Nonnull String getPresentableName(); }
consulo/consulo
modules/base/usage-view/src/main/java/com/intellij/usages/NamedPresentably.java
Java
apache-2.0
770
package android.database.sqlite; /* * #%L * Matos * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2010 - 2014 Orange SA * %% * 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% */ public final class SqliteWrapper { // Constructors private SqliteWrapper(){ } // Methods public static int delete(android.content.Context arg1, android.content.ContentResolver arg2, android.net.Uri arg3, java.lang.String arg4, java.lang.String [] arg5){ return 0; } public static android.net.Uri insert(android.content.Context arg1, android.content.ContentResolver arg2, android.net.Uri arg3, android.content.ContentValues arg4){ return (android.net.Uri) null; } public static android.database.Cursor query(android.content.Context arg1, android.content.ContentResolver arg2, android.net.Uri arg3, java.lang.String [] arg4, java.lang.String arg5, java.lang.String [] arg6, java.lang.String arg7){ return (android.database.Cursor) null; } public static int update(android.content.Context arg1, android.content.ContentResolver arg2, android.net.Uri arg3, android.content.ContentValues arg4, java.lang.String arg5, java.lang.String [] arg6){ return 0; } public static boolean requery(android.content.Context arg1, android.database.Cursor arg2){ return false; } public static void checkSQLiteException(android.content.Context arg1, SQLiteException arg2){ } }
Orange-OpenSource/matos-profiles
matos-android/src/main/java/android/database/sqlite/SqliteWrapper.java
Java
apache-2.0
1,906
package be.kwakeroni.parameters.core.support.client; import be.kwakeroni.parameters.client.api.model.Parameter; import be.kwakeroni.parameters.types.api.ParameterType; import be.kwakeroni.parameters.types.support.ParameterTypes; import java.time.LocalDate; public class ParameterSupport<T> implements Parameter<T> { private final String name; private final ParameterType<T> type; public ParameterSupport(String name, ParameterType<T> type) { this.name = name; this.type = type; } @Override public String getName() { return this.name; } @Override public T fromString(String value) { return type.fromString(value); } @Override public String toString(T value) { return type.toString(value); } public static Parameter<String> ofString(String name) { return new ParameterSupport<>(name, ParameterTypes.STRING); } public static Parameter<Integer> ofInt(String name) { return new ParameterSupport<>(name, ParameterTypes.INT); } public static Parameter<Long> ofLong(String name) { return new ParameterSupport<>(name, ParameterTypes.LONG); } public static Parameter<Boolean> ofBoolean(String name) { return new ParameterSupport<>(name, ParameterTypes.BOOLEAN); } public static Parameter<Character> ofChar(String name) { return new ParameterSupport<>(name, ParameterTypes.CHAR); } public static Parameter<LocalDate> ofLocalDate(String name) { return new ParameterSupport<>(name, ParameterTypes.LOCAL_DATE); } }
kwakeroni/BusinessParameters
parameters-core/parameters-core-support/src/main/java/be/kwakeroni/parameters/core/support/client/ParameterSupport.java
Java
apache-2.0
1,592
/* * Copyright (c) 2002-2015 mgm technology partners 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. */ package com.mgmtp.perfload.core.clientserver.util; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * {@link ThreadFactory} that marks new threads as daemon threads. * * @author rnaegele */ public class DaemonThreadFactory implements ThreadFactory { private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1); private final AtomicInteger threadNumber = new AtomicInteger(1); private final String namePrefix; public DaemonThreadFactory() { namePrefix = "pool-" + POOL_NUMBER.getAndIncrement() + "-thread-"; } @Override public Thread newThread(final Runnable r) { Thread t = new Thread(r, namePrefix + threadNumber.getAndIncrement()); t.setDaemon(true); return t; } }
mgm-tp/perfload-core
perfload-clientserver/src/main/java/com/mgmtp/perfload/core/clientserver/util/DaemonThreadFactory.java
Java
apache-2.0
1,372
/* * 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.phoenix.end2end; import static org.apache.phoenix.util.TestUtil.B_VALUE; import static org.apache.phoenix.util.TestUtil.ROW1; import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.sql.Array; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; import org.apache.phoenix.query.BaseTest; import org.apache.phoenix.schema.types.PhoenixArray; import org.apache.phoenix.util.PropertiesUtil; import org.apache.phoenix.util.TestUtil; import org.junit.Test; import org.apache.phoenix.thirdparty.com.google.common.primitives.Floats; public class Array1IT extends ArrayIT { private void assertArrayGetString(ResultSet rs, int arrayIndex, Array expectedArray, String expectedString) throws SQLException { assertEquals(expectedArray, rs.getArray(arrayIndex)); assertEquals("[" + expectedString + "]", rs.getString(arrayIndex)); } private static String createTableWithAllArrayTypes(String url, byte[][] bs, Object object) throws SQLException { String tableName = generateUniqueName(); String ddlStmt = "create table " + tableName + " (organization_id char(15) not null, \n" + " entity_id char(15) not null,\n" + " boolean_array boolean array,\n" + " byte_array tinyint array,\n" + " double_array double array[],\n" + " float_array float array,\n" + " int_array integer array,\n" + " long_array bigint[5],\n" + " short_array smallint array,\n" + " string_array varchar(100) array[3],\n" + " CONSTRAINT pk PRIMARY KEY (organization_id, entity_id)\n" + ")"; BaseTest.createTestTable(url, ddlStmt, bs, null); return tableName; } private static String createSimpleTableWithArray(String url, byte[][] bs, Object object) throws SQLException { String tableName = generateUniqueName(); String ddlStmt = "create table " + tableName + " (organization_id char(15) not null, \n" + " entity_id char(15) not null,\n" + " x_double double,\n" + " a_double_array double array[],\n" + " a_char_array char(5) array[],\n" + " CONSTRAINT pk PRIMARY KEY (organization_id, entity_id)\n" + ")"; BaseTest.createTestTable(url, ddlStmt, bs, null); return tableName; } private static void initSimpleArrayTable(String tableName, String tenantId, Date date, boolean useNull) throws Exception { Properties props = new Properties(); Connection conn = DriverManager.getConnection(getUrl(), props); try { // Insert all rows at ts PreparedStatement stmt = conn.prepareStatement( "upsert into " + tableName + "(" + " ORGANIZATION_ID, " + " ENTITY_ID, " + " x_double, " + " a_double_array, a_char_array)" + "VALUES (?, ?, ?, ?, ?)"); stmt.setString(1, tenantId); stmt.setString(2, ROW1); stmt.setDouble(3, 1.2d); // Need to support primitive Double[] doubleArr = new Double[2]; doubleArr[0] = 64.87; doubleArr[1] = 89.96; //doubleArr[2] = 9.9; Array array = conn.createArrayOf("DOUBLE", doubleArr); stmt.setArray(4, array); // create character array String[] charArr = new String[2]; charArr[0] = "a"; charArr[1] = "b"; array = conn.createArrayOf("CHAR", charArr); stmt.setArray(5, array); stmt.execute(); conn.commit(); } finally { conn.close(); } } @Test public void testScanByArrayValue() throws Exception { String tenantId = getOrganizationId(); String tableName = createTableWithArray(getUrl(), getDefaultSplits(tenantId), null); initTablesWithArrays(tableName, tenantId, null, false, getUrl()); String query = "SELECT a_double_array, /* comment ok? */ b_string, a_float FROM " + tableName + " WHERE ?=organization_id and ?=a_float"; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); TestUtil.analyzeTable(conn, tableName); try { PreparedStatement statement = conn.prepareStatement(query); statement.setString(1, tenantId); statement.setFloat(2, 0.01f); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); // Need to support primitive Double[] doubleArr = new Double[4]; doubleArr[0] = 25.343; doubleArr[1] = 36.763; doubleArr[2] = 37.56; doubleArr[3] = 386.63; Array array = conn.createArrayOf("DOUBLE", doubleArr); PhoenixArray resultArray = (PhoenixArray) rs.getArray(1); assertEquals(resultArray, array); assertEquals("[25.343, 36.763, 37.56, 386.63]", rs.getString(1)); assertEquals(rs.getString("B_string"), B_VALUE); assertTrue(Floats.compare(rs.getFloat(3), 0.01f) == 0); assertFalse(rs.next()); } finally { conn.close(); } } @Test public void testScanWithArrayInWhereClause() throws Exception { String tenantId = getOrganizationId(); String tableName = createTableWithArray(getUrl(), getDefaultSplits(tenantId), null); initTablesWithArrays(tableName, tenantId, null, false, getUrl()); String query = "SELECT a_double_array, /* comment ok? */ b_string, a_float FROM " + tableName + " WHERE ?=organization_id and ?=a_byte_array"; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); TestUtil.analyzeTable(conn, tableName); try { PreparedStatement statement = conn.prepareStatement(query); statement.setString(1, tenantId); // Need to support primitive Byte[] byteArr = new Byte[2]; byteArr[0] = 25; byteArr[1] = 36; Array array = conn.createArrayOf("TINYINT", byteArr); statement.setArray(2, array); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); // Need to support primitive Double[] doubleArr = new Double[4]; doubleArr[0] = 25.343; doubleArr[1] = 36.763; doubleArr[2] = 37.56; doubleArr[3] = 386.63; array = conn.createArrayOf("DOUBLE", doubleArr); Array resultArray = rs.getArray(1); assertEquals(resultArray, array); assertEquals("[25.343, 36.763, 37.56, 386.63]", rs.getString(1)); assertEquals(rs.getString("B_string"), B_VALUE); assertTrue(Floats.compare(rs.getFloat(3), 0.01f) == 0); assertFalse(rs.next()); } finally { conn.close(); } } @Test public void testScanWithNonFixedWidthArrayInWhereClause() throws Exception { String tenantId = getOrganizationId(); String tableName = createTableWithArray(getUrl(), getDefaultSplits(tenantId), null); initTablesWithArrays(tableName, tenantId, null, false, getUrl()); String query = "SELECT a_double_array, /* comment ok? */ b_string, a_float FROM " + tableName + " WHERE ?=organization_id and ?=a_string_array"; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); try { PreparedStatement statement = conn.prepareStatement(query); statement.setString(1, tenantId); // Need to support primitive String[] strArr = new String[4]; strArr[0] = "ABC"; strArr[1] = "CEDF"; strArr[2] = "XYZWER"; strArr[3] = "AB"; Array array = conn.createArrayOf("VARCHAR", strArr); statement.setArray(2, array); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); // Need to support primitive Double[] doubleArr = new Double[4]; doubleArr[0] = 25.343; doubleArr[1] = 36.763; doubleArr[2] = 37.56; doubleArr[3] = 386.63; array = conn.createArrayOf("DOUBLE", doubleArr); Array resultArray = rs.getArray(1); assertEquals(resultArray, array); assertEquals("[25.343, 36.763, 37.56, 386.63]", rs.getString(1)); assertEquals(rs.getString("B_string"), B_VALUE); assertTrue(Floats.compare(rs.getFloat(3), 0.01f) == 0); assertFalse(rs.next()); } finally { conn.close(); } } @Test public void testScanWithNonFixedWidthArrayInSelectClause() throws Exception { String tenantId = getOrganizationId(); String tableName = createTableWithArray(getUrl(), getDefaultSplits(tenantId), null); initTablesWithArrays(tableName, tenantId, null, false, getUrl()); String query = "SELECT a_string_array FROM " + tableName; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); try { PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); String[] strArr = new String[4]; strArr[0] = "ABC"; strArr[1] = "CEDF"; strArr[2] = "XYZWER"; strArr[3] = "AB"; Array array = conn.createArrayOf("VARCHAR", strArr); PhoenixArray resultArray = (PhoenixArray) rs.getArray(1); assertEquals(resultArray, array); assertEquals("['ABC', 'CEDF', 'XYZWER', 'AB']", rs.getString(1)); assertFalse(rs.next()); } finally { conn.close(); } } @Test public void testSelectSpecificIndexOfAnArrayAsArrayFunction() throws Exception { String tenantId = getOrganizationId(); String tableName = createTableWithArray(getUrl(), getDefaultSplits(tenantId), null); initTablesWithArrays(tableName, tenantId, null, false, getUrl()); String query = "SELECT ARRAY_ELEM(a_double_array,2) FROM " + tableName; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); try { PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); // Need to support primitive Double[] doubleArr = new Double[1]; doubleArr[0] = 36.763; conn.createArrayOf("DOUBLE", doubleArr); Double result = rs.getDouble(1); assertEquals(doubleArr[0], result); assertFalse(rs.next()); } finally { conn.close(); } } @Test public void testSelectSpecificIndexOfAnArray() throws Exception { String tenantId = getOrganizationId(); String tableName = createTableWithArray(getUrl(), getDefaultSplits(tenantId), null); initTablesWithArrays(tableName, tenantId, null, false, getUrl()); String query = "SELECT a_double_array[3] FROM " + tableName; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); try { PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); // Need to support primitive Double[] doubleArr = new Double[1]; doubleArr[0] = 37.56; Double result = rs.getDouble(1); assertEquals(doubleArr[0], result); assertFalse(rs.next()); } finally { conn.close(); } } @Test public void testCaseWithArray() throws Exception { String tenantId = getOrganizationId(); String tableName = createTableWithArray(getUrl(), getDefaultSplits(tenantId), null); initTablesWithArrays(tableName, tenantId, null, false, getUrl()); String query = "SELECT CASE WHEN A_INTEGER = 1 THEN a_double_array ELSE null END [3] FROM " + tableName; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); try { PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); // Need to support primitive Double[] doubleArr = new Double[1]; doubleArr[0] = 37.56; Double result = rs.getDouble(1); assertEquals(doubleArr[0], result); assertFalse(rs.next()); } finally { conn.close(); } } @Test public void testUpsertValuesWithArray() throws Exception { String tenantId = getOrganizationId(); String tableName = createTableWithArray(getUrl(), getDefaultSplits(tenantId), null); String query = "upsert into " + tableName + " (ORGANIZATION_ID,ENTITY_ID,a_double_array) values('" + tenantId + "','00A123122312312',ARRAY[2.0,345.8])"; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); // at Connection conn = DriverManager.getConnection(getUrl(), props); try { PreparedStatement statement = conn.prepareStatement(query); int executeUpdate = statement.executeUpdate(); assertEquals(1, executeUpdate); conn.commit(); statement.close(); conn.close(); // create another connection props = PropertiesUtil.deepCopy(TEST_PROPERTIES); conn = DriverManager.getConnection(getUrl(), props); query = "SELECT ARRAY_ELEM(a_double_array,2) FROM " + tableName; statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); // Need to support primitive Double[] doubleArr = new Double[1]; doubleArr[0] = 345.8d; conn.createArrayOf("DOUBLE", doubleArr); Double result = rs.getDouble(1); assertEquals(doubleArr[0], result); assertFalse(rs.next()); } finally { conn.close(); } } @Test public void testUpsertSelectWithSelectAsSubQuery1() throws Exception { String tenantId = getOrganizationId(); String table1 = createTableWithArray(getUrl(), getDefaultSplits(tenantId), null); Connection conn = null; try { String table2 = createSimpleTableWithArray(getUrl(), getDefaultSplits(tenantId), null); initSimpleArrayTable(table2, tenantId, null, false); Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); conn = DriverManager.getConnection(getUrl(), props); String query = "upsert into " + table1 + " (ORGANIZATION_ID,ENTITY_ID,a_double_array) " + "SELECT organization_id, entity_id, a_double_array FROM " + table2 + " WHERE a_double_array[2] = 89.96"; PreparedStatement statement = conn.prepareStatement(query); int executeUpdate = statement.executeUpdate(); assertEquals(1, executeUpdate); conn.commit(); statement.close(); conn.close(); // create another connection props = PropertiesUtil.deepCopy(TEST_PROPERTIES); conn = DriverManager.getConnection(getUrl(), props); query = "SELECT ARRAY_ELEM(a_double_array,2) FROM " + table1; statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); // Need to support primitive Double[] doubleArr = new Double[1]; doubleArr[0] = 89.96d; Double result = rs.getDouble(1); assertEquals(result, doubleArr[0]); assertFalse(rs.next()); } finally { if (conn != null) { conn.close(); } } } @Test public void testArraySelectWithORCondition() throws Exception { String tenantId = getOrganizationId(); Connection conn = null; try { String table = createSimpleTableWithArray(getUrl(), getDefaultSplits(tenantId), null); initSimpleArrayTable(table, tenantId, null, false); Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); conn = DriverManager.getConnection(getUrl(), props); String query = "SELECT a_double_array[1] FROM " + table + " WHERE a_double_array[2] = 89.96 or a_char_array[0] = 'a'"; PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); Double[] doubleArr = new Double[1]; doubleArr[0] = 64.87d; Double result = rs.getDouble(1); assertEquals(result, doubleArr[0]); assertFalse(rs.next()); } finally { if (conn != null) { conn.close(); } } } @Test public void testArraySelectWithANY() throws Exception { String tenantId = getOrganizationId(); Connection conn = null; try { String table = createSimpleTableWithArray(getUrl(), getDefaultSplits(tenantId), null); initSimpleArrayTable(table, tenantId, null, false); Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); conn = DriverManager.getConnection(getUrl(), props); String query = "SELECT a_double_array[1] FROM " + table + " WHERE CAST(89.96 AS DOUBLE) = ANY(a_double_array)"; PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); Double[] doubleArr = new Double[1]; doubleArr[0] = 64.87d; Double result = rs.getDouble(1); assertEquals(result, doubleArr[0]); assertFalse(rs.next()); } finally { if (conn != null) { conn.close(); } } } @Test public void testArraySelectWithALL() throws Exception { String tenantId = getOrganizationId(); Connection conn = null; try { String table = createSimpleTableWithArray(getUrl(), getDefaultSplits(tenantId), null); initSimpleArrayTable(table, tenantId, null, false); Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); conn = DriverManager.getConnection(getUrl(), props); String query = "SELECT a_double_array[1] FROM " + table + " WHERE CAST(64.87 as DOUBLE) = ALL(a_double_array)"; PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertFalse(rs.next()); } finally { if (conn != null) { conn.close(); } } } @Test public void testArraySelectWithANYCombinedWithOR() throws Exception { String tenantId = getOrganizationId(); Connection conn = null; try { String table = createSimpleTableWithArray(getUrl(), getDefaultSplits(tenantId), null); initSimpleArrayTable(table, tenantId, null, false); Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); conn = DriverManager.getConnection(getUrl(), props); String query = "SELECT a_double_array[1] FROM " + table + " WHERE a_char_array[0] = 'f' or CAST(89.96 AS DOUBLE) > ANY(a_double_array)"; PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); Double[] doubleArr = new Double[1]; doubleArr[0] = 64.87d; Double result = rs.getDouble(1); assertEquals(result, doubleArr[0]); assertFalse(rs.next()); } finally { if (conn != null) { conn.close(); } } } @Test public void testArraySelectWithALLCombinedWithOR() throws Exception { String tenantId = getOrganizationId(); Connection conn = null; try { String table = createSimpleTableWithArray(getUrl(), getDefaultSplits(tenantId), null); initSimpleArrayTable(table, tenantId, null, false); Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); conn = DriverManager.getConnection(getUrl(), props); String query = "SELECT a_double_array[1], a_double_array[2] FROM " + table + " WHERE a_char_array[0] = 'f' or CAST(100.0 AS DOUBLE) > ALL(a_double_array)"; PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); Double[] doubleArr = new Double[1]; doubleArr[0] = 64.87d; Double result = rs.getDouble(1); assertEquals(result, doubleArr[0]); doubleArr = new Double[1]; doubleArr[0] = 89.96d; result = rs.getDouble(2); assertEquals(result, doubleArr[0]); } finally { if (conn != null) { conn.close(); } } } @Test public void testArraySelectWithANYUsingVarLengthArray() throws Exception { Connection conn = null; try { String tenantId = getOrganizationId(); String table = createTableWithArray(getUrl(), getDefaultSplits(tenantId), null); initTablesWithArrays(table, tenantId, null, false, getUrl()); Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); conn = DriverManager.getConnection(getUrl(), props); String query = "SELECT a_string_array[1] FROM " + table + " WHERE 'XYZWER' = ANY(a_string_array)"; PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); String[] strArr = new String[1]; strArr[0] = "ABC"; String result = rs.getString(1); assertEquals(result, strArr[0]); assertFalse(rs.next()); query = "SELECT a_string_array[1] FROM " + table + " WHERE 'AB' = ANY(a_string_array)"; statement = conn.prepareStatement(query); rs = statement.executeQuery(); assertTrue(rs.next()); result = rs.getString(1); assertEquals(result, strArr[0]); assertFalse(rs.next()); } finally { if (conn != null) { conn.close(); } } } @Test public void testSelectWithArrayWithColumnRef() throws Exception { String tenantId = getOrganizationId(); String table = createTableWithArray(getUrl(), getDefaultSplits(tenantId), null); initTablesWithArrays(table, tenantId, null, false, getUrl()); String query = "SELECT a_integer,ARRAY[1,2,a_integer] FROM " + table + " where organization_id = '" + tenantId + "'"; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); try { PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); int val = rs.getInt(1); assertEquals(val, 1); Array array = rs.getArray(2); // Need to support primitive Integer[] intArr = new Integer[3]; intArr[0] = 1; intArr[1] = 2; intArr[2] = 1; Array resultArr = conn.createArrayOf("INTEGER", intArr); assertEquals(resultArr, array); assertEquals("[1, 2, 1]", rs.getString(2)); assertFalse(rs.next()); } finally { conn.close(); } } @Test public void testSelectWithArrayWithColumnRefWithVarLengthArray() throws Exception { String tenantId = getOrganizationId(); String table = createTableWithArray(getUrl(), getDefaultSplits(tenantId), null); initTablesWithArrays(table, tenantId, null, false, getUrl()); String query = "SELECT b_string,ARRAY['abc','defgh',b_string] FROM " + table + " where organization_id = '" + tenantId + "'"; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); try { PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); String val = rs.getString(1); assertEquals(val, "b"); Array array = rs.getArray(2); // Need to support primitive String[] strArr = new String[3]; strArr[0] = "abc"; strArr[1] = "defgh"; strArr[2] = "b"; Array resultArr = conn.createArrayOf("VARCHAR", strArr); assertEquals(resultArr, array); // since array is var length, last string element is messed up String expectedPrefix = "['abc', 'defgh', 'b"; assertTrue("Expected to start with " + expectedPrefix, rs.getString(2).startsWith(expectedPrefix)); assertFalse(rs.next()); } finally { conn.close(); } } @Test public void testSelectWithArrayWithColumnRefWithVarLengthArrayWithNullValue() throws Exception { String tenantId = getOrganizationId(); String table = createTableWithArray(getUrl(), getDefaultSplits(tenantId), null); initTablesWithArrays(table, tenantId, null, false, getUrl()); String query = "SELECT b_string,ARRAY['abc',null,'bcd',null,null,b_string] FROM " + table + " where organization_id = '" + tenantId + "'"; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); try { PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); String val = rs.getString(1); assertEquals(val, "b"); Array array = rs.getArray(2); // Need to support primitive String[] strArr = new String[6]; strArr[0] = "abc"; strArr[1] = null; strArr[2] = "bcd"; strArr[3] = null; strArr[4] = null; strArr[5] = "b"; Array resultArr = conn.createArrayOf("VARCHAR", strArr); assertEquals(resultArr, array); String expectedPrefix = "['abc', null, 'bcd', null, null, 'b"; assertTrue("Expected to start with " + expectedPrefix, rs.getString(2).startsWith(expectedPrefix)); assertFalse(rs.next()); } finally { conn.close(); } } @Test public void testUpsertSelectWithColumnRef() throws Exception { String tenantId = getOrganizationId(); String table1 = createTableWithArray(getUrl(), getDefaultSplits(tenantId), null); Connection conn = null; try { String table2 = createSimpleTableWithArray(getUrl(), getDefaultSplits(tenantId), null); initSimpleArrayTable(table2, tenantId, null, false); Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); conn = DriverManager.getConnection(getUrl(), props); String query = "upsert into " + table1 + " (ORGANIZATION_ID,ENTITY_ID, a_unsigned_double, a_double_array) " + "SELECT organization_id, entity_id, x_double, ARRAY[23.4, 22.1, x_double] FROM " + table2 + " WHERE a_double_array[2] = 89.96"; PreparedStatement statement = conn.prepareStatement(query); int executeUpdate = statement.executeUpdate(); assertEquals(1, executeUpdate); conn.commit(); statement.close(); conn.close(); // create another connection props = PropertiesUtil.deepCopy(TEST_PROPERTIES); conn = DriverManager.getConnection(getUrl(), props); query = "SELECT ARRAY_ELEM(a_double_array,2) FROM " + table1; statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); // Need to support primitive Double[] doubleArr = new Double[1]; doubleArr[0] = 22.1d; Double result = rs.getDouble(1); assertEquals(result, doubleArr[0]); assertFalse(rs.next()); } finally { if (conn != null) { conn.close(); } } } @Test public void testCharArraySpecificIndex() throws Exception { String tenantId = getOrganizationId(); String table = createSimpleTableWithArray(getUrl(), getDefaultSplits(tenantId), null); initSimpleArrayTable(table, tenantId, null, false); String query = "SELECT a_char_array[2] FROM " + table; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); try { PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); String[] charArr = new String[1]; charArr[0] = "b"; String result = rs.getString(1); assertEquals(charArr[0], result); } finally { conn.close(); } } @Test public void testArrayWithDescOrder() throws Exception { Connection conn; PreparedStatement stmt; ResultSet rs; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); conn = DriverManager.getConnection(getUrl(), props); String table = generateUniqueName(); conn.createStatement().execute( "CREATE TABLE " + table + " ( k VARCHAR, a_string_array VARCHAR(100) ARRAY[4], b_string_array VARCHAR(100) ARRAY[4] \n" + " CONSTRAINT pk PRIMARY KEY (k, b_string_array DESC)) \n"); conn.close(); conn = DriverManager.getConnection(getUrl(), props); stmt = conn.prepareStatement("UPSERT INTO " + table + " VALUES(?,?,?)"); stmt.setString(1, "a"); String[] s = new String[] { "abc", "def", "ghi", "jkll", null, null, "xxx" }; Array array = conn.createArrayOf("VARCHAR", s); stmt.setArray(2, array); s = new String[] { "abc", "def", "ghi", "jkll", null, null, null, "xxx" }; array = conn.createArrayOf("VARCHAR", s); stmt.setArray(3, array); stmt.execute(); conn.commit(); conn.close(); conn = DriverManager.getConnection(getUrl(), props); rs = conn.createStatement().executeQuery("SELECT b_string_array FROM " + table); assertTrue(rs.next()); PhoenixArray strArr = (PhoenixArray)rs.getArray(1); assertEquals(array, strArr); assertEquals("['abc', 'def', 'ghi', 'jkll', null, null, null, 'xxx']", rs.getString(1)); conn.close(); } @Test public void testArrayWithFloatArray() throws Exception { Connection conn; PreparedStatement stmt; ResultSet rs; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); conn = DriverManager.getConnection(getUrl(), props); String table = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + table + " ( k VARCHAR PRIMARY KEY, a Float ARRAY[])"); conn.close(); conn = DriverManager.getConnection(getUrl(), props); stmt = conn.prepareStatement("UPSERT INTO " + table + " VALUES('a',ARRAY[2.0,3.0])"); int res = stmt.executeUpdate(); assertEquals(1, res); conn.commit(); conn.close(); conn = DriverManager.getConnection(getUrl(), props); rs = conn.createStatement().executeQuery("SELECT ARRAY_ELEM(a,2) FROM " + table); assertTrue(rs.next()); Float f = new Float(3.0); assertEquals(f, (Float)rs.getFloat(1)); conn.close(); } @Test public void testArrayWithVarCharArray() throws Exception { Connection conn; PreparedStatement stmt; ResultSet rs; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); conn = DriverManager.getConnection(getUrl(), props); String table = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + table + " ( k VARCHAR PRIMARY KEY, a VARCHAR ARRAY[])"); conn.close(); conn = DriverManager.getConnection(getUrl(), props); stmt = conn.prepareStatement("UPSERT INTO " + table + " VALUES('a',ARRAY['a',null])"); int res = stmt.executeUpdate(); assertEquals(1, res); conn.commit(); conn.close(); conn = DriverManager.getConnection(getUrl(), props); rs = conn.createStatement().executeQuery("SELECT ARRAY_ELEM(a,2) FROM " + table); assertTrue(rs.next()); assertEquals(null, rs.getString(1)); conn.close(); } @Test public void testArraySelectSingleArrayElemWithCast() throws Exception { Connection conn; PreparedStatement stmt; ResultSet rs; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); conn = DriverManager.getConnection(getUrl(), props); String table = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + table + " ( k VARCHAR PRIMARY KEY, a bigint ARRAY[])"); conn.close(); conn = DriverManager.getConnection(getUrl(), props); stmt = conn.prepareStatement("UPSERT INTO " + table + " VALUES(?,?)"); stmt.setString(1, "a"); Long[] s = new Long[] {1l, 2l}; Array array = conn.createArrayOf("BIGINT", s); stmt.setArray(2, array); stmt.execute(); conn.commit(); conn.close(); conn = DriverManager.getConnection(getUrl(), props); rs = conn.createStatement().executeQuery("SELECT k, CAST(a[2] AS DOUBLE) FROM " + table); assertTrue(rs.next()); assertEquals("a",rs.getString(1)); Double d = new Double(2.0); assertEquals(d, (Double)rs.getDouble(2)); conn.close(); } @Test public void testArraySelectGetString() throws Exception { Connection conn; PreparedStatement stmt; String tenantId = getOrganizationId(); // create the table String tableName = createTableWithAllArrayTypes(getUrl(), getDefaultSplits(tenantId), null); // populate the table with data Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); conn = DriverManager.getConnection(getUrl(), props); stmt = conn.prepareStatement("UPSERT INTO " + tableName + "(ORGANIZATION_ID, ENTITY_ID, BOOLEAN_ARRAY, BYTE_ARRAY, DOUBLE_ARRAY, FLOAT_ARRAY, INT_ARRAY, LONG_ARRAY, SHORT_ARRAY, STRING_ARRAY)\n" + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); stmt.setString(1, tenantId); stmt.setString(2, ROW1); // boolean array Array boolArray = conn.createArrayOf("BOOLEAN", new Boolean[] { true, false }); int boolIndex = 3; stmt.setArray(boolIndex, boolArray); // byte array Array byteArray = conn.createArrayOf("TINYINT", new Byte[] { 11, 22 }); int byteIndex = 4; stmt.setArray(byteIndex, byteArray); // double array Array doubleArray = conn.createArrayOf("DOUBLE", new Double[] { 67.78, 78.89 }); int doubleIndex = 5; stmt.setArray(doubleIndex, doubleArray); // float array Array floatArray = conn.createArrayOf("FLOAT", new Float[] { 12.23f, 45.56f }); int floatIndex = 6; stmt.setArray(floatIndex, floatArray); // int array Array intArray = conn.createArrayOf("INTEGER", new Integer[] { 5555, 6666 }); int intIndex = 7; stmt.setArray(intIndex, intArray); // long array Array longArray = conn.createArrayOf("BIGINT", new Long[] { 7777777L, 8888888L }); int longIndex = 8; stmt.setArray(longIndex, longArray); // short array Array shortArray = conn.createArrayOf("SMALLINT", new Short[] { 333, 444 }); int shortIndex = 9; stmt.setArray(shortIndex, shortArray); // create character array Array stringArray = conn.createArrayOf("VARCHAR", new String[] { "a", "b" }); int stringIndex = 10; stmt.setArray(stringIndex, stringArray); stmt.execute(); conn.commit(); conn.close(); conn = DriverManager.getConnection(getUrl(), props); stmt = conn.prepareStatement("SELECT organization_id, entity_id, boolean_array, byte_array, double_array, float_array, int_array, long_array, short_array, string_array FROM " + tableName); TestUtil.analyzeTable(conn, tableName); ResultSet rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals(tenantId, rs.getString(1)); assertEquals(ROW1, rs.getString(2)); assertArrayGetString(rs, boolIndex, boolArray, "true, false"); assertArrayGetString(rs, byteIndex, byteArray, "11, 22"); assertArrayGetString(rs, doubleIndex, doubleArray, "67.78, 78.89"); assertArrayGetString(rs, floatIndex, floatArray, "12.23, 45.56"); assertArrayGetString(rs, intIndex, intArray, "5555, 6666"); assertArrayGetString(rs, longIndex, longArray, "7777777, 8888888"); assertArrayGetString(rs, shortIndex, shortArray, "333, 444"); assertArrayGetString(rs, stringIndex, stringArray, "'a', 'b'"); conn.close(); } @Test public void testArrayWithCast() throws Exception { Connection conn; PreparedStatement stmt; ResultSet rs; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); conn = DriverManager.getConnection(getUrl(), props); String table = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + table + " ( k VARCHAR PRIMARY KEY, a bigint ARRAY[])"); conn.close(); conn = DriverManager.getConnection(getUrl(), props); stmt = conn.prepareStatement("UPSERT INTO " + table + " VALUES(?,?)"); stmt.setString(1, "a"); Long[] s = new Long[] { 1l, 2l }; Array array = conn.createArrayOf("BIGINT", s); stmt.setArray(2, array); stmt.execute(); conn.commit(); conn.close(); conn = DriverManager.getConnection(getUrl(), props); rs = conn.createStatement().executeQuery("SELECT CAST(a AS DOUBLE []) FROM " + table); assertTrue(rs.next()); Double[] d = new Double[] { 1.0, 2.0 }; array = conn.createArrayOf("DOUBLE", d); PhoenixArray arr = (PhoenixArray)rs.getArray(1); assertEquals(array, arr); assertEquals("[1.0, 2.0]", rs.getString(1)); conn.close(); } @Test public void testArrayWithCastForVarLengthArr() throws Exception { Connection conn; PreparedStatement stmt; ResultSet rs; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); conn = DriverManager.getConnection(getUrl(), props); String table = generateUniqueName(); conn.createStatement().execute("CREATE TABLE " + table + " ( k VARCHAR PRIMARY KEY, a VARCHAR(5) ARRAY)"); conn.close(); conn = DriverManager.getConnection(getUrl(), props); stmt = conn.prepareStatement("UPSERT INTO " + table + " VALUES(?,?)"); stmt.setString(1, "a"); String[] s = new String[] { "1", "2" }; PhoenixArray array = (PhoenixArray)conn.createArrayOf("VARCHAR", s); stmt.setArray(2, array); stmt.execute(); conn.commit(); conn.close(); conn = DriverManager.getConnection(getUrl(), props); rs = conn.createStatement().executeQuery("SELECT CAST(a AS CHAR ARRAY) FROM " + table); assertTrue(rs.next()); PhoenixArray arr = (PhoenixArray)rs.getArray(1); String[] array2 = (String[])array.getArray(); String[] array3 = (String[])arr.getArray(); assertEquals(array2[0], array3[0]); assertEquals(array2[1], array3[1]); assertEquals("['1', '2']", rs.getString(1)); conn.close(); } }
ankitsinghal/phoenix
phoenix-core/src/it/java/org/apache/phoenix/end2end/Array1IT.java
Java
apache-2.0
43,461
package org.cloudysunny14.persistence.jpa.eclipselink.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Lob; @Entity public class Huge { @Id private String id; @Lob @Column(length = 1 << 20) private byte[] data; public Huge() { } public Huge(String id, byte[] data) { this.id = id; this.data = data; } }
cloudysunny14/infinispan-jpa-eclipselink-store
src/test/java/org/cloudysunny14/persistence/jpa/eclipselink/entity/Huge.java
Java
apache-2.0
438