text
stringlengths
7
1.01M
package com.slidingmenu.lib.app; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup.LayoutParams; import com.google.android.maps.MapActivity; import com.slidingmenu.lib.SlidingMenu; public abstract class SlidingMapActivity extends MapActivity implements SlidingActivityBase { private SlidingActivityHelper mHelper; /* (non-Javadoc) * @see com.google.android.maps.MapActivity#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHelper = new SlidingActivityHelper(this); mHelper.onCreate(savedInstanceState); } /* (non-Javadoc) * @see android.app.Activity#onPostCreate(android.os.Bundle) */ @Override public void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mHelper.onPostCreate(savedInstanceState); } /* (non-Javadoc) * @see android.app.Activity#findViewById(int) */ @Override public View findViewById(int id) { View v = super.findViewById(id); if (v != null) return v; return mHelper.findViewById(id); } /* (non-Javadoc) * @see android.app.Activity#onSaveInstanceState(android.os.Bundle) */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mHelper.onSaveInstanceState(outState); } /* (non-Javadoc) * @see android.app.Activity#setContentView(int) */ @Override public void setContentView(int id) { setContentView(getLayoutInflater().inflate(id, null)); } /* (non-Javadoc) * @see android.app.Activity#setContentView(android.view.View) */ @Override public void setContentView(View v) { setContentView(v, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } /* (non-Javadoc) * @see android.app.Activity#setContentView(android.view.View, android.view.ViewGroup.LayoutParams) */ @Override public void setContentView(View v, LayoutParams params) { super.setContentView(v, params); mHelper.registerAboveContentView(v, params); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#setBehindContentView(int) */ public void setBehindContentView(int id) { setBehindContentView(getLayoutInflater().inflate(id, null)); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#setBehindContentView(android.view.View) */ public void setBehindContentView(View v) { setBehindContentView(v, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#setBehindContentView(android.view.View, android.view.ViewGroup.LayoutParams) */ public void setBehindContentView(View v, LayoutParams params) { mHelper.setBehindContentView(v, params); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#getSlidingMenu() */ public SlidingMenu getSlidingMenu() { return mHelper.getSlidingMenu(); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#toggle() */ public void toggle() { mHelper.toggle(); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#showAbove() */ public void showContent() { mHelper.showContent(); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#showBehind() */ public void showMenu() { mHelper.showMenu(); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#showSecondaryMenu() */ public void showSecondaryMenu() { mHelper.showSecondaryMenu(); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#setSlidingActionBarEnabled(boolean) */ public void setSlidingActionBarEnabled(boolean b) { mHelper.setSlidingActionBarEnabled(b); } /* (non-Javadoc) * @see android.app.Activity#onKeyUp(int, android.view.KeyEvent) */ @Override public boolean onKeyUp(int keyCode, KeyEvent event) { boolean b = mHelper.onKeyUp(keyCode, event); if (b) return b; return super.onKeyUp(keyCode, event); } }
/* * Copyright (c) 2006-2017 DMDirc Developers * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.dmdirc.addons.scriptplugin; import com.dmdirc.commandline.CommandLineOptionsModule.Directory; import com.dmdirc.commandparser.BaseCommandInfo; import com.dmdirc.commandparser.CommandArguments; import com.dmdirc.commandparser.CommandInfo; import com.dmdirc.commandparser.CommandType; import com.dmdirc.commandparser.commands.BaseCommand; import com.dmdirc.commandparser.commands.IntelligentCommand; import com.dmdirc.commandparser.commands.context.CommandContext; import com.dmdirc.config.GlobalConfig; import com.dmdirc.interfaces.CommandController; import com.dmdirc.interfaces.WindowModel; import com.dmdirc.config.provider.AggregateConfigProvider; import com.dmdirc.plugins.PluginDomain; import com.dmdirc.ui.input.AdditionalTabTargets; import javax.annotation.Nonnull; import javax.inject.Inject; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Map; import java.util.stream.Collectors; /** * The Script Command allows controlling of the script plugin. */ public class ScriptCommand extends BaseCommand implements IntelligentCommand { /** A command info object for this command. */ public static final CommandInfo INFO = new BaseCommandInfo("script", "script - Allows controlling the script plugin", CommandType.TYPE_GLOBAL); /** Global config to read settings from. */ private final AggregateConfigProvider globalConfig; /** Plugin settings domain. */ private final String domain; /** Manager used to retrieve script engines. */ private final ScriptEngineManager scriptEngineManager; /** Script directory. */ private final String scriptDirectory; /** Script manager to handle scripts. */ private final ScriptManager scriptManager; /** * Creates a new instance of this command. * * @param scriptManager Used to manage scripts * @param globalConfig Global config * @param commandController The controller to use for command information. * @param domain This plugin's settings domain * @param scriptEngineManager Manager used to get script engines * @param scriptDirectory Directory to store scripts */ @Inject public ScriptCommand(final ScriptManager scriptManager, @Directory(ScriptModule.SCRIPTS) final String scriptDirectory, @GlobalConfig final AggregateConfigProvider globalConfig, final CommandController commandController, @PluginDomain(ScriptPlugin.class) final String domain, final ScriptEngineManager scriptEngineManager) { super(commandController); this.globalConfig = globalConfig; this.domain = domain; this.scriptEngineManager = scriptEngineManager; this.scriptDirectory = scriptDirectory; this.scriptManager = scriptManager; } @Override public void execute(@Nonnull final WindowModel origin, final CommandArguments args, final CommandContext context) { final String[] sargs = args.getArguments(); if (sargs.length > 0 && ("rehash".equalsIgnoreCase(sargs[0]) || "reload".equalsIgnoreCase(sargs[0]))) { showOutput(origin, args.isSilent(), "Reloading scripts"); scriptManager.rehash(); } else if (sargs.length > 0 && "load".equalsIgnoreCase(sargs[0])) { if (sargs.length > 1) { final String filename = args.getArgumentsAsString(1); showOutput(origin, args.isSilent(), "Loading: " + filename + " [" + scriptManager.loadScript(scriptDirectory + filename) + ']'); } else { showError(origin, args.isSilent(), "You must specify a script to load"); } } else if (sargs.length > 0 && "unload".equalsIgnoreCase(sargs[0])) { if (sargs.length > 1) { final String filename = args.getArgumentsAsString(1); showOutput(origin, args.isSilent(), "Unloading: " + filename + " [" + scriptManager.loadScript(scriptDirectory + filename) + ']'); } else { showError(origin, args.isSilent(), "You must specify a script to unload"); } } else if (sargs.length > 0 && "eval".equalsIgnoreCase(sargs[0])) { if (sargs.length > 1) { final String script = args.getArgumentsAsString(1); showOutput(origin, args.isSilent(), "Evaluating: " + script); try { final ScriptEngineWrapper wrapper; if (globalConfig.hasOptionString(domain, "eval.baseFile")) { final String baseFile = scriptDirectory + '/' + globalConfig.getOption(domain, "eval.baseFile"); if (new File(baseFile).exists()) { wrapper = new ScriptEngineWrapper(scriptEngineManager, baseFile); } else { wrapper = new ScriptEngineWrapper(scriptEngineManager, null); } } else { wrapper = new ScriptEngineWrapper(scriptEngineManager, null); } wrapper.getScriptEngine().put("cmd_origin", origin); wrapper.getScriptEngine().put("cmd_isSilent", args.isSilent()); wrapper.getScriptEngine().put("cmd_args", sargs); showOutput(origin, args.isSilent(), "Result: " + wrapper.getScriptEngine().eval(script)); } catch (ScriptException e) { showOutput(origin, args.isSilent(), "Exception: " + e + " -> " + e.getMessage()); if (globalConfig.getOptionBool(domain, "eval.showStackTrace")) { final String[] stacktrace = getTrace(e); for (String line : stacktrace) { showOutput(origin, args.isSilent(), "Stack trace: " + line); } } } } else { showError(origin, args.isSilent(), "You must specify some script to eval."); } } else if (sargs.length > 0 && "savetobasefile".equalsIgnoreCase(sargs[0])) { if (sargs.length > 2) { final String[] bits = sargs[1].split("/"); final String functionName = bits[0]; final String script = args.getArgumentsAsString(2); showOutput(origin, args.isSilent(), "Saving as '" + functionName + "': " + script); if (globalConfig.hasOptionString(domain, "eval.baseFile")) { try { final String baseFile = scriptDirectory + '/' + globalConfig.getOption(domain, "eval.baseFile"); try (FileWriter writer = new FileWriter(baseFile, true)) { writer.write("function "); writer.write(functionName); writer.write("("); for (int i = 1; i < bits.length; i++) { writer.write(bits[i]); writer.write(" "); } writer.write(") {\n"); writer.write(script); writer.write("\n}\n"); writer.flush(); } } catch (IOException ioe) { showError(origin, args.isSilent(), "IOException: " + ioe.getMessage()); } } else { showError(origin, args.isSilent(), "No baseFile specified, please /set " + domain + " eval.baseFile filename (stored in scripts dir of profile)"); } } else if (sargs.length > 1) { showError(origin, args.isSilent(), "You must specify some script to save."); } else { showError(origin, args.isSilent(), "You must specify a function name and some script to save."); } } else if (sargs.length > 0 && "help".equalsIgnoreCase(sargs[0])) { showOutput(origin, args.isSilent(), "This command allows you to interact with the script plugin"); showOutput(origin, args.isSilent(), "-------------------"); showOutput(origin, args.isSilent(), "reload/rehash - Reload all loaded scripts"); showOutput(origin, args.isSilent(), "load <script> - load scripts/<script> (file name relative to scripts dir)"); showOutput(origin, args.isSilent(), "unload <script> - unload <script> (full file name)"); showOutput(origin, args.isSilent(), "eval <script> - evaluate the code <script> and return the result"); showOutput(origin, args.isSilent(), "savetobasefile <name> <script> - save the code <script> to the eval basefile (" + domain + ".eval.basefile)"); showOutput(origin, args.isSilent(), " as the function <name> (name/foo/bar will save it as 'name' with foo and"); showOutput(origin, args.isSilent(), " bar as arguments."); showOutput(origin, args.isSilent(), "-------------------"); } else { showError(origin, args.isSilent(), "Unknown subcommand."); } } @Override public AdditionalTabTargets getSuggestions(final int arg, final IntelligentCommandContext context) { final AdditionalTabTargets res = new AdditionalTabTargets(); res.excludeAll(); if (arg == 0) { res.add("help"); res.add("rehash"); res.add("reload"); res.add("load"); res.add("unload"); res.add("eval"); res.add("savetobasefile"); } else if (arg == 1) { final Map<String, ScriptEngineWrapper> scripts = scriptManager.getScripts(); if ("load".equalsIgnoreCase(context.getPreviousArgs().get(0))) { res.addAll(scriptManager.getPossibleScripts().stream() .collect(Collectors.toList())); } else if ("unload".equalsIgnoreCase(context.getPreviousArgs().get(0))) { res.addAll(scripts.keySet().stream().collect(Collectors.toList())); } } return res; } /** * Converts an exception into a string array. * * @param throwable Exception to convert * * @return Exception string array */ private static String[] getTrace(final Throwable throwable) { String[] trace; if (throwable == null) { trace = new String[0]; } else { final StackTraceElement[] traceElements = throwable.getStackTrace(); trace = new String[traceElements.length + 1]; trace[0] = throwable.toString(); for (int i = 0; i < traceElements.length; i++) { trace[i + 1] = traceElements[i].toString(); } if (throwable.getCause() != null) { final String[] causeTrace = getTrace(throwable.getCause()); final String[] newTrace = new String[trace.length + causeTrace.length]; trace[0] = "\nWhich caused: " + trace[0]; System.arraycopy(causeTrace, 0, newTrace, 0, causeTrace.length); System.arraycopy(trace, 0, newTrace, causeTrace.length, trace.length); trace = newTrace; } } return trace; } }
package cn.rongcloud.im; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.v4.app.FragmentActivity; import android.text.TextUtils; import android.util.Log; import android.view.View; import java.util.HashMap; import java.util.Map; import java.util.Stack; import cn.rongcloud.im.db.DBManager; import cn.rongcloud.im.db.Friend; import cn.rongcloud.im.message.provider.RealTimeLocationInputProvider; import cn.rongcloud.im.server.broadcast.BroadcastManager; import cn.rongcloud.im.server.network.http.HttpException; import cn.rongcloud.im.server.response.ContactNotificationMessageData; import cn.rongcloud.im.server.utils.NLog; import cn.rongcloud.im.server.utils.RongGenerate; import cn.rongcloud.im.server.utils.json.JsonMananger; import cn.rongcloud.im.ui.activity.AMAPLocationActivity; import cn.rongcloud.im.ui.activity.NewFriendListActivity; import cn.rongcloud.im.ui.activity.PersonalProfileActivity; import cn.rongcloud.im.ui.activity.RealTimeLocationActivity; import io.rong.imkit.RongContext; import io.rong.imkit.RongIM; import io.rong.imkit.model.GroupUserInfo; import io.rong.imkit.model.UIConversation; import io.rong.imkit.widget.AlterDialogFragment; import io.rong.imkit.widget.provider.ImageInputProvider; import io.rong.imkit.widget.provider.InputProvider; import io.rong.imkit.widget.provider.LocationInputProvider; import io.rong.imlib.RongIMClient; import io.rong.imlib.location.RealTimeLocationConstant; import io.rong.imlib.location.message.RealTimeLocationStartMessage; import io.rong.imlib.model.Conversation; import io.rong.imlib.model.Group; import io.rong.imlib.model.Message; import io.rong.imlib.model.MessageContent; import io.rong.imlib.model.UserInfo; import io.rong.message.ContactNotificationMessage; import io.rong.message.GroupNotificationMessage; import io.rong.message.ImageMessage; import io.rong.message.LocationMessage; /** * 融云相关监听 事件集合类 * Created by AMing on 16/1/7. * Company RongCloud */ public class SealAppContext implements RongIM.ConversationListBehaviorListener, RongIMClient.OnReceiveMessageListener, RongIM.UserInfoProvider, RongIM.GroupInfoProvider, RongIM.GroupUserInfoProvider, RongIMClient.ConnectionStatusListener, RongIM.LocationProvider, RongIM.ConversationBehaviorListener { public static final String UPDATEFRIEND = "updatefriend"; public static final String UPDATEREDDOT = "updatereddot"; private Context mContext; private static SealAppContext mRongCloudInstance; private RongIM.LocationProvider.LocationCallback mLastLocationCallback; private Stack<Map<String, Activity>> mActivityStack; public SealAppContext(Context mContext) { this.mContext = mContext; initListener(); mActivityStack = new Stack<>(); } /** * 初始化 RongCloud. * * @param context 上下文。 */ public static void init(Context context) { if (mRongCloudInstance == null) { synchronized (SealAppContext.class) { if (mRongCloudInstance == null) { mRongCloudInstance = new SealAppContext(context); } } } } public boolean pushActivity(Conversation.ConversationType conversationType, String targetId, Activity activity) { if (conversationType == null || targetId == null || activity == null) return false; String key = conversationType.getName() + targetId; Map<String, Activity> map = new HashMap<>(); map.put(key, activity); mActivityStack.push(map); return true; } public boolean popActivity(Conversation.ConversationType conversationType, String targetId) { if (conversationType == null || targetId == null) return false; String key = conversationType.getName() + targetId; Map<String, Activity> map = mActivityStack.peek(); if (map.containsKey(key)) { mActivityStack.pop(); return true; } return false; } public boolean containsInQue(Conversation.ConversationType conversationType, String targetId) { if (conversationType == null || targetId == null) return false; String key = conversationType.getName() + targetId; Map<String, Activity> map = mActivityStack.peek(); return map.containsKey(key); } /** * 获取RongCloud 实例。 * * @return RongCloud。 */ public static SealAppContext getInstance() { return mRongCloudInstance; } /** * init 后就能设置的监听 */ private void initListener() { RongIM.setConversationBehaviorListener(this);//设置会话界面操作的监听器。 RongIM.setConversationListBehaviorListener(this); RongIM.setUserInfoProvider(this, true); RongIM.setGroupInfoProvider(this, true); RongIM.setLocationProvider(this);//设置地理位置提供者,不用位置的同学可以注掉此行代码 setInputProvider(); setUserInfoEngineListener(); // RongIM.setGroupUserInfoProvider(this, true); } private void setInputProvider() { RongIM.setOnReceiveMessageListener(this); RongIM.setConnectionStatusListener(this); InputProvider.ExtendProvider[] singleProvider = { new ImageInputProvider(RongContext.getInstance()), new RealTimeLocationInputProvider(RongContext.getInstance()) //带位置共享的地理位置 }; InputProvider.ExtendProvider[] muiltiProvider = { new ImageInputProvider(RongContext.getInstance()), new LocationInputProvider(RongContext.getInstance()),//地理位置 }; RongIM.resetInputExtensionProvider(Conversation.ConversationType.PRIVATE, singleProvider); RongIM.resetInputExtensionProvider(Conversation.ConversationType.DISCUSSION, muiltiProvider); RongIM.resetInputExtensionProvider(Conversation.ConversationType.CUSTOMER_SERVICE, muiltiProvider); RongIM.resetInputExtensionProvider(Conversation.ConversationType.GROUP, muiltiProvider); RongIM.resetInputExtensionProvider(Conversation.ConversationType.CHATROOM, muiltiProvider); } /** * 需要 rongcloud connect 成功后设置的 listener */ public void setUserInfoEngineListener() { UserInfoEngine.getInstance(mContext).setListener(new UserInfoEngine.UserInfoListener() { @Override public void onResult(UserInfo info) { if (info != null && RongIM.getInstance() != null) { if (TextUtils.isEmpty(String.valueOf(info.getPortraitUri()))) { info.setPortraitUri(Uri.parse(RongGenerate.generateDefaultAvatar(info.getName(), info.getUserId()))); } NLog.e("UserInfoEngine", info.getName() + info.getPortraitUri()); RongIM.getInstance().refreshUserInfoCache(info); } } }); GroupInfoEngine.getInstance(mContext).setmListener(new GroupInfoEngine.GroupInfoListeners() { @Override public void onResult(Group info) { if (info != null && RongIM.getInstance() != null) { NLog.e("GroupInfoEngine:" + info.getId() + "----" + info.getName() + "----" + info.getPortraitUri()); if (TextUtils.isEmpty(String.valueOf(info.getPortraitUri()))) { info.setPortraitUri(Uri.parse(RongGenerate.generateDefaultAvatar(info.getName(), info.getId()))); } RongIM.getInstance().refreshGroupInfoCache(info); } } }); } @Override public boolean onConversationPortraitClick(Context context, Conversation.ConversationType conversationType, String s) { return false; } @Override public boolean onConversationPortraitLongClick(Context context, Conversation.ConversationType conversationType, String s) { return false; } @Override public boolean onConversationLongClick(Context context, View view, UIConversation uiConversation) { return false; } @Override public boolean onConversationClick(Context context, View view, UIConversation uiConversation) { MessageContent messageContent = uiConversation.getMessageContent(); if (messageContent instanceof ContactNotificationMessage) { ContactNotificationMessage contactNotificationMessage = (ContactNotificationMessage) messageContent; if (contactNotificationMessage.getOperation().equals("AcceptResponse")) { // 被加方同意请求后 if (contactNotificationMessage.getExtra() != null) { ContactNotificationMessageData bean = null; try { bean = JsonMananger.jsonToBean(contactNotificationMessage.getExtra(), ContactNotificationMessageData.class); } catch (HttpException e) { e.printStackTrace(); } RongIM.getInstance().startPrivateChat(context, uiConversation.getConversationSenderId(), bean.getSourceUserNickname()); } } else { context.startActivity(new Intent(context, NewFriendListActivity.class)); } return true; } return false; } @Override public boolean onReceived(Message message, int i) { MessageContent messageContent = message.getContent(); if (messageContent instanceof ContactNotificationMessage) { ContactNotificationMessage contactNotificationMessage = (ContactNotificationMessage) messageContent; if (contactNotificationMessage.getOperation().equals("Request")) { //对方发来好友邀请 BroadcastManager.getInstance(mContext).sendBroadcast(SealAppContext.UPDATEREDDOT); } else if (contactNotificationMessage.getOperation().equals("AcceptResponse")) { //对方同意我的好友请求 ContactNotificationMessageData c = null; try { c = JsonMananger.jsonToBean(contactNotificationMessage.getExtra(), ContactNotificationMessageData.class); } catch (HttpException e) { e.printStackTrace(); } if (c != null) { DBManager.getInstance(mContext).getDaoSession().getFriendDao().insertOrReplace(new Friend(contactNotificationMessage.getSourceUserId(), c.getSourceUserNickname(), null, null, null, null)); } BroadcastManager.getInstance(mContext).sendBroadcast(UPDATEFRIEND); BroadcastManager.getInstance(mContext).sendBroadcast(SealAppContext.UPDATEREDDOT); } // // 发广播通知更新好友列表 // BroadcastManager.getInstance(mContext).sendBroadcast(UPDATEREDDOT); // } } else if (messageContent instanceof GroupNotificationMessage) { GroupNotificationMessage groupNotificationMessage = (GroupNotificationMessage) messageContent; NLog.e("" + groupNotificationMessage.getMessage()); if (groupNotificationMessage.getOperation().equals("Kicked")) { } else if (groupNotificationMessage.getOperation().equals("Add")) { } else if (groupNotificationMessage.getOperation().equals("Quit")) { } else if (groupNotificationMessage.getOperation().equals("Rename")) { } } else if (messageContent instanceof ImageMessage) { ImageMessage imageMessage = (ImageMessage) messageContent; Log.e("imageMessage", imageMessage.getRemoteUri().toString()); } return false; } @Override public UserInfo getUserInfo(String s) { NLog.e("Rongcloudevent : getUserInfo:" + s); return UserInfoEngine.getInstance(mContext).startEngine(s); } @Override public Group getGroupInfo(String s) { NLog.e("Rongcloudevent : getGroupInfo:" + s); return GroupInfoEngine.getInstance(mContext).startEngine(s); } @Override public GroupUserInfo getGroupUserInfo(String groupId, String userId) { // return GroupUserInfoEngine.getInstance(mContext).startEngine(groupId, userId); return null; } @Override public void onChanged(ConnectionStatus connectionStatus) { if (connectionStatus.getMessage().equals(ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT)) { } } @Override public void onStartLocation(Context context, LocationCallback locationCallback) { /** * demo 代码 开发者需替换成自己的代码。 */ SealAppContext.getInstance().setLastLocationCallback(locationCallback); Intent intent = new Intent(context, AMAPLocationActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } @Override public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) { if (userInfo != null) { Intent intent = new Intent(context, PersonalProfileActivity.class); intent.putExtra("conversationType", conversationType.getValue()); intent.putExtra("userinfo", userInfo); context.startActivity(intent); } return true; } @Override public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) { return false; } @Override public boolean onMessageClick(final Context context, final View view, final Message message) { //real-time location message begin if (message.getContent() instanceof RealTimeLocationStartMessage) { RealTimeLocationConstant.RealTimeLocationStatus status = RongIMClient.getInstance().getRealTimeLocationCurrentState(message.getConversationType(), message.getTargetId()); // if (status == RealTimeLocationConstant.RealTimeLocationStatus.RC_REAL_TIME_LOCATION_STATUS_IDLE) { // startRealTimeLocation(context, message.getConversationType(), message.getTargetId()); // } else if (status == RealTimeLocationConstant.RealTimeLocationStatus.RC_REAL_TIME_LOCATION_STATUS_INCOMING) { final AlterDialogFragment alterDialogFragment = AlterDialogFragment.newInstance("", "加入位置共享", "取消", "加入"); alterDialogFragment.setOnAlterDialogBtnListener(new AlterDialogFragment.AlterDialogBtnListener() { @Override public void onDialogPositiveClick(AlterDialogFragment dialog) { RealTimeLocationConstant.RealTimeLocationStatus status = RongIMClient.getInstance().getRealTimeLocationCurrentState(message.getConversationType(), message.getTargetId()); if (status == null || status == RealTimeLocationConstant.RealTimeLocationStatus.RC_REAL_TIME_LOCATION_STATUS_IDLE) { startRealTimeLocation(context, message.getConversationType(), message.getTargetId()); } else { joinRealTimeLocation(context, message.getConversationType(), message.getTargetId()); } } @Override public void onDialogNegativeClick(AlterDialogFragment dialog) { alterDialogFragment.dismiss(); } }); alterDialogFragment.show(((FragmentActivity) context).getSupportFragmentManager()); } else { if (status != null && (status == RealTimeLocationConstant.RealTimeLocationStatus.RC_REAL_TIME_LOCATION_STATUS_OUTGOING || status == RealTimeLocationConstant.RealTimeLocationStatus.RC_REAL_TIME_LOCATION_STATUS_CONNECTED)) { Intent intent = new Intent(((FragmentActivity) context), RealTimeLocationActivity.class); intent.putExtra("conversationType", message.getConversationType().getValue()); intent.putExtra("targetId", message.getTargetId()); context.startActivity(intent); } } return true; } //real-time location message end /** * demo 代码 开发者需替换成自己的代码。 */ if (message.getContent() instanceof LocationMessage) { Intent intent = new Intent(context, AMAPLocationActivity.class); intent.putExtra("location", message.getContent()); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } else if (message.getContent() instanceof ImageMessage) { // Intent intent = new Intent(context, PhotoActivity.class); // intent.putExtra("message", message); // context.startActivity(intent); } return false; } private void startRealTimeLocation(Context context, Conversation.ConversationType conversationType, String targetId) { RongIMClient.getInstance().startRealTimeLocation(conversationType, targetId); Intent intent = new Intent(((FragmentActivity) context), RealTimeLocationActivity.class); intent.putExtra("conversationType", conversationType.getValue()); intent.putExtra("targetId", targetId); context.startActivity(intent); } private void joinRealTimeLocation(Context context, Conversation.ConversationType conversationType, String targetId) { RongIMClient.getInstance().joinRealTimeLocation(conversationType, targetId); Intent intent = new Intent(((FragmentActivity) context), RealTimeLocationActivity.class); intent.putExtra("conversationType", conversationType.getValue()); intent.putExtra("targetId", targetId); context.startActivity(intent); } @Override public boolean onMessageLinkClick(Context context, String s) { return false; } @Override public boolean onMessageLongClick(Context context, View view, Message message) { return false; } public RongIM.LocationProvider.LocationCallback getLastLocationCallback() { return mLastLocationCallback; } public void setLastLocationCallback(RongIM.LocationProvider.LocationCallback lastLocationCallback) { this.mLastLocationCallback = lastLocationCallback; } }
package com.san.allergy; import org.springframework.data.repository.CrudRepository; public interface AllergyRepository extends CrudRepository<Allergy, Integer> { }
/* * Copyright 2016 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.gradle.performance.fixture; import groovy.transform.CompileStatic; import org.gradle.performance.results.MeasuredOperationList; import org.gradle.profiler.BenchmarkResultCollector; @CompileStatic public class GradleVsMavenBuildExperimentRunner extends AbstractBuildExperimentRunner { private final GradleBuildExperimentRunner gradleRunner; private final MavenBuildExperimentRunner mavenRunner; public GradleVsMavenBuildExperimentRunner(BenchmarkResultCollector resultCollector) { super(resultCollector); this.gradleRunner = new GradleBuildExperimentRunner(resultCollector); this.mavenRunner = new MavenBuildExperimentRunner(resultCollector); } @Override public void doRun(BuildExperimentSpec experiment, MeasuredOperationList results) { if (experiment instanceof MavenBuildExperimentSpec) { mavenRunner.doRun(experiment, results); } else { gradleRunner.doRun(experiment, results); } } }
/* * Copyright 2015-2020 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.glue.model; import javax.annotation.Generated; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum CrawlerLineageSettings { ENABLE("ENABLE"), DISABLE("DISABLE"); private String value; private CrawlerLineageSettings(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return CrawlerLineageSettings corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static CrawlerLineageSettings fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (CrawlerLineageSettings enumEntry : CrawlerLineageSettings.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
/******************************************************************************* * Copyright (c) 1991, 2021 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ * or the Apache License, Version 2.0 which accompanies this distribution * and is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following * Secondary Licenses when the conditions for such availability set * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU * General Public License, version 2 with the GNU Classpath * Exception [1] and GNU General Public License, version 2 with the * OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] http://openjdk.java.net/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception *******************************************************************************/ /** * WARNING!!! GENERATED FILE * * This class is generated. * Do not use the Eclipse "Organize Imports" feature on this class. * * It can contain user content, but that content must be delimited with the * the tags * [BEGIN USER IMPORTS] * [END USER IMPORTS] * * or * * [BEGIN USER CODE] * [END USER CODE] * * These tags are entered as comments. Characters before [ and after ] are ignored. * Lines between the tags are inserted into the newly generated file. * * IMPORTS are combined and inserted above newly generated imports. CODE is combined * and inserted immediately after the class declaration * * All lines outside these tags are lost and replaced with newly generated code. */ package com.ibm.j9ddr.vm29.pointer.generated; /*[BEGIN USER IMPORTS]*/ /*[END USER IMPORTS]*/ import com.ibm.j9ddr.CorruptDataException; import com.ibm.j9ddr.vm29.pointer.*; import com.ibm.j9ddr.vm29.structure.*; import com.ibm.j9ddr.vm29.types.*; /** * Structure: SynchronizerInfoPointer * * A generated implementation of a VM structure * * This class contains generated code and MAY contain hand written user code. * * Hand written user code must be contained at the top of * the class file, specifically above * the comment line containing WARNING!!! GENERATED CODE * * ALL code below the GENERATED warning will be replaced with new generated code * each time the PointerGenerator utility is run. * * The generated code will provide getters for all elements in the SynchronizerInfoPointer * structure. Where possible, meaningful return types are inferred. * * The user may add methods to provide meaningful return types where only pointers * could be automatically inferred. */ @com.ibm.j9ddr.GeneratedPointerClass(structureClass=SynchronizerInfo.class) public class SynchronizerInfoPointer extends StructurePointer { // NULL public static final SynchronizerInfoPointer NULL = new SynchronizerInfoPointer(0); /*[BEGIN USER CODE]*/ /*[END USER CODE]*/ // Do not call this constructor. Use static method cast instead. protected SynchronizerInfoPointer(long address) { super(address); } public static SynchronizerInfoPointer cast(AbstractPointer structure) { return cast(structure.getAddress()); } public static SynchronizerInfoPointer cast(UDATA udata) { return cast(udata.longValue()); } public static SynchronizerInfoPointer cast(long address) { if (address == 0) { return NULL; } return new SynchronizerInfoPointer(address); } public SynchronizerInfoPointer add(long count) { return SynchronizerInfoPointer.cast(address + (SynchronizerInfo.SIZEOF * count)); } public SynchronizerInfoPointer add(Scalar count) { return add(count.longValue()); } public SynchronizerInfoPointer addOffset(long offset) { return SynchronizerInfoPointer.cast(address + offset); } public SynchronizerInfoPointer addOffset(Scalar offset) { return addOffset(offset.longValue()); } public SynchronizerInfoPointer sub(long count) { return SynchronizerInfoPointer.cast(address - (SynchronizerInfo.SIZEOF * count)); } public SynchronizerInfoPointer sub(Scalar count) { return sub(count.longValue()); } public SynchronizerInfoPointer subOffset(long offset) { return SynchronizerInfoPointer.cast(address - offset); } public SynchronizerInfoPointer subOffset(Scalar offset) { return subOffset(offset.longValue()); } public SynchronizerInfoPointer untag(long mask) { return SynchronizerInfoPointer.cast(address & ~mask); } public SynchronizerInfoPointer untag() { return untag(UDATA.SIZEOF - 1); } protected long sizeOfBaseType() { return SynchronizerInfo.SIZEOF; } // Implementation methods // SynchronizerInfo* next @com.ibm.j9ddr.GeneratedFieldAccessor(offsetFieldName="_nextOffset_", declaredType="SynchronizerInfo*") public SynchronizerInfoPointer next() throws CorruptDataException { return SynchronizerInfoPointer.cast(getPointerAtOffset(SynchronizerInfo._nextOffset_)); } // SynchronizerInfo* next public PointerPointer nextEA() throws CorruptDataException { return PointerPointer.cast(nonNullFieldEA(SynchronizerInfo._nextOffset_)); } // FlexObjectRef obj @com.ibm.j9ddr.GeneratedFieldAccessor(offsetFieldName="_objOffset_", declaredType="FlexObjectRef") public FlexObjectRefPointer obj() throws CorruptDataException { return FlexObjectRefPointer.cast(nonNullFieldEA(SynchronizerInfo._objOffset_)); } // FlexObjectRef obj public PointerPointer objEA() throws CorruptDataException { return PointerPointer.cast(nonNullFieldEA(SynchronizerInfo._objOffset_)); } }
/* Copyright (c) 2018 LinkedIn Corp. 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.linkedin.r2.netty.client.http2; import com.linkedin.common.callback.Callback; import com.linkedin.r2.netty.common.NettyChannelAttributes; import com.linkedin.r2.transport.http.client.AsyncPool; import com.linkedin.r2.transport.http.client.PoolStats; import com.linkedin.util.clock.Clock; import io.netty.channel.Channel; import io.netty.channel.group.ChannelGroup; import io.netty.handler.codec.http2.Http2StreamChannel; import io.netty.handler.codec.http2.Http2StreamChannelBootstrap; import java.net.SocketAddress; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implementation of {@link AsyncPool.Lifecycle} for bootstrapping {@link Http2StreamChannel}s. * The parent channel is bootstrapped upon first invocation of #create. The parent channel is * kept in the state for bootstrapping subsequent stream channels. The parent channel is recreated * if the channel is no longer valid. The parent channel is reaped after the parent channel is idle * for the configurable timeout period. * * Implementation of this class is supposed to be thread safe. * * @author Sean Sheng * @author Nizar Mankulangara */ class Http2ChannelLifecycle implements AsyncPool.Lifecycle<Channel> { private static final Logger LOG = LoggerFactory.getLogger(Http2ChannelLifecycle.class); private final SocketAddress _address; private final ScheduledExecutorService _scheduler; private final Clock _clock; private final boolean _ssl; private final long _maxContentLength; private final long _idleTimeout; private AsyncPool.Lifecycle<Channel> _parentChannelLifecycle; /** * Read and write to the following members should be synchronized by this lock. */ private final Object _lock = new Object(); private final Queue<Callback<Channel>> _waiters = new ArrayDeque<>(); private final ChannelGroup _channelGroup; private boolean _bootstrapping = false; private Channel _parentChannel = null; private long _childChannelCount; private long _lastActiveTime; Http2ChannelLifecycle(SocketAddress address, ScheduledExecutorService scheduler, Clock clock, ChannelGroup channelGroup, boolean ssl, long maxContentLength, long idleTimeout, AsyncPool.Lifecycle<Channel> parentChannelLifecycle) { _address = address; _scheduler = scheduler; _clock = clock; _channelGroup = channelGroup; _ssl = ssl; _maxContentLength = maxContentLength; _idleTimeout = idleTimeout; _parentChannelLifecycle = parentChannelLifecycle; _childChannelCount = 0; _lastActiveTime = _clock.currentTimeMillis(); _scheduler.scheduleAtFixedRate(this::closeParentIfIdle, idleTimeout, idleTimeout, TimeUnit.MILLISECONDS); } @Override public void create(Callback<Channel> callback) { Channel parentChannel; synchronized (_lock) { _lastActiveTime = _clock.currentTimeMillis(); parentChannel = _parentChannel; } if (!isChannelActive(parentChannel)) { parentChannel = null; synchronized (_lock) { _childChannelCount = 0; } } if (parentChannel == null) { synchronized (_lock) { _waiters.add(callback); if (_bootstrapping) { return; } _bootstrapping = true; } doBootstrapParentChannel(new Callback<Channel>() { @Override public void onError(Throwable e) { notifyWaiters(e); } @Override public void onSuccess(Channel channel) { doBootstrapWaitersStreamChannel(channel); } }); } else { doBootstrapStreamChannel(parentChannel, callback); } } private boolean isChannelActive(Channel channel) { return channel != null && channel.isActive(); } private void doBootstrapWaitersStreamChannel(Channel channel) { final List<Callback<Channel>> waiters; synchronized (_lock) { _parentChannel = channel; _channelGroup.add(channel); waiters = new ArrayList<>(_waiters.size()); IntStream.range(0, _waiters.size()).forEach(i -> waiters.add(_waiters.poll())); _bootstrapping = false; } for (Callback<Channel> waiter : waiters) { doBootstrapStreamChannel(channel, waiter); } } private void notifyWaiters(Throwable e) { final List<Callback<Channel>> waiters; synchronized (_lock) { waiters = new ArrayList<>(_waiters.size()); IntStream.range(0, _waiters.size()).forEach(i -> waiters.add(_waiters.poll())); _bootstrapping = false; } for (Callback<Channel> waiter : waiters) { waiter.onError(e); } } /** * Bootstraps the parent (connection) channel, awaits for ALPN, and returns the * channel through success callback. If exception occurs, the cause is returned * through the error callback. * @param callback Callback of the parent channel bootstrap. */ private void doBootstrapParentChannel(Callback<Channel> callback) { _parentChannelLifecycle.create(new Callback<Channel>() { @Override public void onError(Throwable error) { callback.onError(error); } @Override public void onSuccess(Channel channel) { channel.attr(NettyChannelAttributes.INITIALIZATION_FUTURE).get().addListener(alpnFuture -> { if (alpnFuture.isSuccess()) { callback.onSuccess(channel); } else { callback.onError(alpnFuture.cause()); } }); } }); } /** * Bootstraps the stream channel from the given parent channel. Returns the stream channel * through the success callback if bootstrap succeeds; Return the cause if an exception occurs. * @param channel Parent channel to bootstrap the stream channel from. * @param callback Callback of the stream channel bootstrap. */ private void doBootstrapStreamChannel(Channel channel, Callback<Channel> callback) { final Http2StreamChannelBootstrap bootstrap = new Http2StreamChannelBootstrap(channel).handler(new Http2StreamChannelInitializer(_ssl, _maxContentLength)); bootstrap.open().addListener(future -> { if (future.isSuccess()) { synchronized (_lock) { _childChannelCount++; } callback.onSuccess((Http2StreamChannel) future.get()); } else { channel.close(); callback.onError(future.cause()); } }); } /** * Attempts to close the parent channel if idle timeout has expired. */ private void closeParentIfIdle() { final Channel channel; final long lastActiveTime; final long childChannelCount; synchronized (_lock) { channel = _parentChannel; lastActiveTime = _lastActiveTime; childChannelCount = _childChannelCount; } if (_clock.currentTimeMillis() - lastActiveTime < _idleTimeout) { return; } if (channel == null || !channel.isOpen()) { return; } if (childChannelCount > 0) { return; } synchronized (_lock) { _parentChannel = null; _childChannelCount = 0; } LOG.error("Closing parent channel due to idle timeout !"); channel.close().addListener(future -> { if (!future.isSuccess()) { LOG.error("Failed to close parent channel after idle timeout, remote={}", _address, future.cause()); } }); } // ############# delegating section ############## @Override public boolean validateGet(Channel channel) { return _parentChannelLifecycle.validateGet(channel); } @Override public boolean validatePut(Channel channel) { return _parentChannelLifecycle.validatePut(channel); } @Override public void destroy(Channel channel, boolean error, Callback<Channel> callback) { _parentChannelLifecycle.destroy(channel, error, callback); synchronized (_lock) { if (_childChannelCount > 0) { _childChannelCount--; } } } @Override public PoolStats.LifecycleStats getStats() { return _parentChannelLifecycle.getStats(); } }
package emufog.docker; import java.util.ArrayList; import java.util.List; /** * This docker image represents a fog computing node in the topology. * It can serve a fixed number of clients and is associated with deployment costs. */ public class FogType extends DockerType { /* maximal number of clients this image can serve, including */ public final int maxClients; /* costs to deploy an instance of this image */ public final float costs; /* list of dependencies of this image */ public final List<FogType> dependencies; /** * Creates a new fog computing node to be deployed in the network. * * @param dockerImage actual docker image to deploy * @param maxClients maximum number of clients to serve * @param costs costs to deploy this image * @param memoryLimit upper limit of memory to use in Bytes * @param cpuShare share of the sum of available computing resources * @throws IllegalArgumentException the docker image name cannot be null and must * match the pattern of a docker container name */ public FogType(String dockerImage, int maxClients, float costs, int memoryLimit, float cpuShare) throws IllegalArgumentException { super(dockerImage, memoryLimit, cpuShare); this.maxClients = maxClients; this.costs = costs; dependencies = new ArrayList<>(); } /** * Adds * * @param type fog node type dependency to add * @throws IllegalArgumentException if type object is null */ public void addDependency(FogType type) throws IllegalArgumentException { if (type == null) { throw new IllegalArgumentException("Fog type dependency is not initialized."); } dependencies.add(type); } /** * Returns identification whether there are dependencies for this fog node type. * * @return true if there are dependencies, false otherwise */ public boolean hasDependencies() { return !dependencies.isEmpty(); } }
package com.ruoyi.common.exception; /** * 验证异常 * * @author jack */ public class ValidateCodeException extends Exception { private static final long serialVersionUID = 3887472968823615091L; public ValidateCodeException() { } public ValidateCodeException(String msg) { super(msg); } }
package ru.job4j.condition; public class Driver { private char license = 'N'; public void passExamOn(char category) { this.license = category; } public boolean hasLicense(){ return this.license == 'A' || this.license == 'B' || this.license == 'C'; } public boolean canDrive(char category) { return this.license == category; } }
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002, 2014 Oracle and/or its affiliates. All rights reserved. * */ package com.sleepycat.je.rep; import java.util.List; /** * NetworkRestoreConfig defines the configuration parameters used to configure * a NetworkRestore operation. * * @see NetworkRestore */ public class NetworkRestoreConfig { /** * Determines whether obsolete log files must be renamed or deleted. */ private boolean retainLogFiles = true; /** * The size of the network restore client socket's receive buffer. */ private int receiveBufferSize = 0x200000; /* 2 MB */ /** * List (in priority order) of the members who should be contacted for the * the log files. */ private List<ReplicationNode> logProviders; /** * Returns a boolean indicating whether existing log files should be * retained or deleted. * * @return true if log files must be retained */ public boolean getRetainLogFiles() { return retainLogFiles; } /** * If true retains obsolete log files, by renaming them instead of deleting * them. The default is "true". * <p> * A renamed file has its <code>.jdb</code> suffix replaced by * <code>.bup</code> and an additional numeric monotonically increasing * numeric suffix. All files that were renamed as part of the same * NetworkRestore attempt will have the same numeric suffix. * <p> * For example, if files 00000001.jdb and files 00000002.jdb were rendered * obsolete, and 4 was the highest suffix in use for this environment when * the operation was initiated, then the files would be renamed as * 00000001.bup.5 and 00000002.bup.5. * * @param retainLogFiles if true retains obsolete log files * * @return this */ public NetworkRestoreConfig setRetainLogFiles(boolean retainLogFiles) { setRetainLogFilesVoid(retainLogFiles); return this; } /** * @hidden * The void return setter for use by Bean editors. */ public void setRetainLogFilesVoid(boolean retainLogFiles) { this.retainLogFiles = retainLogFiles; } /** * Returns the size of the receive buffer associated with the socket used * to transfer files during the NetworkRestore operation. */ public int getReceiveBufferSize() { return receiveBufferSize; } /** * Sets the size of the receive buffer associated with the socket used to * transfer files during the NetworkRestore operation. * <p> * Note that if the size specified is larger than the operating system * constrained maximum, it will be limited to this maximum value. For * example, on Linux you may need to set the kernel parameter: * net.core.rmem_max property using the command: <i>sysctl -w * net.core.rmem_max=1048576</i> to increase the operating system imposed * limit. * <p> * @param receiveBufferSize the size of the receive buffer. If it's zero, * the operating system default value is used.. */ public NetworkRestoreConfig setReceiveBufferSize(int receiveBufferSize) { if (receiveBufferSize < 0) { throw new IllegalArgumentException("receiveBufferSize:" + receiveBufferSize + " is negative."); } this.receiveBufferSize = receiveBufferSize; return this; } /** * @hidden * The void return setter for use by Bean editors. */ public void setReceiveBufferSizeVoid(int receiveBufferSize) { setReceiveBufferSize(receiveBufferSize); } /** * Returns the candidate list of members that may be used to obtain log * files. * * @return this */ public List<ReplicationNode> getLogProviders() { return logProviders; } /** * Sets the prioritized list of members used to select a node from which to * obtain log files for the NetworkRestore operation. If a list is * supplied, NetworkRestore will only use nodes from this list, trying each * one in order. * <p> * The default value is null. If a null value is configured for * NetworkRestore, it will choose the least busy member with a current set * of logs, as the provider of log files. * * @param providers the list of members in priority order, or null * * @return this */ public NetworkRestoreConfig setLogProviders(List<ReplicationNode> providers) { setLogProvidersVoid(providers); return this; } /** * @hidden * The void return setter for use by Bean editors. */ public void setLogProvidersVoid(List<ReplicationNode> providers) { logProviders = providers; } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests.extensions; import com.microsoft.graph.requests.extensions.IAndroidManagedStoreAccountEnterpriseSettingsRequestSignupUrlRequest; import com.microsoft.graph.requests.extensions.AndroidManagedStoreAccountEnterpriseSettingsRequestSignupUrlRequest; import com.microsoft.graph.core.BaseActionRequestBuilder; import com.microsoft.graph.core.BaseFunctionRequestBuilder; import com.microsoft.graph.core.IBaseClient; import com.google.gson.JsonElement; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Android Managed Store Account Enterprise Settings Request Signup Url Request Builder. */ public class AndroidManagedStoreAccountEnterpriseSettingsRequestSignupUrlRequestBuilder extends BaseActionRequestBuilder implements IAndroidManagedStoreAccountEnterpriseSettingsRequestSignupUrlRequestBuilder { /** * The request builder for this AndroidManagedStoreAccountEnterpriseSettingsRequestSignupUrl * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request * @param hostName the hostName */ public AndroidManagedStoreAccountEnterpriseSettingsRequestSignupUrlRequestBuilder(final String requestUrl, final IBaseClient client, final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions, final String hostName) { super(requestUrl, client, requestOptions); bodyParams.put("hostName", hostName); } /** * Creates the IAndroidManagedStoreAccountEnterpriseSettingsRequestSignupUrlRequest * * @param requestOptions the options for the request * @return the IAndroidManagedStoreAccountEnterpriseSettingsRequestSignupUrlRequest instance */ public IAndroidManagedStoreAccountEnterpriseSettingsRequestSignupUrlRequest buildRequest(final com.microsoft.graph.options.Option... requestOptions) { return buildRequest(getOptions(requestOptions)); } /** * Creates the IAndroidManagedStoreAccountEnterpriseSettingsRequestSignupUrlRequest with specific requestOptions instead of the existing requestOptions * * @param requestOptions the options for the request * @return the IAndroidManagedStoreAccountEnterpriseSettingsRequestSignupUrlRequest instance */ public IAndroidManagedStoreAccountEnterpriseSettingsRequestSignupUrlRequest buildRequest(final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { AndroidManagedStoreAccountEnterpriseSettingsRequestSignupUrlRequest request = new AndroidManagedStoreAccountEnterpriseSettingsRequestSignupUrlRequest( getRequestUrl(), getClient(), requestOptions ); if (hasParameter("hostName")) { request.body.hostName = getParameter("hostName"); } return request; } }
/* * (c) Copyright 2020 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.dialogue.hc5; import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.concurrent.atomic.AtomicInteger; import org.awaitility.Awaitility; import org.junit.jupiter.api.Test; class CleanerSupportTest { @Test void testCleaner() { AtomicInteger counter = new AtomicInteger(); CleanerSupport.register(new byte[1024 * 1024], counter::incrementAndGet); Awaitility.waitAtMost(Duration.ofSeconds(3)).untilAsserted(() -> { attemptToGarbageCollect(); assertThat(counter).hasValue(1); }); } private static void attemptToGarbageCollect() { // Create some garbage to entice the collector ByteArrayOutputStream baos = new ByteArrayOutputStream(); while (baos.toString().length() < 4096) { byte[] buf = "Hello, World!".getBytes(StandardCharsets.UTF_8); baos.write(buf, 0, buf.length); } // System.gc is disabled in some environments, so it alone cannot be relied upon. System.gc(); } }
/******************************************************************************* * Copyright 2009 OpenSHA.org in partnership with * the Southern California Earthquake Center (SCEC, http://www.scec.org) * at the University of Southern California and the UnitedStates Geological * Survey (USGS; http://www.usgs.gov) * * 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.opensha.nshmp.sha.data; import java.rmi.RemoteException; import org.opensha.commons.data.function.ArbitrarilyDiscretizedFunc; import org.opensha.nshmp.exceptions.ZipCodeErrorException; /** * <p>Title: DataGenerator_FEMA</p> * * <p>Description: </p> * @author Ned Field, Nitin Gupta and Vipin Gupta * @version 1.0 */ public class DataGenerator_FEMA extends DataGenerator_NEHRP { /** * Returns the SA at .2sec * @return double */ public double getSs() { return saFunction.getY(0); } /** * Returns the SA at 1 sec * @return double */ public double getSa() { return saFunction.getY(1); } /** * Gets the data for SsS1 in case region specified is not a Territory and user * specifies Lat-Lon for the location. */ public void calculateSsS1(double lat, double lon) throws RemoteException { HazardDataMinerAPI miner = new HazardDataMinerServletMode(); ArbitrarilyDiscretizedFunc function = miner.getSsS1(geographicRegion, dataEdition, lat, lon, selectedSpectraType); String location = "Lat - " + lat + " Lon - " + lon; createMetadataForPlots(location); addDataInfo(function.getInfo()); saFunction = function; } /** * Gets the data for SsS1 in case region specified is not a Territory and user * specifies zip code for the location. */ public void calculateSsS1(String zipCode) throws ZipCodeErrorException, RemoteException { HazardDataMinerAPI miner = new HazardDataMinerServletMode(); ArbitrarilyDiscretizedFunc function = miner.getSsS1(geographicRegion, dataEdition, zipCode, selectedSpectraType); String location = "Zipcode - " + zipCode; createMetadataForPlots(location); addDataInfo(function.getInfo()); saFunction = function; } }
package com.smart.smartchart.utils; import android.content.Context; import android.os.Handler; import android.widget.TextView; import com.smart.smartchart.R; public class CountDownUtils { private Context context; private int iTime = 60; private TextView v; private Handler countdownHandler; public CountDownUtils(final Context context, final TextView v) { this.context = context; this.v = v; countdownHandler = new Handler(context.getMainLooper()) { public void handleMessage(android.os.Message msg) { String s = String.format(context.getString(R.string.code_txt), String.valueOf(iTime)); v.setText(s); countdownHandler.postDelayed(countdownRunnable, 1000); } }; } private Runnable countdownRunnable = new Runnable() { @Override public void run() { if (iTime == 60) { v.setEnabled(false); v.setTextColor(context.getResources().getColor(R.color.color_969696)); } if (iTime > 0) { iTime--; countdownHandler.sendEmptyMessage(0); } else if (iTime == 0) { iTime = 60; v.setEnabled(true); countdownHandler.removeCallbacks(this); v.setText(context.getString(R.string.bind_mobile_get_code)); v.setTextColor(context.getResources().getColor(R.color.color_2CA2F4)); } } }; public void countDown() { countdownHandler.post(countdownRunnable); } public void cancleCount() { countdownHandler.removeCallbacks(countdownRunnable); } }
/** * 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.interceptor; import javax.sql.DataSource; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.spring.SpringRouteBuilder; import org.apache.camel.spring.SpringTestSupport; import org.apache.camel.spring.spi.SpringTransactionPolicy; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.support.TransactionTemplate; /** * Using the default error handler = DeadLetterChannel to unit test that this works out of the box * also, that Camel doesn't break. */ public class TransactionalClientDataSourceWithDefaultErrorHandlerTest extends TransactionalClientDataSourceTest { @Override protected void setUp() throws Exception { super.setUp(); useTransactionErrorHandler = false; } }
package com.kzmen.sczxjf.ebean; import java.io.Serializable; /** * Created by Administrator on 2015/10/29. */ public class User implements Serializable{ /** * own_id : 63235 * own_name : 312312hrfhhrr个护肤 * email : null * own_mob_no : 13594015206 * own_logname : 13594015206 * acc_status : 479 * acc_status_str : 待上传资料 * type_id : 148 * type_id_str : 财经 * amount_account : 5105.05 * company_name : 213123 * company_address : 3123123vvvbvvbb * user_rank : 0 * is_banding : 1 * faq : http://www.baidu.com/ */ private String own_id; private String own_name; private String email; private String own_mob_no; private String own_logname; private String acc_status; private String acc_status_str; private String type_id; private String type_id_str; private String amount_account; private String company_name; private String company_address; private String user_rank; private int is_banding; private String faq; private String appkey; private String sing; private String token; private String userkey; public String getAppkey() { return appkey; } public void setAppkey(String appkey) { this.appkey = appkey; } public String getSing() { return sing; } public void setSing(String sing) { this.sing = sing; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getUserkey() { return userkey; } public void setUserkey(String userkey) { this.userkey = userkey; } public void setOwn_id(String own_id) { this.own_id = own_id; } public void setOwn_name(String own_name) { this.own_name = own_name; } public void setEmail(String email) { this.email = email; } public void setOwn_mob_no(String own_mob_no) { this.own_mob_no = own_mob_no; } public void setOwn_logname(String own_logname) { this.own_logname = own_logname; } public void setAcc_status(String acc_status) { this.acc_status = acc_status; } public void setAcc_status_str(String acc_status_str) { this.acc_status_str = acc_status_str; } public void setType_id(String type_id) { this.type_id = type_id; } public void setType_id_str(String type_id_str) { this.type_id_str = type_id_str; } public void setAmount_account(String amount_account) { this.amount_account = amount_account; } public void setCompany_name(String company_name) { this.company_name = company_name; } public void setCompany_address(String company_address) { this.company_address = company_address; } public void setUser_rank(String user_rank) { this.user_rank = user_rank; } public void setIs_banding(int is_banding) { this.is_banding = is_banding; } public void setFaq(String faq) { this.faq = faq; } public String getOwn_id() { return own_id; } public String getOwn_name() { return own_name; } public String getEmail() { return email; } public String getOwn_mob_no() { return own_mob_no; } public String getOwn_logname() { return own_logname; } public String getAcc_status() { return acc_status; } public String getAcc_status_str() { return acc_status_str; } public String getType_id() { return type_id; } public String getType_id_str() { return type_id_str; } public String getAmount_account() { return amount_account; } public String getCompany_name() { return company_name; } public String getCompany_address() { return company_address; } public String getUser_rank() { return user_rank; } public int getIs_banding() { return is_banding; } public String getFaq() { return faq; } @Override public String toString() { return "User{" + "own_id='" + own_id + '\'' + ", own_name='" + own_name + '\'' + ", email='" + email + '\'' + ", own_mob_no='" + own_mob_no + '\'' + ", own_logname='" + own_logname + '\'' + ", acc_status='" + acc_status + '\'' + ", acc_status_str='" + acc_status_str + '\'' + ", type_id='" + type_id + '\'' + ", type_id_str='" + type_id_str + '\'' + ", amount_account='" + amount_account + '\'' + ", company_name='" + company_name + '\'' + ", company_address='" + company_address + '\'' + ", user_rank='" + user_rank + '\'' + ", is_banding=" + is_banding + ", faq='" + faq + '\'' + '}'; } }
package org.dddjava.jig.domain.model.parts.relation.packages; import org.dddjava.jig.domain.model.parts.classes.type.TypeIdentifier; import org.dddjava.jig.domain.model.parts.packages.PackageIdentifier; import org.dddjava.jig.domain.model.parts.relation.class_.ClassRelation; /** * 相互依存 */ public class BidirectionalRelation { PackageRelation packageRelation; public BidirectionalRelation(PackageRelation packageRelation) { this.packageRelation = packageRelation; } public boolean matches(PackageRelation packageRelation) { PackageIdentifier left = this.packageRelation.from; PackageIdentifier right = this.packageRelation.to; return (left.equals(packageRelation.from()) && right.equals(packageRelation.to())) || (left.equals(packageRelation.to()) && right.equals(packageRelation.from())); } @Override public String toString() { return packageRelation.from.asText() + " <-> " + packageRelation.to.asText(); } public boolean matches(ClassRelation classRelation) { TypeIdentifier fromClass = classRelation.from(); TypeIdentifier toClass = classRelation.to(); return packageRelation.matches(fromClass, toClass) || packageRelation.matches(toClass, fromClass); } }
package vazkii.quark.experimental.block; import net.minecraft.block.Block; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.ChunkCache; import net.minecraft.world.IBlockAccess; import net.minecraft.world.chunk.Chunk; import net.minecraftforge.common.property.ExtendedBlockState; import net.minecraftforge.common.property.IExtendedBlockState; import net.minecraftforge.common.property.IUnlistedProperty; import vazkii.arl.block.property.PropertyBlockState; import vazkii.quark.experimental.tile.TileFramed; public class FramedBlockCommons { public static final PropertyBlockState STATE = new PropertyBlockState(); public static BlockStateContainer createStateContainer(Block block, BlockStateContainer normalContainer) { return new ExtendedBlockState(block, normalContainer.getProperties().toArray(new IProperty[0]), new IUnlistedProperty[] { STATE }); } public static IBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos) { IBlockState actualState = state.getActualState(world, pos); TileEntity tile = world instanceof ChunkCache ? ((ChunkCache)world).getTileEntity(pos, Chunk.EnumCreateEntityType.CHECK) : world.getTileEntity(pos); if(tile instanceof TileFramed && actualState instanceof IExtendedBlockState) { TileFramed frame = (TileFramed) tile; IExtendedBlockState extend = (IExtendedBlockState) actualState; return extend.withProperty(STATE, frame.getState()); } return state; } }
package org.nico.honeycomb.tests; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.Random; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.sql.DataSource; import org.junit.Test; import org.nico.honeycomb.connection.pool.feature.CleanerFeature; import org.nico.honeycomb.datasource.HoneycombDataSource; import com.alibaba.druid.pool.DruidDataSource; public class BaseTests { @Test public void testHoneycomb() throws SQLException, InterruptedException{ HoneycombDataSource dataSource = new HoneycombDataSource(); dataSource.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&transformedBitIsBoolean=true&zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=Asia/Shanghai"); dataSource.setUser("root"); dataSource.setPassword("root"); dataSource.setDriver("com.mysql.cj.jdbc.Driver"); dataSource.setMaxPoolSize(300); dataSource.setInitialPoolSize(0); dataSource.setMaxWaitTime(Long.MAX_VALUE); dataSource.setMinPoolSize(0); dataSource.setMaxIdleTime(5000); dataSource.addFeature(new CleanerFeature(true, 5 * 1000)); test(dataSource, 1000 * 60); } @Test public void testDruid() throws SQLException, InterruptedException{ DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&transformedBitIsBoolean=true&zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=Asia/Shanghai"); dataSource.setUsername("root"); dataSource.setPassword("root"); dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); dataSource.setMaxActive(300); dataSource.setInitialSize(0); dataSource.setMaxWait(Long.MAX_VALUE); dataSource.setMinIdle(100); dataSource.setTimeBetweenEvictionRunsMillis(1000 * 5); test(dataSource, 1000 * 60); } static volatile boolean s = true; static volatile boolean b = true; static ThreadPoolExecutor tpe = new ThreadPoolExecutor(200, 200, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); public static void test(DataSource dataSource, long howlong) throws SQLException, InterruptedException { Random random = new Random(); final AtomicInteger atomicInteger = new AtomicInteger(); new Thread() { @Override public void run() { while(s) { BaseTests.sleep(random.nextInt(1)); tpe.execute(() -> { Connection connection = null; try { connection = dataSource.getConnection(); Statement s = connection.createStatement(); s.executeUpdate("INSERT INTO `test`.`testpool` VALUES ()"); atomicInteger.incrementAndGet(); }catch(Exception e) { }finally { if(connection != null) try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } }); BaseTests.sleep(random.nextInt(2)); } } }.start(); new Thread() { @Override public void run() { BaseTests.sleep(howlong); s = false; while(tpe.getActiveCount() != 0) { BaseTests.sleep(1000); } System.out.println(atomicInteger.get()); b = false; } }.start(); sleep(10000000); tpe.shutdown(); } public static void sleep(long time) { try { Thread.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); } } }
package com.coolweather.app.activity; import com.coolweather.app.service.AutoUpdateService; import com.coolweather.app.util.HttpCallbackListener; import com.coolweather.app.util.HttpUtil; import com.coolweather.app.util.Utility; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; public class WeatherActivity extends Activity implements OnClickListener{ private LinearLayout weatherInfoLayout; private TextView cityNameText; private TextView publishText; private TextView weatherDespText; private TextView temp1Text; private TextView temp2Text; private TextView currentDateText; private Button switchCity; private Button refreshWeather; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.weather_layout); weatherInfoLayout = (LinearLayout) findViewById(R.id.weather_info_layout); cityNameText = (TextView) findViewById(R.id.city_name); publishText = (TextView) findViewById(R.id.publish_text); weatherDespText = (TextView) findViewById(R.id.weather_desp); temp1Text = (TextView) findViewById(R.id.temp1); currentDateText = (TextView) findViewById(R.id.current_date); String countyCode = getIntent().getStringExtra("county_code"); if(!TextUtils.isEmpty(countyCode)){ publishText.setText("同步中..."); weatherInfoLayout.setVisibility(View.INVISIBLE); cityNameText.setVisibility(View.INVISIBLE); queryWeatherCode(countyCode); } else { showWeather(); } switchCity = (Button) findViewById(R.id.switch_city); refreshWeather = (Button) findViewById(R.id.refresh_weather); switchCity.setOnClickListener(this); refreshWeather.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()) { case R.id.switch_city: Intent intent = new Intent(this, ChooseAreaActivity.class); intent.putExtra("from_weather_activity", true); startActivity(intent); finish(); break; case R.id.refresh_weather: publishText.setText("同步中..."); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String weatherCode = prefs.getString("weather_code", ""); if(!TextUtils.isEmpty(weatherCode)){ queryWeatherInfo(weatherCode); } break; default: break; } } private void queryWeatherCode(String countyCode){ String address = "http://m.weather.com.cn/data5/city" + countyCode +".xml"; queryFromServer(address, "countyCode"); } private void queryWeatherInfo(String weatherCode){ String address = "http://m.weather.com.cn/data/"+weatherCode+".html"; Log.d("Weather", address); queryFromServer(address, "weatherCode"); } private void queryFromServer(final String address, final String type){ HttpUtil.sendHttpRequest(address, new HttpCallbackListener() { @Override public void onFinish(String response) { // TODO Auto-generated method stub Log.d("Weather", response); if("countyCode".equals(type)){ if(!TextUtils.isEmpty(response)){ String[] array = response.split("\\|"); if(array != null && array.length == 2){ String weatherCode = array[1]; queryWeatherInfo(weatherCode); } } } else if("weatherCode".equals(type)){ Utility.handleWeatherResponse(WeatherActivity.this, response); runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub showWeather(); } }); } } @Override public void onError(Exception e) { // TODO Auto-generated method stub runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub publishText.setText("同步失败"); } }); } }); } private void showWeather(){ SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); cityNameText.setText(prefs.getString("city_name", "")); temp1Text.setText(prefs.getString("temp1", "")); weatherDespText.setText(prefs.getString("weather_desp", "")); publishText.setText("今天"+prefs.getString("publish_time", "")+"发布"); currentDateText.setText(prefs.getString("current_date", "")); weatherInfoLayout.setVisibility(View.VISIBLE); cityNameText.setVisibility(View.VISIBLE); Intent intent = new Intent(this, AutoUpdateService.class); startService(intent); } }
package com.alipay.api.response; import java.util.Date; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.fund.auth.order.freeze response. * * @author auto create * @since 1.0, 2021-03-04 10:32:32 */ public class AlipayFundAuthOrderFreezeResponse extends AlipayResponse { private static final long serialVersionUID = 6183721447464843767L; /** * 本次操作冻结的金额,单位为:元(人民币),精确到小数点后两位 */ @ApiField("amount") private String amount; /** * 支付宝的资金授权订单号 */ @ApiField("auth_no") private String authNo; /** * 本次冻结操作中信用冻结金额,单位为:元(人民币),精确到小数点后两位 */ @ApiField("credit_amount") private String creditAmount; /** * 本次冻结操作中自有资金冻结金额,单位为:元(人民币),精确到小数点后两位 */ @ApiField("fund_amount") private String fundAmount; /** * 资金授权成功时间 格式:YYYY-MM-DD HH:MM:SS */ @ApiField("gmt_trans") private Date gmtTrans; /** * 支付宝的资金操作流水号 */ @ApiField("operation_id") private String operationId; /** * 商户的授权资金订单号 */ @ApiField("out_order_no") private String outOrderNo; /** * 商户本次资金操作的请求流水号 */ @ApiField("out_request_no") private String outRequestNo; /** * 付款方支付宝账号(Email或手机号) */ @ApiField("payer_logon_id") private String payerLogonId; /** * 付款方支付宝用户号 */ @ApiField("payer_user_id") private String payerUserId; /** * 预授权类型,目前支持 CREDIT_AUTH(信用预授权); 商户可根据该标识来判断该笔预授权的类型,当返回值为"CREDIT_AUTH"表明该笔预授权为信用预授权,没有真实冻结资金;当返回值为空或者不为"CREDIT_AUTH"则表明该笔预授权为普通资金预授权,会冻结用户资金。 */ @ApiField("pre_auth_type") private String preAuthType; /** * 资金预授权明细的状态 目前支持: INIT:初始 SUCCESS: 成功 CLOSED:关闭 */ @ApiField("status") private String status; /** * 标价币种, amount 对应的币种单位。支持澳元:AUD, 新西兰元:NZD, 台币:TWD, 美元:USD, 欧元:EUR, 英镑:GBP */ @ApiField("trans_currency") private String transCurrency; public void setAmount(String amount) { this.amount = amount; } public String getAmount( ) { return this.amount; } public void setAuthNo(String authNo) { this.authNo = authNo; } public String getAuthNo( ) { return this.authNo; } public void setCreditAmount(String creditAmount) { this.creditAmount = creditAmount; } public String getCreditAmount( ) { return this.creditAmount; } public void setFundAmount(String fundAmount) { this.fundAmount = fundAmount; } public String getFundAmount( ) { return this.fundAmount; } public void setGmtTrans(Date gmtTrans) { this.gmtTrans = gmtTrans; } public Date getGmtTrans( ) { return this.gmtTrans; } public void setOperationId(String operationId) { this.operationId = operationId; } public String getOperationId( ) { return this.operationId; } public void setOutOrderNo(String outOrderNo) { this.outOrderNo = outOrderNo; } public String getOutOrderNo( ) { return this.outOrderNo; } public void setOutRequestNo(String outRequestNo) { this.outRequestNo = outRequestNo; } public String getOutRequestNo( ) { return this.outRequestNo; } public void setPayerLogonId(String payerLogonId) { this.payerLogonId = payerLogonId; } public String getPayerLogonId( ) { return this.payerLogonId; } public void setPayerUserId(String payerUserId) { this.payerUserId = payerUserId; } public String getPayerUserId( ) { return this.payerUserId; } public void setPreAuthType(String preAuthType) { this.preAuthType = preAuthType; } public String getPreAuthType( ) { return this.preAuthType; } public void setStatus(String status) { this.status = status; } public String getStatus( ) { return this.status; } public void setTransCurrency(String transCurrency) { this.transCurrency = transCurrency; } public String getTransCurrency( ) { return this.transCurrency; } }
/* * $RCSfile: FPXUtils.java,v $ * * Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved. * * Use is subject to license terms. * * $Revision: 1.1 $ * $Date: 2005-02-11 04:55:41 $ * $State: Exp $ */ package com.sun.media.jai.codecimpl.fpx; import java.io.IOException; import java.text.DecimalFormat; import com.sun.media.jai.codec.SeekableStream; public class FPXUtils { // /** Reads a 2-byte little-endian value. */ // public static final int readInt2(SeekableStream file, int offset) // throws IOException { // file.seek(offset); // return file.readShortLE(); // } // /** Reads a 4-byte little-endian value. */ // public static final int readInt4(SeekableStream file, int offset) // throws IOException { // file.seek(offset); // return file.readIntLE(); // } // /** Reads a 4-byte little-endian IEEE float. */ // public static final float readFloat(SeekableStream file, int offset) // throws IOException { // file.seek(offset); // return file.readFloatLE(); // } // /** Reads an 8-byte little-endian IEEE double. */ // public static final double readDouble(SeekableStream file, // int offset) // throws IOException { // file.seek(offset); // return file.readDoubleLE(); // } public static final short getShortLE(byte[] data, int offset) { int b0 = data[offset] & 0xff; int b1 = data[offset + 1] & 0xff; return (short)((b1 << 8) | b0); } public static final int getUnsignedShortLE(byte[] data, int offset) { int b0 = data[offset] & 0xff; int b1 = data[offset + 1] & 0xff; return (b1 << 8) | b0; } public static final int getIntLE(byte[] data, int offset) { int b0 = data[offset] & 0xff; int b1 = data[offset + 1] & 0xff; int b2 = data[offset + 2] & 0xff; int b3 = data[offset + 3] & 0xff; return (b3 << 24) | (b2 << 16) | (b1 << 8) | b0; } public static final long getUnsignedIntLE(byte[] data, int offset) { long b0 = data[offset] & 0xff; long b1 = data[offset + 1] & 0xff; long b2 = data[offset + 2] & 0xff; long b3 = data[offset + 3] & 0xff; return (b3 << 24) | (b2 << 16) | (b1 << 8) | b0; } public static final String getString(byte[] data, int offset, int length) { if (length == 0) { return "<none>"; } else { length = length/2 - 1; // workaround for Kodak bug } StringBuffer b = new StringBuffer(length); for (int i = 0; i < length; i++) { int c = getUnsignedShortLE(data, offset); b.append((char)c); offset += 2; } return b.toString(); } private static void printDecimal(int i) { DecimalFormat d = new DecimalFormat("00000"); System.out.print(d.format(i)); } private static void printHex(byte b) { int i = b & 0xff; int hi = i/16; int lo = i % 16; if (hi < 10) { System.out.print((char)('0' + hi)); } else { System.out.print((char)('a' + hi - 10)); } if (lo < 10) { System.out.print((char)('0' + lo)); } else { System.out.print((char)('a' + lo - 10)); } } private static void printChar(byte b) { char c = (char)(b & 0xff); if (c >= '!' && c <= '~') { System.out.print(' '); System.out.print(c); } else if (c == 0) { System.out.print("^@"); } else if (c < ' ') { System.out.print('^'); System.out.print((char)('A' + c - 1)); } else if (c == ' ') { System.out.print("__"); } else { System.out.print("??"); } } public static void dumpBuffer(byte[] buf, int offset, int length, int printOffset) { int lines = length/8; for (int j = 0; j < lines; j++) { printDecimal(printOffset); System.out.print(": "); for (int i = 0; i < 8; i++) { printHex(buf[offset + i]); System.out.print(" "); } for (int i = 0; i < 8; i++) { printChar(buf[offset + i]); System.out.print(" "); } offset += 8; printOffset += 8; System.out.println(); } } }
/* * This source file is part of the FIUS ICGE project. * For more information see github.com/FIUS/ICGE2 * * Copyright (c) 2019 the ICGE project authors. * * This software is available under the MIT license. * SPDX-License-Identifier: MIT */ package de.unistuttgart.informatik.fius.icge.ui; /** * The interface for a game window of the ICGE. * * @author Tim Neumann */ public interface GameWindow { /** * Get the registry, with which to register textures for this game window. * * @return The texture registry used by this window. */ TextureRegistry getTextureRegistry(); /** * Get the drawer responsible for drawing the playfield for this game window. * * @return The playfield drawer used by this window. */ PlayfieldDrawer getPlayfieldDrawer(); /** * Get the toolbar for this game window. * * @return The toolbar used by this window. */ Toolbar getToolbar(); /** * Get the entity sidebar for this game window * * @return The entity sidebar used by this window */ EntitySidebar getEntitySidebar(); /** * Get the console for this game window * * @return The console used by thsi window */ Console getConsole(); /** * Set the title of the window, in which the ICGE is displayed. * * @param title * The title to use. */ void setWindowTitle(String title); /** * Start the game window and all its submodules. */ void start(); }
/** * Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. * This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. */ package com.oracle.bmc.identity; import com.oracle.bmc.identity.requests.*; import com.oracle.bmc.identity.responses.*; @javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20160918") public interface IdentityAsync extends AutoCloseable { /** * Sets the endpoint to call (ex, https://www.example.com). * @param endpoint The endpoint of the serice. */ void setEndpoint(String endpoint); /** * Sets the region to call (ex, Region.US_PHOENIX_1). * <p> * Note, this will call {@link #setEndpoint(String) setEndpoint} after resolving the endpoint. If the service is not available in this region, however, an IllegalArgumentException will be raised. * @param region The region of the service. */ void setRegion(com.oracle.bmc.Region region); /** * Sets the region to call (ex, 'us-phoenix-1'). * <p> * Note, this will first try to map the region ID to a known Region and call * {@link #setRegion(Region) setRegion}. * <p> * If no known Region could be determined, it will create an endpoint based on the * default endpoint format ({@link com.oracle.bmc.Region#formatDefaultRegionEndpoint(Service, String)} * and then call {@link #setEndpoint(String) setEndpoint}. * @param regionId The public region ID. */ void setRegion(String regionId); /** * Activates the specified MFA TOTP device for the user. Activation requires manual interaction with the Console. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ActivateMfaTotpDeviceResponse> activateMfaTotpDevice( ActivateMfaTotpDeviceRequest request, com.oracle.bmc.responses.AsyncHandler< ActivateMfaTotpDeviceRequest, ActivateMfaTotpDeviceResponse> handler); /** * Adds the specified user to the specified group and returns a `UserGroupMembership` object with its own OCID. * <p> * After you send your request, the new object's `lifecycleState` will temporarily be CREATING. Before using the * object, first make sure its `lifecycleState` has changed to ACTIVE. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<AddUserToGroupResponse> addUserToGroup( AddUserToGroupRequest request, com.oracle.bmc.responses.AsyncHandler<AddUserToGroupRequest, AddUserToGroupResponse> handler); /** * Assembles tag defaults in the specified compartment and any parent compartments to determine * the tags to apply. Tag defaults from parent compartments do not override tag defaults * referencing the same tag in a compartment lower down the hierarchy. This set of tag defaults * includes all tag defaults from the current compartment back to the root compartment. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<AssembleEffectiveTagSetResponse> assembleEffectiveTagSet( AssembleEffectiveTagSetRequest request, com.oracle.bmc.responses.AsyncHandler< AssembleEffectiveTagSetRequest, AssembleEffectiveTagSetResponse> handler); /** * Moves the specified tag namespace to the specified compartment within the same tenancy. * <p> * To move the tag namespace, you must have the manage tag-namespaces permission on both compartments. * For more information about IAM policies, see [Details for IAM](https://docs.cloud.oracle.com/Content/Identity/Reference/iampolicyreference.htm). * <p> * Moving a tag namespace moves all the tag key definitions contained in the tag namespace. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ChangeTagNamespaceCompartmentResponse> changeTagNamespaceCompartment( ChangeTagNamespaceCompartmentRequest request, com.oracle.bmc.responses.AsyncHandler< ChangeTagNamespaceCompartmentRequest, ChangeTagNamespaceCompartmentResponse> handler); /** * Creates a new auth token for the specified user. For information about what auth tokens are for, see * [Managing User Credentials](https://docs.cloud.oracle.com/Content/Identity/Tasks/managingcredentials.htm). * <p> * You must specify a *description* for the auth token (although it can be an empty string). It does not * have to be unique, and you can change it anytime with * {@link #updateAuthToken(UpdateAuthTokenRequest, Consumer, Consumer) updateAuthToken}. * <p> * Every user has permission to create an auth token for *their own user ID*. An administrator in your organization * does not need to write a policy to give users this ability. To compare, administrators who have permission to the * tenancy can use this operation to create an auth token for any user, including themselves. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreateAuthTokenResponse> createAuthToken( CreateAuthTokenRequest request, com.oracle.bmc.responses.AsyncHandler<CreateAuthTokenRequest, CreateAuthTokenResponse> handler); /** * Creates a new compartment in the specified compartment. * <p> **Important:** Compartments cannot be deleted. * <p> * Specify the parent compartment's OCID as the compartment ID in the request object. Remember that the tenancy * is simply the root compartment. For information about OCIDs, see * [Resource Identifiers](https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm). * <p> * You must also specify a *name* for the compartment, which must be unique across all compartments in * your tenancy. You can use this name or the OCID when writing policies that apply * to the compartment. For more information about policies, see * [How Policies Work](https://docs.cloud.oracle.com/Content/Identity/Concepts/policies.htm). * <p> * You must also specify a *description* for the compartment (although it can be an empty string). It does * not have to be unique, and you can change it anytime with * {@link #updateCompartment(UpdateCompartmentRequest, Consumer, Consumer) updateCompartment}. * <p> * After you send your request, the new object's `lifecycleState` will temporarily be CREATING. Before using the * object, first make sure its `lifecycleState` has changed to ACTIVE. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreateCompartmentResponse> createCompartment( CreateCompartmentRequest request, com.oracle.bmc.responses.AsyncHandler< CreateCompartmentRequest, CreateCompartmentResponse> handler); /** * Creates a new secret key for the specified user. Secret keys are used for authentication with the Object Storage Service's Amazon S3 * compatible API. For information, see * [Managing User Credentials](https://docs.cloud.oracle.com/Content/Identity/Tasks/managingcredentials.htm). * <p> * You must specify a *description* for the secret key (although it can be an empty string). It does not * have to be unique, and you can change it anytime with * {@link #updateCustomerSecretKey(UpdateCustomerSecretKeyRequest, Consumer, Consumer) updateCustomerSecretKey}. * <p> * Every user has permission to create a secret key for *their own user ID*. An administrator in your organization * does not need to write a policy to give users this ability. To compare, administrators who have permission to the * tenancy can use this operation to create a secret key for any user, including themselves. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreateCustomerSecretKeyResponse> createCustomerSecretKey( CreateCustomerSecretKeyRequest request, com.oracle.bmc.responses.AsyncHandler< CreateCustomerSecretKeyRequest, CreateCustomerSecretKeyResponse> handler); /** * Creates a new dynamic group in your tenancy. * <p> * You must specify your tenancy's OCID as the compartment ID in the request object (remember that the tenancy * is simply the root compartment). Notice that IAM resources (users, groups, compartments, and some policies) * reside within the tenancy itself, unlike cloud resources such as compute instances, which typically * reside within compartments inside the tenancy. For information about OCIDs, see * [Resource Identifiers](https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm). * <p> * You must also specify a *name* for the dynamic group, which must be unique across all dynamic groups in your * tenancy, and cannot be changed. Note that this name has to be also unique across all groups in your tenancy. * You can use this name or the OCID when writing policies that apply to the dynamic group. For more information * about policies, see [How Policies Work](https://docs.cloud.oracle.com/Content/Identity/Concepts/policies.htm). * <p> * You must also specify a *description* for the dynamic group (although it can be an empty string). It does not * have to be unique, and you can change it anytime with {@link #updateDynamicGroup(UpdateDynamicGroupRequest, Consumer, Consumer) updateDynamicGroup}. * <p> * After you send your request, the new object's `lifecycleState` will temporarily be CREATING. Before using the * object, first make sure its `lifecycleState` has changed to ACTIVE. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreateDynamicGroupResponse> createDynamicGroup( CreateDynamicGroupRequest request, com.oracle.bmc.responses.AsyncHandler< CreateDynamicGroupRequest, CreateDynamicGroupResponse> handler); /** * Creates a new group in your tenancy. * <p> * You must specify your tenancy's OCID as the compartment ID in the request object (remember that the tenancy * is simply the root compartment). Notice that IAM resources (users, groups, compartments, and some policies) * reside within the tenancy itself, unlike cloud resources such as compute instances, which typically * reside within compartments inside the tenancy. For information about OCIDs, see * [Resource Identifiers](https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm). * <p> * You must also specify a *name* for the group, which must be unique across all groups in your tenancy and * cannot be changed. You can use this name or the OCID when writing policies that apply to the group. For more * information about policies, see [How Policies Work](https://docs.cloud.oracle.com/Content/Identity/Concepts/policies.htm). * <p> * You must also specify a *description* for the group (although it can be an empty string). It does not * have to be unique, and you can change it anytime with {@link #updateGroup(UpdateGroupRequest, Consumer, Consumer) updateGroup}. * <p> * After you send your request, the new object's `lifecycleState` will temporarily be CREATING. Before using the * object, first make sure its `lifecycleState` has changed to ACTIVE. * <p> * After creating the group, you need to put users in it and write policies for it. * See {@link #addUserToGroup(AddUserToGroupRequest, Consumer, Consumer) addUserToGroup} and * {@link #createPolicy(CreatePolicyRequest, Consumer, Consumer) createPolicy}. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreateGroupResponse> createGroup( CreateGroupRequest request, com.oracle.bmc.responses.AsyncHandler<CreateGroupRequest, CreateGroupResponse> handler); /** * Creates a new identity provider in your tenancy. For more information, see * [Identity Providers and Federation](https://docs.cloud.oracle.com/Content/Identity/Concepts/federation.htm). * <p> * You must specify your tenancy's OCID as the compartment ID in the request object. * Remember that the tenancy is simply the root compartment. For information about * OCIDs, see [Resource Identifiers](https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm). * <p> * You must also specify a *name* for the `IdentityProvider`, which must be unique * across all `IdentityProvider` objects in your tenancy and cannot be changed. * <p> * You must also specify a *description* for the `IdentityProvider` (although * it can be an empty string). It does not have to be unique, and you can change * it anytime with * {@link #updateIdentityProvider(UpdateIdentityProviderRequest, Consumer, Consumer) updateIdentityProvider}. * <p> * After you send your request, the new object's `lifecycleState` will temporarily * be CREATING. Before using the object, first make sure its `lifecycleState` has * changed to ACTIVE. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreateIdentityProviderResponse> createIdentityProvider( CreateIdentityProviderRequest request, com.oracle.bmc.responses.AsyncHandler< CreateIdentityProviderRequest, CreateIdentityProviderResponse> handler); /** * Creates a single mapping between an IdP group and an IAM Service * {@link Group}. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreateIdpGroupMappingResponse> createIdpGroupMapping( CreateIdpGroupMappingRequest request, com.oracle.bmc.responses.AsyncHandler< CreateIdpGroupMappingRequest, CreateIdpGroupMappingResponse> handler); /** * Creates a new MFA TOTP device for the user. A user can have one MFA TOTP device. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreateMfaTotpDeviceResponse> createMfaTotpDevice( CreateMfaTotpDeviceRequest request, com.oracle.bmc.responses.AsyncHandler< CreateMfaTotpDeviceRequest, CreateMfaTotpDeviceResponse> handler); /** * Creates a new network source in your tenancy. * <p> * You must specify your tenancy's OCID as the compartment ID in the request object (remember that the tenancy * is simply the root compartment). Notice that IAM resources (users, groups, compartments, and some policies) * reside within the tenancy itself, unlike cloud resources such as compute instances, which typically * reside within compartments inside the tenancy. For information about OCIDs, see * [Resource Identifiers](https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm). * <p> * You must also specify a *name* for the network source, which must be unique across all network sources in your * tenancy, and cannot be changed. * You can use this name or the OCID when writing policies that apply to the network source. For more information * about policies, see [How Policies Work](https://docs.cloud.oracle.com/Content/Identity/Concepts/policies.htm). * <p> * You must also specify a *description* for the network source (although it can be an empty string). It does not * have to be unique, and you can change it anytime with {@link #updateNetworkSource(UpdateNetworkSourceRequest, Consumer, Consumer) updateNetworkSource}. * <p> * After you send your request, the new object's `lifecycleState` will temporarily be CREATING. Before using the * object, first make sure its `lifecycleState` has changed to ACTIVE. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreateNetworkSourceResponse> createNetworkSource( CreateNetworkSourceRequest request, com.oracle.bmc.responses.AsyncHandler< CreateNetworkSourceRequest, CreateNetworkSourceResponse> handler); /** * Creates Oauth token for the user * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreateOAuthClientCredentialResponse> createOAuthClientCredential( CreateOAuthClientCredentialRequest request, com.oracle.bmc.responses.AsyncHandler< CreateOAuthClientCredentialRequest, CreateOAuthClientCredentialResponse> handler); /** * Creates a new Console one-time password for the specified user. For more information about user * credentials, see [User Credentials](https://docs.cloud.oracle.com/Content/Identity/Concepts/usercredentials.htm). * <p> * Use this operation after creating a new user, or if a user forgets their password. The new one-time * password is returned to you in the response, and you must securely deliver it to the user. They'll * be prompted to change this password the next time they sign in to the Console. If they don't change * it within 7 days, the password will expire and you'll need to create a new one-time password for the * user. * <p> **Note:** The user's Console login is the unique name you specified when you created the user * (see {@link #createUser(CreateUserRequest, Consumer, Consumer) createUser}). * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreateOrResetUIPasswordResponse> createOrResetUIPassword( CreateOrResetUIPasswordRequest request, com.oracle.bmc.responses.AsyncHandler< CreateOrResetUIPasswordRequest, CreateOrResetUIPasswordResponse> handler); /** * Creates a new policy in the specified compartment (either the tenancy or another of your compartments). * If you're new to policies, see [Getting Started with Policies](https://docs.cloud.oracle.com/Content/Identity/Concepts/policygetstarted.htm). * <p> * You must specify a *name* for the policy, which must be unique across all policies in your tenancy * and cannot be changed. * <p> * You must also specify a *description* for the policy (although it can be an empty string). It does not * have to be unique, and you can change it anytime with {@link #updatePolicy(UpdatePolicyRequest, Consumer, Consumer) updatePolicy}. * <p> * You must specify one or more policy statements in the statements array. For information about writing * policies, see [How Policies Work](https://docs.cloud.oracle.com/Content/Identity/Concepts/policies.htm) and * [Common Policies](https://docs.cloud.oracle.com/Content/Identity/Concepts/commonpolicies.htm). * <p> * After you send your request, the new object's `lifecycleState` will temporarily be CREATING. Before using the * object, first make sure its `lifecycleState` has changed to ACTIVE. * <p> * New policies take effect typically within 10 seconds. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreatePolicyResponse> createPolicy( CreatePolicyRequest request, com.oracle.bmc.responses.AsyncHandler<CreatePolicyRequest, CreatePolicyResponse> handler); /** * Creates a subscription to a region for a tenancy. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreateRegionSubscriptionResponse> createRegionSubscription( CreateRegionSubscriptionRequest request, com.oracle.bmc.responses.AsyncHandler< CreateRegionSubscriptionRequest, CreateRegionSubscriptionResponse> handler); /** * Creates a new SMTP credential for the specified user. An SMTP credential has an SMTP user name and an SMTP password. * You must specify a *description* for the SMTP credential (although it can be an empty string). It does not * have to be unique, and you can change it anytime with * {@link #updateSmtpCredential(UpdateSmtpCredentialRequest, Consumer, Consumer) updateSmtpCredential}. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreateSmtpCredentialResponse> createSmtpCredential( CreateSmtpCredentialRequest request, com.oracle.bmc.responses.AsyncHandler< CreateSmtpCredentialRequest, CreateSmtpCredentialResponse> handler); /** * **Deprecated. Use {@link #createAuthToken(CreateAuthTokenRequest, Consumer, Consumer) createAuthToken} instead.** * <p> * Creates a new Swift password for the specified user. For information about what Swift passwords are for, see * [Managing User Credentials](https://docs.cloud.oracle.com/Content/Identity/Tasks/managingcredentials.htm). * <p> * You must specify a *description* for the Swift password (although it can be an empty string). It does not * have to be unique, and you can change it anytime with * {@link #updateSwiftPassword(UpdateSwiftPasswordRequest, Consumer, Consumer) updateSwiftPassword}. * <p> * Every user has permission to create a Swift password for *their own user ID*. An administrator in your organization * does not need to write a policy to give users this ability. To compare, administrators who have permission to the * tenancy can use this operation to create a Swift password for any user, including themselves. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreateSwiftPasswordResponse> createSwiftPassword( CreateSwiftPasswordRequest request, com.oracle.bmc.responses.AsyncHandler< CreateSwiftPasswordRequest, CreateSwiftPasswordResponse> handler); /** * Creates a new tag in the specified tag namespace. * <p> * The tag requires either the OCID or the name of the tag namespace that will contain this * tag definition. * <p> * You must specify a *name* for the tag, which must be unique across all tags in the tag namespace * and cannot be changed. The name can contain any ASCII character except the space (_) or period (.) characters. * Names are case insensitive. That means, for example, \"myTag\" and \"mytag\" are not allowed in the same namespace. * If you specify a name that's already in use in the tag namespace, a 409 error is returned. * <p> * The tag must have a *description*. It does not have to be unique, and you can change it with * {@link #updateTag(UpdateTagRequest, Consumer, Consumer) updateTag}. * <p> * The tag must have a value type, which is specified with a validator. Tags can use either a * static value or a list of possible values. Static values are entered by a user applying the tag * to a resource. Lists are created by you and the user must apply a value from the list. Lists * are validiated. * <p> * If no `validator` is set, the user applying the tag to a resource can type in a static * value or leave the tag value empty. * * If a `validator` is set, the user applying the tag to a resource must select from a list * of values that you supply with {@link #enumTagDefinitionValidator(EnumTagDefinitionValidatorRequest, Consumer, Consumer) enumTagDefinitionValidator}. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreateTagResponse> createTag( CreateTagRequest request, com.oracle.bmc.responses.AsyncHandler<CreateTagRequest, CreateTagResponse> handler); /** * Creates a new tag default in the specified compartment for the specified tag definition. * <p> * If you specify that a value is required, a value is set during resource creation (either by * the user creating the resource or another tag defualt). If no value is set, resource creation * is blocked. * <p> * If the `isRequired` flag is set to \"true\", the value is set during resource creation. * * If the `isRequired` flag is set to \"false\", the value you enter is set during resource creation. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreateTagDefaultResponse> createTagDefault( CreateTagDefaultRequest request, com.oracle.bmc.responses.AsyncHandler<CreateTagDefaultRequest, CreateTagDefaultResponse> handler); /** * Creates a new tag namespace in the specified compartment. * <p> * You must specify the compartment ID in the request object (remember that the tenancy is simply the root * compartment). * <p> * You must also specify a *name* for the namespace, which must be unique across all namespaces in your tenancy * and cannot be changed. The name can contain any ASCII character except the space (_) or period (.). * Names are case insensitive. That means, for example, \"myNamespace\" and \"mynamespace\" are not allowed * in the same tenancy. Once you created a namespace, you cannot change the name. * If you specify a name that's already in use in the tenancy, a 409 error is returned. * <p> * You must also specify a *description* for the namespace. * It does not have to be unique, and you can change it with * {@link #updateTagNamespace(UpdateTagNamespaceRequest, Consumer, Consumer) updateTagNamespace}. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreateTagNamespaceResponse> createTagNamespace( CreateTagNamespaceRequest request, com.oracle.bmc.responses.AsyncHandler< CreateTagNamespaceRequest, CreateTagNamespaceResponse> handler); /** * Creates a new user in your tenancy. For conceptual information about users, your tenancy, and other * IAM Service components, see [Overview of the IAM Service](https://docs.cloud.oracle.com/Content/Identity/Concepts/overview.htm). * <p> * You must specify your tenancy's OCID as the compartment ID in the request object (remember that the * tenancy is simply the root compartment). Notice that IAM resources (users, groups, compartments, and * some policies) reside within the tenancy itself, unlike cloud resources such as compute instances, * which typically reside within compartments inside the tenancy. For information about OCIDs, see * [Resource Identifiers](https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm). * <p> * You must also specify a *name* for the user, which must be unique across all users in your tenancy * and cannot be changed. Allowed characters: No spaces. Only letters, numerals, hyphens, periods, * underscores, +, and @. If you specify a name that's already in use, you'll get a 409 error. * This name will be the user's login to the Console. You might want to pick a * name that your company's own identity system (e.g., Active Directory, LDAP, etc.) already uses. * If you delete a user and then create a new user with the same name, they'll be considered different * users because they have different OCIDs. * <p> * You must also specify a *description* for the user (although it can be an empty string). * It does not have to be unique, and you can change it anytime with * {@link #updateUser(UpdateUserRequest, Consumer, Consumer) updateUser}. You can use the field to provide the user's * full name, a description, a nickname, or other information to generally identify the user. * <p> * After you send your request, the new object's `lifecycleState` will temporarily be CREATING. Before * using the object, first make sure its `lifecycleState` has changed to ACTIVE. * <p> * A new user has no permissions until you place the user in one or more groups (see * {@link #addUserToGroup(AddUserToGroupRequest, Consumer, Consumer) addUserToGroup}). If the user needs to * access the Console, you need to provide the user a password (see * {@link #createOrResetUIPassword(CreateOrResetUIPasswordRequest, Consumer, Consumer) createOrResetUIPassword}). * If the user needs to access the Oracle Cloud Infrastructure REST API, you need to upload a * public API signing key for that user (see * [Required Keys and OCIDs](https://docs.cloud.oracle.com/Content/API/Concepts/apisigningkey.htm) and also * {@link #uploadApiKey(UploadApiKeyRequest, Consumer, Consumer) uploadApiKey}). * <p> **Important:** Make sure to inform the new user which compartment(s) they have access to. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<CreateUserResponse> createUser( CreateUserRequest request, com.oracle.bmc.responses.AsyncHandler<CreateUserRequest, CreateUserResponse> handler); /** * Deletes the specified API signing key for the specified user. * <p> * Every user has permission to use this operation to delete a key for *their own user ID*. An * administrator in your organization does not need to write a policy to give users this ability. * To compare, administrators who have permission to the tenancy can use this operation to delete * a key for any user, including themselves. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<DeleteApiKeyResponse> deleteApiKey( DeleteApiKeyRequest request, com.oracle.bmc.responses.AsyncHandler<DeleteApiKeyRequest, DeleteApiKeyResponse> handler); /** * Deletes the specified auth token for the specified user. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<DeleteAuthTokenResponse> deleteAuthToken( DeleteAuthTokenRequest request, com.oracle.bmc.responses.AsyncHandler<DeleteAuthTokenRequest, DeleteAuthTokenResponse> handler); /** * Deletes the specified compartment. The compartment must be empty. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<DeleteCompartmentResponse> deleteCompartment( DeleteCompartmentRequest request, com.oracle.bmc.responses.AsyncHandler< DeleteCompartmentRequest, DeleteCompartmentResponse> handler); /** * Deletes the specified secret key for the specified user. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<DeleteCustomerSecretKeyResponse> deleteCustomerSecretKey( DeleteCustomerSecretKeyRequest request, com.oracle.bmc.responses.AsyncHandler< DeleteCustomerSecretKeyRequest, DeleteCustomerSecretKeyResponse> handler); /** * Deletes the specified dynamic group. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<DeleteDynamicGroupResponse> deleteDynamicGroup( DeleteDynamicGroupRequest request, com.oracle.bmc.responses.AsyncHandler< DeleteDynamicGroupRequest, DeleteDynamicGroupResponse> handler); /** * Deletes the specified group. The group must be empty. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<DeleteGroupResponse> deleteGroup( DeleteGroupRequest request, com.oracle.bmc.responses.AsyncHandler<DeleteGroupRequest, DeleteGroupResponse> handler); /** * Deletes the specified identity provider. The identity provider must not have * any group mappings (see {@link IdpGroupMapping}). * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<DeleteIdentityProviderResponse> deleteIdentityProvider( DeleteIdentityProviderRequest request, com.oracle.bmc.responses.AsyncHandler< DeleteIdentityProviderRequest, DeleteIdentityProviderResponse> handler); /** * Deletes the specified group mapping. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<DeleteIdpGroupMappingResponse> deleteIdpGroupMapping( DeleteIdpGroupMappingRequest request, com.oracle.bmc.responses.AsyncHandler< DeleteIdpGroupMappingRequest, DeleteIdpGroupMappingResponse> handler); /** * Deletes the specified MFA TOTP device for the specified user. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<DeleteMfaTotpDeviceResponse> deleteMfaTotpDevice( DeleteMfaTotpDeviceRequest request, com.oracle.bmc.responses.AsyncHandler< DeleteMfaTotpDeviceRequest, DeleteMfaTotpDeviceResponse> handler); /** * Deletes the specified network source * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<DeleteNetworkSourceResponse> deleteNetworkSource( DeleteNetworkSourceRequest request, com.oracle.bmc.responses.AsyncHandler< DeleteNetworkSourceRequest, DeleteNetworkSourceResponse> handler); /** * Delete Oauth token for the user * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<DeleteOAuthClientCredentialResponse> deleteOAuthClientCredential( DeleteOAuthClientCredentialRequest request, com.oracle.bmc.responses.AsyncHandler< DeleteOAuthClientCredentialRequest, DeleteOAuthClientCredentialResponse> handler); /** * Deletes the specified policy. The deletion takes effect typically within 10 seconds. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<DeletePolicyResponse> deletePolicy( DeletePolicyRequest request, com.oracle.bmc.responses.AsyncHandler<DeletePolicyRequest, DeletePolicyResponse> handler); /** * Deletes the specified SMTP credential for the specified user. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<DeleteSmtpCredentialResponse> deleteSmtpCredential( DeleteSmtpCredentialRequest request, com.oracle.bmc.responses.AsyncHandler< DeleteSmtpCredentialRequest, DeleteSmtpCredentialResponse> handler); /** * **Deprecated. Use {@link #deleteAuthToken(DeleteAuthTokenRequest, Consumer, Consumer) deleteAuthToken} instead.** * <p> * Deletes the specified Swift password for the specified user. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<DeleteSwiftPasswordResponse> deleteSwiftPassword( DeleteSwiftPasswordRequest request, com.oracle.bmc.responses.AsyncHandler< DeleteSwiftPasswordRequest, DeleteSwiftPasswordResponse> handler); /** * Deletes the specified tag definition. This operation triggers a process that removes the * tag from all resources in your tenancy. * <p> * These things happen immediately: * \u00A0 * * If the tag was a cost-tracking tag, it no longer counts against your 10 cost-tracking * tags limit, whether you first disabled it or not. * * If the tag was used with dynamic groups, none of the rules that contain the tag will * be evaluated against the tag. * <p> * Once you start the delete operation, the state of the tag changes to DELETING and tag removal * from resources begins. This can take up to 48 hours depending on the number of resources that * were tagged as well as the regions in which those resources reside. When all tags have been * removed, the state changes to DELETED. You cannot restore a deleted tag. Once the deleted tag * changes its state to DELETED, you can use the same tag name again. * <p> * To delete a tag, you must first retire it. Use {@link #updateTag(UpdateTagRequest, Consumer, Consumer) updateTag} * to retire a tag. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<DeleteTagResponse> deleteTag( DeleteTagRequest request, com.oracle.bmc.responses.AsyncHandler<DeleteTagRequest, DeleteTagResponse> handler); /** * Deletes the the specified tag default. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<DeleteTagDefaultResponse> deleteTagDefault( DeleteTagDefaultRequest request, com.oracle.bmc.responses.AsyncHandler<DeleteTagDefaultRequest, DeleteTagDefaultResponse> handler); /** * Deletes the specified tag namespace. Only an empty tag namespace can be deleted. To delete * a tag namespace, first delete all its tag definitions. * <p> * Use {@link #deleteTag(DeleteTagRequest, Consumer, Consumer) deleteTag} to delete a tag definition. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<DeleteTagNamespaceResponse> deleteTagNamespace( DeleteTagNamespaceRequest request, com.oracle.bmc.responses.AsyncHandler< DeleteTagNamespaceRequest, DeleteTagNamespaceResponse> handler); /** * Deletes the specified user. The user must not be in any groups. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<DeleteUserResponse> deleteUser( DeleteUserRequest request, com.oracle.bmc.responses.AsyncHandler<DeleteUserRequest, DeleteUserResponse> handler); /** * Generate seed for the MFA TOTP device. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GenerateTotpSeedResponse> generateTotpSeed( GenerateTotpSeedRequest request, com.oracle.bmc.responses.AsyncHandler<GenerateTotpSeedRequest, GenerateTotpSeedResponse> handler); /** * Gets the authentication policy for the given tenancy. You must specify your tenant\u2019s OCID as the value for * the compartment ID (remember that the tenancy is simply the root compartment). * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GetAuthenticationPolicyResponse> getAuthenticationPolicy( GetAuthenticationPolicyRequest request, com.oracle.bmc.responses.AsyncHandler< GetAuthenticationPolicyRequest, GetAuthenticationPolicyResponse> handler); /** * Gets the specified compartment's information. * <p> * This operation does not return a list of all the resources inside the compartment. There is no single * API operation that does that. Compartments can contain multiple types of resources (instances, block * storage volumes, etc.). To find out what's in a compartment, you must call the \"List\" operation for * each resource type and specify the compartment's OCID as a query parameter in the request. For example, * call the {@link #listInstances(ListInstancesRequest, Consumer, Consumer) listInstances} operation in the Cloud Compute * Service or the {@link #listVolumes(ListVolumesRequest, Consumer, Consumer) listVolumes} operation in Cloud Block Storage. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GetCompartmentResponse> getCompartment( GetCompartmentRequest request, com.oracle.bmc.responses.AsyncHandler<GetCompartmentRequest, GetCompartmentResponse> handler); /** * Gets the specified dynamic group's information. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GetDynamicGroupResponse> getDynamicGroup( GetDynamicGroupRequest request, com.oracle.bmc.responses.AsyncHandler<GetDynamicGroupRequest, GetDynamicGroupResponse> handler); /** * Gets the specified group's information. * <p> * This operation does not return a list of all the users in the group. To do that, use * {@link #listUserGroupMemberships(ListUserGroupMembershipsRequest, Consumer, Consumer) listUserGroupMemberships} and * provide the group's OCID as a query parameter in the request. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GetGroupResponse> getGroup( GetGroupRequest request, com.oracle.bmc.responses.AsyncHandler<GetGroupRequest, GetGroupResponse> handler); /** * Gets the specified identity provider's information. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GetIdentityProviderResponse> getIdentityProvider( GetIdentityProviderRequest request, com.oracle.bmc.responses.AsyncHandler< GetIdentityProviderRequest, GetIdentityProviderResponse> handler); /** * Gets the specified group mapping. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GetIdpGroupMappingResponse> getIdpGroupMapping( GetIdpGroupMappingRequest request, com.oracle.bmc.responses.AsyncHandler< GetIdpGroupMappingRequest, GetIdpGroupMappingResponse> handler); /** * Get the specified MFA TOTP device for the specified user. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GetMfaTotpDeviceResponse> getMfaTotpDevice( GetMfaTotpDeviceRequest request, com.oracle.bmc.responses.AsyncHandler<GetMfaTotpDeviceRequest, GetMfaTotpDeviceResponse> handler); /** * Gets the specified network source's information. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GetNetworkSourceResponse> getNetworkSource( GetNetworkSourceRequest request, com.oracle.bmc.responses.AsyncHandler<GetNetworkSourceRequest, GetNetworkSourceResponse> handler); /** * Gets the specified policy's information. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GetPolicyResponse> getPolicy( GetPolicyRequest request, com.oracle.bmc.responses.AsyncHandler<GetPolicyRequest, GetPolicyResponse> handler); /** * Gets the specified tag's information. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GetTagResponse> getTag( GetTagRequest request, com.oracle.bmc.responses.AsyncHandler<GetTagRequest, GetTagResponse> handler); /** * Retrieves the specified tag default. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GetTagDefaultResponse> getTagDefault( GetTagDefaultRequest request, com.oracle.bmc.responses.AsyncHandler<GetTagDefaultRequest, GetTagDefaultResponse> handler); /** * Gets the specified tag namespace's information. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GetTagNamespaceResponse> getTagNamespace( GetTagNamespaceRequest request, com.oracle.bmc.responses.AsyncHandler<GetTagNamespaceRequest, GetTagNamespaceResponse> handler); /** * Gets details on a specified work request. The workRequestID is returned in the opc-workrequest-id header * for any asynchronous operation in the Identity and Access Management service. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GetTaggingWorkRequestResponse> getTaggingWorkRequest( GetTaggingWorkRequestRequest request, com.oracle.bmc.responses.AsyncHandler< GetTaggingWorkRequestRequest, GetTaggingWorkRequestResponse> handler); /** * Get the specified tenancy's information. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GetTenancyResponse> getTenancy( GetTenancyRequest request, com.oracle.bmc.responses.AsyncHandler<GetTenancyRequest, GetTenancyResponse> handler); /** * Gets the specified user's information. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GetUserResponse> getUser( GetUserRequest request, com.oracle.bmc.responses.AsyncHandler<GetUserRequest, GetUserResponse> handler); /** * Gets the specified UserGroupMembership's information. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GetUserGroupMembershipResponse> getUserGroupMembership( GetUserGroupMembershipRequest request, com.oracle.bmc.responses.AsyncHandler< GetUserGroupMembershipRequest, GetUserGroupMembershipResponse> handler); /** * Gets the specified user's console password information. The returned object contains the user's OCID, * but not the password itself. The actual password is returned only when created or reset. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GetUserUIPasswordInformationResponse> getUserUIPasswordInformation( GetUserUIPasswordInformationRequest request, com.oracle.bmc.responses.AsyncHandler< GetUserUIPasswordInformationRequest, GetUserUIPasswordInformationResponse> handler); /** * Gets details on a specified work request. The workRequestID is returned in the opc-workrequest-id header * for any asynchronous operation in the Identity and Access Management service. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<GetWorkRequestResponse> getWorkRequest( GetWorkRequestRequest request, com.oracle.bmc.responses.AsyncHandler<GetWorkRequestRequest, GetWorkRequestResponse> handler); /** * Lists the API signing keys for the specified user. A user can have a maximum of three keys. * <p> * Every user has permission to use this API call for *their own user ID*. An administrator in your * organization does not need to write a policy to give users this ability. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListApiKeysResponse> listApiKeys( ListApiKeysRequest request, com.oracle.bmc.responses.AsyncHandler<ListApiKeysRequest, ListApiKeysResponse> handler); /** * Lists the auth tokens for the specified user. The returned object contains the token's OCID, but not * the token itself. The actual token is returned only upon creation. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListAuthTokensResponse> listAuthTokens( ListAuthTokensRequest request, com.oracle.bmc.responses.AsyncHandler<ListAuthTokensRequest, ListAuthTokensResponse> handler); /** * Lists the availability domains in your tenancy. Specify the OCID of either the tenancy or another * of your compartments as the value for the compartment ID (remember that the tenancy is simply the root compartment). * See [Where to Get the Tenancy's OCID and User's OCID](https://docs.cloud.oracle.com/Content/API/Concepts/apisigningkey.htm#five). * Note that the order of the results returned can change if availability domains are added or removed; therefore, do not * create a dependency on the list order. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListAvailabilityDomainsResponse> listAvailabilityDomains( ListAvailabilityDomainsRequest request, com.oracle.bmc.responses.AsyncHandler< ListAvailabilityDomainsRequest, ListAvailabilityDomainsResponse> handler); /** * Lists the compartments in a specified compartment. The members of the list * returned depends on the values set for several parameters. * <p> * With the exception of the tenancy (root compartment), the ListCompartments operation * returns only the first-level child compartments in the parent compartment specified in * `compartmentId`. The list does not include any subcompartments of the child * compartments (grandchildren). * <p> * The parameter `accessLevel` specifies whether to return only those compartments for which the * requestor has INSPECT permissions on at least one resource directly * or indirectly (the resource can be in a subcompartment). * <p> * The parameter `compartmentIdInSubtree` applies only when you perform ListCompartments on the * tenancy (root compartment). When set to true, the entire hierarchy of compartments can be returned. * To get a full list of all compartments and subcompartments in the tenancy (root compartment), * set the parameter `compartmentIdInSubtree` to true and `accessLevel` to ANY. * <p> * See [Where to Get the Tenancy's OCID and User's OCID](https://docs.cloud.oracle.com/Content/API/Concepts/apisigningkey.htm#five). * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListCompartmentsResponse> listCompartments( ListCompartmentsRequest request, com.oracle.bmc.responses.AsyncHandler<ListCompartmentsRequest, ListCompartmentsResponse> handler); /** * Lists all the tags enabled for cost-tracking in the specified tenancy. For information about * cost-tracking tags, see [Using Cost-tracking Tags](https://docs.cloud.oracle.com/Content/Identity/Concepts/taggingoverview.htm#costs). * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListCostTrackingTagsResponse> listCostTrackingTags( ListCostTrackingTagsRequest request, com.oracle.bmc.responses.AsyncHandler< ListCostTrackingTagsRequest, ListCostTrackingTagsResponse> handler); /** * Lists the secret keys for the specified user. The returned object contains the secret key's OCID, but not * the secret key itself. The actual secret key is returned only upon creation. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListCustomerSecretKeysResponse> listCustomerSecretKeys( ListCustomerSecretKeysRequest request, com.oracle.bmc.responses.AsyncHandler< ListCustomerSecretKeysRequest, ListCustomerSecretKeysResponse> handler); /** * Lists the dynamic groups in your tenancy. You must specify your tenancy's OCID as the value for * the compartment ID (remember that the tenancy is simply the root compartment). * See [Where to Get the Tenancy's OCID and User's OCID](https://docs.cloud.oracle.com/Content/API/Concepts/apisigningkey.htm#five). * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListDynamicGroupsResponse> listDynamicGroups( ListDynamicGroupsRequest request, com.oracle.bmc.responses.AsyncHandler< ListDynamicGroupsRequest, ListDynamicGroupsResponse> handler); /** * Lists the Fault Domains in your tenancy. Specify the OCID of either the tenancy or another * of your compartments as the value for the compartment ID (remember that the tenancy is simply the root compartment). * See [Where to Get the Tenancy's OCID and User's OCID](https://docs.cloud.oracle.com/Content/API/Concepts/apisigningkey.htm#five). * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListFaultDomainsResponse> listFaultDomains( ListFaultDomainsRequest request, com.oracle.bmc.responses.AsyncHandler<ListFaultDomainsRequest, ListFaultDomainsResponse> handler); /** * Lists the groups in your tenancy. You must specify your tenancy's OCID as the value for * the compartment ID (remember that the tenancy is simply the root compartment). * See [Where to Get the Tenancy's OCID and User's OCID](https://docs.cloud.oracle.com/Content/API/Concepts/apisigningkey.htm#five). * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListGroupsResponse> listGroups( ListGroupsRequest request, com.oracle.bmc.responses.AsyncHandler<ListGroupsRequest, ListGroupsResponse> handler); /** * Lists the identity provider groups. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListIdentityProviderGroupsResponse> listIdentityProviderGroups( ListIdentityProviderGroupsRequest request, com.oracle.bmc.responses.AsyncHandler< ListIdentityProviderGroupsRequest, ListIdentityProviderGroupsResponse> handler); /** * Lists all the identity providers in your tenancy. You must specify the identity provider type (e.g., `SAML2` for * identity providers using the SAML2.0 protocol). You must specify your tenancy's OCID as the value for the * compartment ID (remember that the tenancy is simply the root compartment). * See [Where to Get the Tenancy's OCID and User's OCID](https://docs.cloud.oracle.com/Content/API/Concepts/apisigningkey.htm#five). * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListIdentityProvidersResponse> listIdentityProviders( ListIdentityProvidersRequest request, com.oracle.bmc.responses.AsyncHandler< ListIdentityProvidersRequest, ListIdentityProvidersResponse> handler); /** * Lists the group mappings for the specified identity provider. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListIdpGroupMappingsResponse> listIdpGroupMappings( ListIdpGroupMappingsRequest request, com.oracle.bmc.responses.AsyncHandler< ListIdpGroupMappingsRequest, ListIdpGroupMappingsResponse> handler); /** * Lists the MFA TOTP devices for the specified user. The returned object contains the device's OCID, but not * the seed. The seed is returned only upon creation or when the IAM service regenerates the MFA seed for the device. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListMfaTotpDevicesResponse> listMfaTotpDevices( ListMfaTotpDevicesRequest request, com.oracle.bmc.responses.AsyncHandler< ListMfaTotpDevicesRequest, ListMfaTotpDevicesResponse> handler); /** * Lists the network sources in your tenancy. You must specify your tenancy's OCID as the value for * the compartment ID (remember that the tenancy is simply the root compartment). * See [Where to Get the Tenancy's OCID and User's OCID](https://docs.cloud.oracle.com/Content/API/Concepts/apisigningkey.htm#five). * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListNetworkSourcesResponse> listNetworkSources( ListNetworkSourcesRequest request, com.oracle.bmc.responses.AsyncHandler< ListNetworkSourcesRequest, ListNetworkSourcesResponse> handler); /** * List of Oauth tokens for the user * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListOAuthClientCredentialsResponse> listOAuthClientCredentials( ListOAuthClientCredentialsRequest request, com.oracle.bmc.responses.AsyncHandler< ListOAuthClientCredentialsRequest, ListOAuthClientCredentialsResponse> handler); /** * Lists the policies in the specified compartment (either the tenancy or another of your compartments). * See [Where to Get the Tenancy's OCID and User's OCID](https://docs.cloud.oracle.com/Content/API/Concepts/apisigningkey.htm#five). * <p> * To determine which policies apply to a particular group or compartment, you must view the individual * statements inside all your policies. There isn't a way to automatically obtain that information via the API. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListPoliciesResponse> listPolicies( ListPoliciesRequest request, com.oracle.bmc.responses.AsyncHandler<ListPoliciesRequest, ListPoliciesResponse> handler); /** * Lists the region subscriptions for the specified tenancy. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListRegionSubscriptionsResponse> listRegionSubscriptions( ListRegionSubscriptionsRequest request, com.oracle.bmc.responses.AsyncHandler< ListRegionSubscriptionsRequest, ListRegionSubscriptionsResponse> handler); /** * Lists all the regions offered by Oracle Cloud Infrastructure. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListRegionsResponse> listRegions( ListRegionsRequest request, com.oracle.bmc.responses.AsyncHandler<ListRegionsRequest, ListRegionsResponse> handler); /** * Lists the SMTP credentials for the specified user. The returned object contains the credential's OCID, * the SMTP user name but not the SMTP password. The SMTP password is returned only upon creation. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListSmtpCredentialsResponse> listSmtpCredentials( ListSmtpCredentialsRequest request, com.oracle.bmc.responses.AsyncHandler< ListSmtpCredentialsRequest, ListSmtpCredentialsResponse> handler); /** * **Deprecated. Use {@link #listAuthTokens(ListAuthTokensRequest, Consumer, Consumer) listAuthTokens} instead.** * <p> * Lists the Swift passwords for the specified user. The returned object contains the password's OCID, but not * the password itself. The actual password is returned only upon creation. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListSwiftPasswordsResponse> listSwiftPasswords( ListSwiftPasswordsRequest request, com.oracle.bmc.responses.AsyncHandler< ListSwiftPasswordsRequest, ListSwiftPasswordsResponse> handler); /** * Lists the tag defaults for tag definitions in the specified compartment. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListTagDefaultsResponse> listTagDefaults( ListTagDefaultsRequest request, com.oracle.bmc.responses.AsyncHandler<ListTagDefaultsRequest, ListTagDefaultsResponse> handler); /** * Lists the tag namespaces in the specified compartment. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListTagNamespacesResponse> listTagNamespaces( ListTagNamespacesRequest request, com.oracle.bmc.responses.AsyncHandler< ListTagNamespacesRequest, ListTagNamespacesResponse> handler); /** * Gets the errors for a work request. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListTaggingWorkRequestErrorsResponse> listTaggingWorkRequestErrors( ListTaggingWorkRequestErrorsRequest request, com.oracle.bmc.responses.AsyncHandler< ListTaggingWorkRequestErrorsRequest, ListTaggingWorkRequestErrorsResponse> handler); /** * Gets the logs for a work request. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListTaggingWorkRequestLogsResponse> listTaggingWorkRequestLogs( ListTaggingWorkRequestLogsRequest request, com.oracle.bmc.responses.AsyncHandler< ListTaggingWorkRequestLogsRequest, ListTaggingWorkRequestLogsResponse> handler); /** * Lists the tagging work requests in compartment. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListTaggingWorkRequestsResponse> listTaggingWorkRequests( ListTaggingWorkRequestsRequest request, com.oracle.bmc.responses.AsyncHandler< ListTaggingWorkRequestsRequest, ListTaggingWorkRequestsResponse> handler); /** * Lists the tag definitions in the specified tag namespace. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListTagsResponse> listTags( ListTagsRequest request, com.oracle.bmc.responses.AsyncHandler<ListTagsRequest, ListTagsResponse> handler); /** * Lists the `UserGroupMembership` objects in your tenancy. You must specify your tenancy's OCID * as the value for the compartment ID * (see [Where to Get the Tenancy's OCID and User's OCID](https://docs.cloud.oracle.com/Content/API/Concepts/apisigningkey.htm#five)). * You must also then filter the list in one of these ways: * <p> * - You can limit the results to just the memberships for a given user by specifying a `userId`. * - Similarly, you can limit the results to just the memberships for a given group by specifying a `groupId`. * - You can set both the `userId` and `groupId` to determine if the specified user is in the specified group. * If the answer is no, the response is an empty list. * - Although`userId` and `groupId` are not individually required, you must set one of them. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListUserGroupMembershipsResponse> listUserGroupMemberships( ListUserGroupMembershipsRequest request, com.oracle.bmc.responses.AsyncHandler< ListUserGroupMembershipsRequest, ListUserGroupMembershipsResponse> handler); /** * Lists the users in your tenancy. You must specify your tenancy's OCID as the value for the * compartment ID (remember that the tenancy is simply the root compartment). * See [Where to Get the Tenancy's OCID and User's OCID](https://docs.cloud.oracle.com/Content/API/Concepts/apisigningkey.htm#five). * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListUsersResponse> listUsers( ListUsersRequest request, com.oracle.bmc.responses.AsyncHandler<ListUsersRequest, ListUsersResponse> handler); /** * Lists the work requests in compartment. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ListWorkRequestsResponse> listWorkRequests( ListWorkRequestsRequest request, com.oracle.bmc.responses.AsyncHandler<ListWorkRequestsRequest, ListWorkRequestsResponse> handler); /** * Move the compartment to a different parent compartment in the same tenancy. When you move a * compartment, all its contents (subcompartments and resources) are moved with it. Note that * the `CompartmentId` that you specify in the path is the compartment that you want to move. * <p> **IMPORTANT**: After you move a compartment to a new parent compartment, the access policies of * the new parent take effect and the policies of the previous parent no longer apply. Ensure that you * are aware of the implications for the compartment contents before you move it. For more * information, see [Moving a Compartment](https://docs.cloud.oracle.com/Content/Identity/Tasks/managingcompartments.htm#MoveCompartment). * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<MoveCompartmentResponse> moveCompartment( MoveCompartmentRequest request, com.oracle.bmc.responses.AsyncHandler<MoveCompartmentRequest, MoveCompartmentResponse> handler); /** * Recover the compartment from DELETED state to ACTIVE state. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<RecoverCompartmentResponse> recoverCompartment( RecoverCompartmentRequest request, com.oracle.bmc.responses.AsyncHandler< RecoverCompartmentRequest, RecoverCompartmentResponse> handler); /** * Removes a user from a group by deleting the corresponding `UserGroupMembership`. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<RemoveUserFromGroupResponse> removeUserFromGroup( RemoveUserFromGroupRequest request, com.oracle.bmc.responses.AsyncHandler< RemoveUserFromGroupRequest, RemoveUserFromGroupResponse> handler); /** * Resets the OAuth2 client credentials for the SCIM client associated with this identity provider. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<ResetIdpScimClientResponse> resetIdpScimClient( ResetIdpScimClientRequest request, com.oracle.bmc.responses.AsyncHandler< ResetIdpScimClientRequest, ResetIdpScimClientResponse> handler); /** * Updates the specified auth token's description. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdateAuthTokenResponse> updateAuthToken( UpdateAuthTokenRequest request, com.oracle.bmc.responses.AsyncHandler<UpdateAuthTokenRequest, UpdateAuthTokenResponse> handler); /** * Updates authentication policy for the specified tenancy * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdateAuthenticationPolicyResponse> updateAuthenticationPolicy( UpdateAuthenticationPolicyRequest request, com.oracle.bmc.responses.AsyncHandler< UpdateAuthenticationPolicyRequest, UpdateAuthenticationPolicyResponse> handler); /** * Updates the specified compartment's description or name. You can't update the root compartment. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdateCompartmentResponse> updateCompartment( UpdateCompartmentRequest request, com.oracle.bmc.responses.AsyncHandler< UpdateCompartmentRequest, UpdateCompartmentResponse> handler); /** * Updates the specified secret key's description. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdateCustomerSecretKeyResponse> updateCustomerSecretKey( UpdateCustomerSecretKeyRequest request, com.oracle.bmc.responses.AsyncHandler< UpdateCustomerSecretKeyRequest, UpdateCustomerSecretKeyResponse> handler); /** * Updates the specified dynamic group. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdateDynamicGroupResponse> updateDynamicGroup( UpdateDynamicGroupRequest request, com.oracle.bmc.responses.AsyncHandler< UpdateDynamicGroupRequest, UpdateDynamicGroupResponse> handler); /** * Updates the specified group. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdateGroupResponse> updateGroup( UpdateGroupRequest request, com.oracle.bmc.responses.AsyncHandler<UpdateGroupRequest, UpdateGroupResponse> handler); /** * Updates the specified identity provider. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdateIdentityProviderResponse> updateIdentityProvider( UpdateIdentityProviderRequest request, com.oracle.bmc.responses.AsyncHandler< UpdateIdentityProviderRequest, UpdateIdentityProviderResponse> handler); /** * Updates the specified group mapping. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdateIdpGroupMappingResponse> updateIdpGroupMapping( UpdateIdpGroupMappingRequest request, com.oracle.bmc.responses.AsyncHandler< UpdateIdpGroupMappingRequest, UpdateIdpGroupMappingResponse> handler); /** * Updates the specified network source. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdateNetworkSourceResponse> updateNetworkSource( UpdateNetworkSourceRequest request, com.oracle.bmc.responses.AsyncHandler< UpdateNetworkSourceRequest, UpdateNetworkSourceResponse> handler); /** * Updates Oauth token for the user * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdateOAuthClientCredentialResponse> updateOAuthClientCredential( UpdateOAuthClientCredentialRequest request, com.oracle.bmc.responses.AsyncHandler< UpdateOAuthClientCredentialRequest, UpdateOAuthClientCredentialResponse> handler); /** * Updates the specified policy. You can update the description or the policy statements themselves. * <p> * Policy changes take effect typically within 10 seconds. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdatePolicyResponse> updatePolicy( UpdatePolicyRequest request, com.oracle.bmc.responses.AsyncHandler<UpdatePolicyRequest, UpdatePolicyResponse> handler); /** * Updates the specified SMTP credential's description. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdateSmtpCredentialResponse> updateSmtpCredential( UpdateSmtpCredentialRequest request, com.oracle.bmc.responses.AsyncHandler< UpdateSmtpCredentialRequest, UpdateSmtpCredentialResponse> handler); /** * **Deprecated. Use {@link #updateAuthToken(UpdateAuthTokenRequest, Consumer, Consumer) updateAuthToken} instead.** * <p> * Updates the specified Swift password's description. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdateSwiftPasswordResponse> updateSwiftPassword( UpdateSwiftPasswordRequest request, com.oracle.bmc.responses.AsyncHandler< UpdateSwiftPasswordRequest, UpdateSwiftPasswordResponse> handler); /** * Updates the specified tag definition. * <p> * Setting `validator` determines the value type. Tags can use either a static value or a * list of possible values. Static values are entered by a user applying the tag to a resource. * Lists are created by you and the user must apply a value from the list. On update, any values * in a list that were previously set do not change, but new values must pass validation. Values * already applied to a resource do not change. * <p> * You cannot remove list values that appear in a TagDefault. To remove a list value that * appears in a TagDefault, first update the TagDefault to use a different value. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdateTagResponse> updateTag( UpdateTagRequest request, com.oracle.bmc.responses.AsyncHandler<UpdateTagRequest, UpdateTagResponse> handler); /** * Updates the specified tag default. If you specify that a value is required, a value is set * during resource creation (either by the user creating the resource or another tag defualt). * If no value is set, resource creation is blocked. * <p> * If the `isRequired` flag is set to \"true\", the value is set during resource creation. * * If the `isRequired` flag is set to \"false\", the value you enter is set during resource creation. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdateTagDefaultResponse> updateTagDefault( UpdateTagDefaultRequest request, com.oracle.bmc.responses.AsyncHandler<UpdateTagDefaultRequest, UpdateTagDefaultResponse> handler); /** * Updates the the specified tag namespace. You can't update the namespace name. * <p> * Updating `isRetired` to 'true' retires the namespace and all the tag definitions in the namespace. Reactivating a * namespace (changing `isRetired` from 'true' to 'false') does not reactivate tag definitions. * To reactivate the tag definitions, you must reactivate each one individually *after* you reactivate the namespace, * using {@link #updateTag(UpdateTagRequest, Consumer, Consumer) updateTag}. For more information about retiring tag namespaces, see * [Retiring Key Definitions and Namespace Definitions](https://docs.cloud.oracle.com/Content/Identity/Concepts/taggingoverview.htm#Retiring). * <p> * You can't add a namespace with the same name as a retired namespace in the same tenancy. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdateTagNamespaceResponse> updateTagNamespace( UpdateTagNamespaceRequest request, com.oracle.bmc.responses.AsyncHandler< UpdateTagNamespaceRequest, UpdateTagNamespaceResponse> handler); /** * Updates the description of the specified user. * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdateUserResponse> updateUser( UpdateUserRequest request, com.oracle.bmc.responses.AsyncHandler<UpdateUserRequest, UpdateUserResponse> handler); /** * Updates the capabilities of the specified user. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdateUserCapabilitiesResponse> updateUserCapabilities( UpdateUserCapabilitiesRequest request, com.oracle.bmc.responses.AsyncHandler< UpdateUserCapabilitiesRequest, UpdateUserCapabilitiesResponse> handler); /** * Updates the state of the specified user. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UpdateUserStateResponse> updateUserState( UpdateUserStateRequest request, com.oracle.bmc.responses.AsyncHandler<UpdateUserStateRequest, UpdateUserStateResponse> handler); /** * Uploads an API signing key for the specified user. * <p> * Every user has permission to use this operation to upload a key for *their own user ID*. An * administrator in your organization does not need to write a policy to give users this ability. * To compare, administrators who have permission to the tenancy can use this operation to upload a * key for any user, including themselves. * <p> **Important:** Even though you have permission to upload an API key, you might not yet * have permission to do much else. If you try calling an operation unrelated to your own credential * management (e.g., `ListUsers`, `LaunchInstance`) and receive an \"unauthorized\" error, * check with an administrator to confirm which IAM Service group(s) you're in and what access * you have. Also confirm you're working in the correct compartment. * <p> * After you send your request, the new object's `lifecycleState` will temporarily be CREATING. Before using * the object, first make sure its `lifecycleState` has changed to ACTIVE. * * * @param request The request object containing the details to send * @param handler The request handler to invoke upon completion, may be null. * @return A Future that can be used to get the response if no AsyncHandler was * provided. Note, if you provide an AsyncHandler and use the Future, some * types of responses (like java.io.InputStream) may not be able to be read in * both places as the underlying stream may only be consumed once. */ java.util.concurrent.Future<UploadApiKeyResponse> uploadApiKey( UploadApiKeyRequest request, com.oracle.bmc.responses.AsyncHandler<UploadApiKeyRequest, UploadApiKeyResponse> handler); }
package com.salesmanager.web.entity.catalog.product.attribute; import java.io.Serializable; import java.util.List; public class PersistableProductOptionValue extends ProductOptionValueEntity implements Serializable { /** * */ private static final long serialVersionUID = 1L; private List<ProductOptionValueDescription> descriptions; public void setDescriptions(List<ProductOptionValueDescription> descriptions) { this.descriptions = descriptions; } public List<ProductOptionValueDescription> getDescriptions() { return descriptions; } }
package office ; import com4j.*; @IID("{000C0357-0000-0000-C000-000000000046}") public interface HTMLProjectItems extends office._IMsoDispObj,Iterable<Com4jObject> { // Methods: /** * @param index Mandatory java.lang.Object parameter. * @return Returns a value of type office.HTMLProjectItem */ @DISPID(0) //= 0x0. The runtime will prefer the VTID if present @VTID(9) @DefaultMethod office.HTMLProjectItem item( java.lang.Object index); /** * <p> * Getter method for the COM property "Count" * </p> * @return Returns a value of type int */ @DISPID(1) //= 0x1. The runtime will prefer the VTID if present @VTID(10) int count(); /** * <p> * Getter method for the COM property "_NewEnum" * </p> */ @DISPID(-4) //= 0xfffffffc. The runtime will prefer the VTID if present @VTID(11) java.util.Iterator<Com4jObject> iterator(); /** * <p> * Getter method for the COM property "Parent" * </p> * @return Returns a value of type com4j.Com4jObject */ @DISPID(2) //= 0x2. The runtime will prefer the VTID if present @VTID(12) @ReturnValue(type=NativeType.Dispatch) com4j.Com4jObject parent(); // Properties: }
package play.data.validation; import play.libs.F.*; import static play.libs.F.*; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.*; import java.lang.annotation.*; import javax.validation.*; import javax.validation.metadata.*; import java.util.*; /** * Defines a set of built-in validation constraints. */ public class Constraints { /** * Super-type for validators. */ public static abstract class Validator<T> { /** * Returns <code>true</code> if this value is valid. */ public abstract boolean isValid(T object); /** * Returns <code>true</code> if this value is valid for the given constraint. * * @param constraintContext The JSR-303 validation context. */ public boolean isValid(T object, ConstraintValidatorContext constraintContext) { return isValid(object); } } /** * Converts a set of constraints to human-readable values. */ public static List<Tuple<String,List<Object>>> displayableConstraint(Set<ConstraintDescriptor<?>> constraints) { List<Tuple<String,List<Object>>> displayable = new ArrayList<Tuple<String,List<Object>>>(); for(ConstraintDescriptor<?> c: constraints) { Class<?> annotationType = c.getAnnotation().annotationType(); if(annotationType.isAnnotationPresent(play.data.Form.Display.class)) { play.data.Form.Display d = annotationType.getAnnotation(play.data.Form.Display.class); String name = d.name(); List<Object> attributes = new ArrayList<Object>(); Map<String,Object> annotationAttributes = c.getAttributes(); for(String attr: d.attributes()) { attributes.add(annotationAttributes.get(attr)); } displayable.add(Tuple(name, attributes)); } } return displayable; } // --- Required /** * Defines a field as required. */ @Target({FIELD}) @Retention(RUNTIME) @Constraint(validatedBy = RequiredValidator.class) @play.data.Form.Display(name="constraint.required") public static @interface Required { String message() default RequiredValidator.message; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; } /** * Validator for <code>@Required</code> fields. */ public static class RequiredValidator extends Validator<Object> implements ConstraintValidator<Required, Object> { final static public String message = "error.required"; public void initialize(Required constraintAnnotation) {} public boolean isValid(Object object) { if(object == null) { return false; } if(object instanceof String) { return !((String)object).isEmpty(); } if(object instanceof Collection) { return !((Collection)object).isEmpty(); } return true; } } /** * Constructs a 'required' validator. */ public static Validator<Object> required() { return new RequiredValidator(); } // --- Min /** * Defines a minumum value for a numeric field. */ @Target({FIELD}) @Retention(RUNTIME) @Constraint(validatedBy = MinValidator.class) @play.data.Form.Display(name="constraint.min", attributes={"value"}) public static @interface Min { String message() default MinValidator.message; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; long value(); } /** * Validator for <code>@Min</code> fields. */ public static class MinValidator extends Validator<Number> implements ConstraintValidator<Min, Number> { final static public String message = "error.min"; private long min; public MinValidator() {} public MinValidator(long value) { this.min = value; } public void initialize(Min constraintAnnotation) { this.min = constraintAnnotation.value(); } public boolean isValid(Number object) { if(object == null) { return true; } return object.longValue() >= min; } } /** * Constructs a 'min' validator. */ public static Validator<Number> min(long value) { return new MinValidator(value); } // --- Max /** * Defines a maximum value for a numeric field. */ @Target({FIELD}) @Retention(RUNTIME) @Constraint(validatedBy = MaxValidator.class) @play.data.Form.Display(name="constraint.max", attributes={"value"}) public static @interface Max { String message() default MaxValidator.message; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; long value(); } /** * Validator for <code>@Max</code> fields. */ public static class MaxValidator extends Validator<Number> implements ConstraintValidator<Max, Number> { final static public String message = "error.max"; private long max; public MaxValidator() {} public MaxValidator(long value) { this.max = value; } public void initialize(Max constraintAnnotation) { this.max = constraintAnnotation.value(); } public boolean isValid(Number object) { if(object == null) { return true; } return object.longValue() <= max; } } /** * Constructs a 'max' validator. */ public static Validator<Number> max(long value) { return new MaxValidator(value); } // --- MinLength /** * Defines a minumum length for a string field. */ @Target({FIELD}) @Retention(RUNTIME) @Constraint(validatedBy = MinLengthValidator.class) @play.data.Form.Display(name="constraint.minLength", attributes={"value"}) public static @interface MinLength { String message() default MinLengthValidator.message; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; long value(); } /** * Validator for <code>@MinLength</code> fields. */ public static class MinLengthValidator extends Validator<String> implements ConstraintValidator<MinLength, String> { final static public String message = "error.minLength"; private long min; public MinLengthValidator() {} public MinLengthValidator(long value) { this.min = value; } public void initialize(MinLength constraintAnnotation) { this.min = constraintAnnotation.value(); } public boolean isValid(String object) { if(object == null || object.length() == 0) { return true; } return object.length() >= min; } } /** * Constructs a 'minLength' validator. */ public static Validator<String> minLength(long value) { return new MinLengthValidator(value); } // --- MaxLength /** * Defines a maxmimum length for a string field. */ @Target({FIELD}) @Retention(RUNTIME) @Constraint(validatedBy = MaxLengthValidator.class) @play.data.Form.Display(name="constraint.maxLength", attributes={"value"}) public static @interface MaxLength { String message() default MaxLengthValidator.message; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; long value(); } /** * Validator for <code>@MaxLength</code> fields. */ public static class MaxLengthValidator extends Validator<String> implements ConstraintValidator<MaxLength, String> { final static public String message = "error.maxLength"; private long max; public MaxLengthValidator() {} public MaxLengthValidator(long value) { this.max = value; } public void initialize(MaxLength constraintAnnotation) { this.max = constraintAnnotation.value(); } public boolean isValid(String object) { if(object == null || object.length() == 0) { return true; } return object.length() <= max; } } /** * Constructs a 'maxLength' validator. */ public static Validator<String> maxLength(long value) { return new MaxLengthValidator(value); } // --- Email /** * Defines a email constraint for a string field. */ @Target({FIELD}) @Retention(RUNTIME) @Constraint(validatedBy = EmailValidator.class) @play.data.Form.Display(name="constraint.email", attributes={}) public static @interface Email { String message() default EmailValidator.message; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; } /** * Validator for <code>@Email</code> fields. */ public static class EmailValidator extends Validator<String> implements ConstraintValidator<Email, String> { final static public String message = "error.email"; final static java.util.regex.Pattern regex = java.util.regex.Pattern.compile("\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}\\b"); public EmailValidator() {} public void initialize(Email constraintAnnotation) { } public boolean isValid(String object) { if(object == null || object.length() == 0) { return true; } return regex.matcher(object).matches(); } } /** * Constructs a 'email' validator. */ public static Validator<String> email() { return new EmailValidator(); } // --- Pattern /** * Defines a pattern constraint for a string field. */ @Target({FIELD}) @Retention(RUNTIME) @Constraint(validatedBy = PatternValidator.class) @play.data.Form.Display(name="constraint.pattern", attributes={}) public static @interface Pattern { String message() default EmailValidator.message; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; String value(); } /** * Validator for <code>@Pattern</code> fields. */ public static class PatternValidator extends Validator<String> implements ConstraintValidator<Pattern, String> { final static public String message = "error.pattern"; java.util.regex.Pattern regex = null; public PatternValidator() {} public PatternValidator(String regex) { this.regex = java.util.regex.Pattern.compile(regex); } public void initialize(Pattern constraintAnnotation) { regex = java.util.regex.Pattern.compile(constraintAnnotation.value()); } public boolean isValid(String object) { if(object == null || object.length() == 0) { return true; } return regex.matcher(object).matches(); } } /** * Constructs a 'pattern' validator. */ public static Validator<String> pattern(String regex) { return new PatternValidator(regex); } }
package listener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.FloatControl; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.JOptionPane; import control.PlayerController; import database.Database; import util.FileManager; import view.LoginWindow; import view.MenuWindow; import view.RegisterWindow; import view.SnakeFrame; public class MenuListener implements ActionListener{ private MenuWindow mw; private Database db; private PlayerController pc; private SnakeFrame sf; public boolean barrier = false; public int speed; File musicFile = null; AudioInputStream musicIn = null; Clip musicClip = null; public MenuListener(MenuWindow mw, Database db, PlayerController pc){ this.mw = mw; this.db = db; this.pc = pc; this.sf = new SnakeFrame(this.db, this.pc, this.mw, barrier, speed); } public void actionPerformed(ActionEvent e) { try { musicFile = new File("assets/button.wav"); musicIn = AudioSystem.getAudioInputStream(musicFile); musicClip = AudioSystem.getClip(); musicClip.open(musicIn); } catch (LineUnavailableException e1) { e1.printStackTrace(); } catch (UnsupportedAudioFileException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } if(e.getSource()== mw.btnBarrier){ musicClip.start(); this.barrier = true; this.sf = new SnakeFrame(this.db, this.pc, this.mw, barrier, this.speed); mw.btnBarrier.setEnabled(false); mw.btnNoBarrier.setEnabled(true); } if(e.getSource()== mw.btnNoBarrier){ musicClip.start(); this.barrier = false; this.sf = new SnakeFrame(this.db, this.pc, this.mw, barrier, this.speed); mw.btnNoBarrier.setEnabled(false); mw.btnBarrier.setEnabled(true); } if(e.getSource() == mw.btnPlay){ musicClip.start(); if(mw.loggedIn.getText().equals("")){ JOptionPane.showMessageDialog(null, "Please, register and login!"); }else{ mw.setVisible(false); this.sf = new SnakeFrame(this.db, this.pc, this.mw, this.mw.ml.barrier, this.speed); this.sf.setVisible(true); } } if(e.getSource() == mw.btnRegister){ musicClip.start(); new RegisterWindow(this.db); } if(e.getSource() == mw.btnLogin){ musicClip.start(); new LoginWindow(this.db, this.mw, this.pc); } if(e.getSource() == mw.btnHighscore){ musicClip.start(); String name = ""; for(int i=0; i<this.db.getPlayers().size(); i++){ if(this.db.getPlayers().get(i).getHighscore()==new FileManager().sortScore().get(0)) name = this.db.getPlayers().get(i).getName(); } JOptionPane.showMessageDialog(null, "The highscore is from:\n" + name + " - " + new FileManager().sortScore().get(0)); } if(e.getSource() == mw.btnExit){ musicClip.start(); this.mw.dispose(); } if(e.getSource() == mw.snakeColor){ musicClip.start(); for(int i=0; i<this.db.getPlayers().size(); i++){ if(pc.player.getName().equals(this.db.getPlayers().get(i).getName())) this.db.getPlayers().get(i).setSnakeColor(this.mw.snakeColor.getSelectedIndex()); } } if(e.getSource() == mw.btnEasy){ musicClip.start(); this.mw.btnEasy.setEnabled(false); this.mw.btnMedium.setEnabled(true); this.mw.btnHard.setEnabled(true); this.speed = 0; } if(e.getSource() == mw.btnMedium){ musicClip.start(); this.mw.btnEasy.setEnabled(true); this.mw.btnMedium.setEnabled(false); this.mw.btnHard.setEnabled(true); this.speed = 1; } if(e.getSource() == mw.btnHard){ musicClip.start(); this.mw.btnEasy.setEnabled(true); this.mw.btnMedium.setEnabled(true); this.mw.btnHard.setEnabled(false); this.speed = 2; } } }
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2014-2017 Marc de Verdelhan, 2017-2018 Ta4j Organization * & respective authors (see AUTHORS) * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *******************************************************************************/ package org.ta4j.core.analysis.criteria; import org.ta4j.core.TimeSeries; import org.ta4j.core.Trade; import org.ta4j.core.TradingRecord; import org.ta4j.core.num.Num; /** * Buy and hold criterion. * </p> * @see <a href="http://en.wikipedia.org/wiki/Buy_and_hold">http://en.wikipedia.org/wiki/Buy_and_hold</a> */ public class BuyAndHoldCriterion extends AbstractAnalysisCriterion { @Override public Num calculate(TimeSeries series, TradingRecord tradingRecord) { return series.getBar(series.getEndIndex()).getClosePrice().dividedBy(series.getBar(series.getBeginIndex()).getClosePrice()); } @Override public Num calculate(TimeSeries series, Trade trade) { int entryIndex = trade.getEntry().getIndex(); int exitIndex = trade.getExit().getIndex(); if (trade.getEntry().isBuy()) { return series.getBar(exitIndex).getClosePrice().dividedBy(series.getBar(entryIndex).getClosePrice()); } else { return series.getBar(entryIndex).getClosePrice().dividedBy(series.getBar(exitIndex).getClosePrice()); } } @Override public boolean betterThan(Num criterionValue1, Num criterionValue2) { return criterionValue1.isGreaterThan(criterionValue2); } }
package com.scoreboard.app.comment.repository; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.annotations.GenericGenerator; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import java.time.ZonedDateTime; @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Builder @EqualsAndHashCode @Entity @Table(name = "COMMENTS") public class Comment { public static final int MAXIMUM_TEXT_LENGTH = 500; @Id @GeneratedValue(generator = "UUID") @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator") private String id; @Column(name = "TEXT", length = MAXIMUM_TEXT_LENGTH) private String text; @Column(name = "MODIFIED_DATE") private ZonedDateTime modifiedDate; @Column(name = "GAME_ID") private Long gameId; }
/* * JBoss, Home of Professional Open Source * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual 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.redhat.virtualsummit.hackathon.rest; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; /** * A class extending {@link Application} and annotated with @ApplicationPath is the Java EE 6 "no XML" approach to activating * JAX-RS. * * <p> * Resources are served relative to the servlet path specified in the {@link ApplicationPath} annotation. * </p> */ @ApplicationPath("/ ") public class JaxRsActivator extends Application { /* class body intentionally left blank */ }
package headfirst.factory.pizzas; /** * Created by Gavin on 2017/3/9. */ public class ClamPizza extends Pizza { public ClamPizza() { name = "Clam Pizza"; dough = "Thin crust"; sauce = "White garlic sauce"; toppings.add("Clams"); toppings.add("Grated parmesan cheese"); } }
/** * 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.oozie.util.db; import java.util.Date; import org.apache.oozie.ErrorCode; import org.apache.oozie.SLAEventBean; import org.apache.oozie.client.SLAEvent.SlaAppType; import org.apache.oozie.client.SLAEvent.Status; import org.apache.oozie.command.CommandException; import org.apache.oozie.executor.jpa.SLAEventInsertJPAExecutor; import org.apache.oozie.service.JPAService; import org.apache.oozie.service.Services; import org.apache.oozie.service.StoreService; import org.apache.oozie.store.SLAStore; import org.apache.oozie.store.Store; import org.apache.oozie.util.DateUtils; import org.apache.oozie.util.XLog; import org.jdom.Element; public class SLADbOperations { public static final String CLIENT_ID_TAG = "oozie:sla:client-id"; public static void writeSlaRegistrationEvent(Element eSla, Store store, String slaId, SlaAppType appType, String user, String groupName) throws Exception { // System.out.println("BBBBB SLA added"); if (eSla == null) { return; } // System.out.println("Writing REG AAAAA " + slaId); SLAEventBean sla = new SLAEventBean(); // sla.setClientId(getTagElement( eSla, "client-id")); // sla.setClientId(getClientId()); sla.setAppName(getTagElement(eSla, "app-name")); sla.setParentClientId(getTagElement(eSla, "parent-child-id")); sla.setParentSlaId(getTagElement(eSla, "parent-sla-id")); String strNominalTime = getTagElement(eSla, "nominal-time"); // System.out.println("AAAAA SLA nominal time "+ strNominalTime); if (strNominalTime == null || strNominalTime.length() == 0) { throw new RuntimeException("Nominal time is required"); // TODO: // change to // CommandException } Date nominalTime = DateUtils.parseDateUTC(strNominalTime); // Setting expected start time String strRelExpectedStart = getTagElement(eSla, "should-start"); if (strRelExpectedStart == null || strRelExpectedStart.length() == 0) { throw new RuntimeException("should-start can't be empty"); } int relExpectedStart = Integer.parseInt(strRelExpectedStart); if (relExpectedStart < 0) { sla.setExpectedStart(null); } else { Date expectedStart = new Date(nominalTime.getTime() + relExpectedStart * 60 * 1000); sla.setExpectedStart(expectedStart); // sla.setExpectedStart(nominalTime); } // Setting expected end time String strRelExpectedEnd = getTagElement(eSla, "should-end"); if (strRelExpectedEnd == null || strRelExpectedEnd.length() == 0) { throw new RuntimeException("should-end can't be empty"); } int relExpectedEnd = Integer.parseInt(strRelExpectedEnd); if (relExpectedEnd < 0) { sla.setExpectedEnd(null); } else { Date expectedEnd = new Date(nominalTime.getTime() + relExpectedEnd * 60 * 1000); sla.setExpectedEnd(expectedEnd); } sla.setNotificationMsg(getTagElement(eSla, "notification-msg")); sla.setAlertContact(getTagElement(eSla, "alert-contact")); sla.setDevContact(getTagElement(eSla, "dev-contact")); sla.setQaContact(getTagElement(eSla, "qa-contact")); sla.setSeContact(getTagElement(eSla, "se-contact")); sla.setAlertFrequency(getTagElement(eSla, "alert-frequency")); sla.setAlertPercentage(getTagElement(eSla, "alert-percentage")); sla.setUpstreamApps(getTagElement(eSla, "upstream-apps")); // Oozie defined sla.setSlaId(slaId); sla.setAppType(appType); sla.setUser(user); sla.setGroupName(groupName); sla.setJobStatus(Status.CREATED); sla.setStatusTimestamp(new Date()); SLAStore slaStore = (SLAStore) Services.get().get(StoreService.class).getStore(SLAStore.class, store); slaStore.insertSLAEvent(sla); } public static void writeSlaRegistrationEvent(Element eSla, String slaId, SlaAppType appType, String user, String groupName, XLog log) throws Exception { // System.out.println("BBBBB SLA added"); if (eSla == null) { return; } //System.out.println("Writing REG AAAAA " + slaId); SLAEventBean sla = new SLAEventBean(); // sla.setClientId(getTagElement( eSla, "client-id")); // sla.setClientId(getClientId()); sla.setAppName(getTagElement(eSla, "app-name")); sla.setParentClientId(getTagElement(eSla, "parent-child-id")); sla.setParentSlaId(getTagElement(eSla, "parent-sla-id")); String strNominalTime = getTagElement(eSla, "nominal-time"); // System.out.println("AAAAA SLA nominal time "+ strNominalTime); if (strNominalTime == null || strNominalTime.length() == 0) { throw new RuntimeException("Nominal time is required"); // TODO: // change to // CommandException } Date nominalTime = DateUtils.parseDateUTC(strNominalTime); // Setting expected start time String strRelExpectedStart = getTagElement(eSla, "should-start"); if (strRelExpectedStart == null || strRelExpectedStart.length() == 0) { throw new RuntimeException("should-start can't be empty"); } int relExpectedStart = Integer.parseInt(strRelExpectedStart); if (relExpectedStart < 0) { sla.setExpectedStart(null); } else { Date expectedStart = new Date(nominalTime.getTime() + relExpectedStart * 60 * 1000); sla.setExpectedStart(expectedStart); // sla.setExpectedStart(nominalTime); } // Setting expected end time String strRelExpectedEnd = getTagElement(eSla, "should-end"); if (strRelExpectedEnd == null || strRelExpectedEnd.length() == 0) { throw new RuntimeException("should-end can't be empty"); } int relExpectedEnd = Integer.parseInt(strRelExpectedEnd); if (relExpectedEnd < 0) { sla.setExpectedEnd(null); } else { Date expectedEnd = new Date(nominalTime.getTime() + relExpectedEnd * 60 * 1000); sla.setExpectedEnd(expectedEnd); } sla.setNotificationMsg(getTagElement(eSla, "notification-msg")); sla.setAlertContact(getTagElement(eSla, "alert-contact")); sla.setDevContact(getTagElement(eSla, "dev-contact")); sla.setQaContact(getTagElement(eSla, "qa-contact")); sla.setSeContact(getTagElement(eSla, "se-contact")); sla.setAlertFrequency(getTagElement(eSla, "alert-frequency")); sla.setAlertPercentage(getTagElement(eSla, "alert-percentage")); sla.setUpstreamApps(getTagElement(eSla, "upstream-apps")); // Oozie defined sla.setSlaId(slaId); sla.setAppType(appType); sla.setUser(user); sla.setGroupName(groupName); sla.setJobStatus(Status.CREATED); sla.setStatusTimestamp(new Date()); //SLAStore slaStore = (SLAStore) Services.get().get(StoreService.class) // .getStore(SLAStore.class, store); //slaStore.insertSLAEvent(sla); JPAService jpaService = Services.get().get(JPAService.class); if (jpaService != null) { jpaService.execute(new SLAEventInsertJPAExecutor(sla)); } else { log.error(ErrorCode.E0610); } } public static void writeSlaStatusEvent(String id, Status status, Store store, SlaAppType appType) throws Exception { SLAEventBean sla = new SLAEventBean(); sla.setSlaId(id); sla.setJobStatus(status); sla.setAppType(appType); sla.setStatusTimestamp(new Date()); //System.out.println("Writing STATUS AAAAA " + id); SLAStore slaStore = (SLAStore) Services.get().get(StoreService.class) .getStore(SLAStore.class, store); slaStore.insertSLAEvent(sla); } public static void writeSlaStatusEvent(String id, Status status, SlaAppType appType, XLog log) throws Exception { SLAEventBean sla = new SLAEventBean(); sla.setSlaId(id); sla.setJobStatus(status); sla.setAppType(appType); sla.setStatusTimestamp(new Date()); // System.out.println("Writing STATUS AAAAA " + id); //SLAStore slaStore = (SLAStore) Services.get().get(StoreService.class).getStore(SLAStore.class, store); //slaStore.insertSLAEvent(sla); JPAService jpaService = Services.get().get(JPAService.class); if (jpaService != null) { jpaService.execute(new SLAEventInsertJPAExecutor(sla)); } else { log.error(ErrorCode.E0610); } } public static void writeStausEvent(String slaXml, String id, Store store, Status stat, SlaAppType appType) throws CommandException { if (slaXml == null || slaXml.length() == 0) { return; } try { writeSlaStatusEvent(id, stat, store, appType); } catch (Exception e) { throw new CommandException(ErrorCode.E1007, " id " + id, e); } } public static void writeStausEvent(String slaXml, String id, Status stat, SlaAppType appType, XLog log) throws CommandException { if (slaXml == null || slaXml.length() == 0) { return; } try { writeSlaStatusEvent(id, stat, appType, log); } catch (Exception e) { throw new CommandException(ErrorCode.E1007, " id " + id, e); } } public static String getClientId() { Services services = Services.get(); if (services == null) { throw new RuntimeException("Services is not initialized"); } String clientId = services.getConf().get(CLIENT_ID_TAG, "oozie-default-instance"); // TODO" remove default if (clientId == null) { //System.out.println("CONF " // + XmlUtils.prettyPrint(services.getConf())); throw new RuntimeException( "No SLA_CLIENT_ID defined in oozie-site.xml with property name " + CLIENT_ID_TAG); } return clientId; } private static String getTagElement(Element elem, String tagName) { if (elem != null && elem.getChild(tagName, elem.getNamespace("sla")) != null) { return elem.getChild(tagName, elem.getNamespace("sla")).getText() .trim(); } else { return null; } } }
package com.sunzn.cube.sample; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.sunzn.cube.sample", appContext.getPackageName()); } }
package org.fintx.httpagent; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; @WebServlet(displayName = "AdminServlet" , //描述 name = "AdminServlet", //servlet名称 urlPatterns = { "/admin","/admin" }, //url loadOnStartup = 1, //启动项 initParams = { @WebInitParam(name = "username", value = "张三") } ) public class AdminServlet extends HttpServlet { /** * */ private static final long serialVersionUID = -8762294920980583988L; }
package eu.bcvsolutions.idm.core.monitoring.service.impl; import java.util.List; import java.util.UUID; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import eu.bcvsolutions.idm.core.api.service.AbstractEventableDtoService; import eu.bcvsolutions.idm.core.api.service.EntityEventManager; import eu.bcvsolutions.idm.core.monitoring.api.domain.MonitoringGroupPermission; import eu.bcvsolutions.idm.core.monitoring.api.dto.IdmMonitoringResultDto; import eu.bcvsolutions.idm.core.monitoring.api.dto.filter.IdmMonitoringResultFilter; import eu.bcvsolutions.idm.core.monitoring.api.service.IdmMonitoringResultService; import eu.bcvsolutions.idm.core.monitoring.entity.IdmMonitoringResult; import eu.bcvsolutions.idm.core.monitoring.entity.IdmMonitoringResult_; import eu.bcvsolutions.idm.core.monitoring.entity.IdmMonitoring_; import eu.bcvsolutions.idm.core.monitoring.repository.IdmMonitoringResultRepository; import eu.bcvsolutions.idm.core.notification.api.domain.NotificationLevel; import eu.bcvsolutions.idm.core.security.api.dto.AuthorizableType; /** * CRUD for monitoring results. * * @author Radek Tomiška * @since 11.1.0 */ @Service("monitoringResultService") public class DefaultIdmMonitoringResultService extends AbstractEventableDtoService<IdmMonitoringResultDto, IdmMonitoringResult, IdmMonitoringResultFilter> implements IdmMonitoringResultService { private final IdmMonitoringResultRepository repository; @Autowired public DefaultIdmMonitoringResultService( IdmMonitoringResultRepository repository, EntityEventManager entityEventManager) { super(repository, entityEventManager); // this.repository = repository; } @Override public AuthorizableType getAuthorizableType() { return new AuthorizableType(MonitoringGroupPermission.MONITORINGRESULT, getEntityClass()); } @Override @Transactional public int resetLastResult(UUID monitoringId) { return repository.resetLastResult(monitoringId, false); } @Override protected List<Predicate> toPredicates(Root<IdmMonitoringResult> root, CriteriaQuery<?> query, CriteriaBuilder builder, IdmMonitoringResultFilter filter) { List<Predicate> predicates = super.toPredicates(root, query, builder, filter); // // "fulltext" String text = filter.getText(); if (StringUtils.isNotEmpty(text)) { text = text.toLowerCase(); predicates.add(builder.or( builder.like(builder.lower(root.get(IdmMonitoringResult_.monitoring).get(IdmMonitoring_.code)), "%" + text + "%"), builder.like(builder.lower(root.get(IdmMonitoringResult_.monitoring).get(IdmMonitoring_.evaluatorType)), "%" + text + "%"), builder.like(builder.lower(root.get(IdmMonitoringResult_.monitoring).get(IdmMonitoring_.description)), "%" + text + "%") )); } // UUID monitoring = filter.getMonitoring(); if (monitoring != null) { predicates.add(builder.equal(root.get(IdmMonitoringResult_.monitoring).get(IdmMonitoring_.id), monitoring)); } List<NotificationLevel> levels = filter.getLevels(); if (CollectionUtils.isNotEmpty(levels)) { predicates.add(root.get(IdmMonitoringResult_.level).in(levels)); } // if (filter.isLastResult()) { predicates.add(builder.isTrue(root.get(IdmMonitoringResult_.lastResult))); } // return predicates; } }
package com.u_call_34010; import android.app.Application; import android.content.Context; import com.facebook.react.PackageList; import com.facebook.react.ReactApplication; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.soloader.SoLoader; import java.lang.reflect.InvocationTargetException; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { @SuppressWarnings("UnnecessaryLocalVariable") List<ReactPackage> packages = new PackageList(this).getPackages(); // Packages that cannot be autolinked yet can be added manually here, for example: // packages.add(new MyReactNativePackage()); return packages; } @Override protected String getJSMainModuleName() { return "index"; } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); } /** * Loads Flipper in React Native templates. Call this in the onCreate method with something like * initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); * * @param context * @param reactInstanceManager */ private static void initializeFlipper( Context context, ReactInstanceManager reactInstanceManager) { if (BuildConfig.DEBUG) { try { /* We use reflection here to pick up the class that initializes Flipper, since Flipper library is not available in release mode */ Class<?> aClass = Class.forName("com.u_call_34010.ReactNativeFlipper"); aClass .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class) .invoke(null, context, reactInstanceManager); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } }
package lib.tarek.quiz; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumentation test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("lib.tarek.quiz", appContext.getPackageName()); } }
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2005, 2006, 2007, 2008 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-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.sakaiproject.user.tool; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.faces.event.ValueChangeEvent; import javax.faces.model.SelectItem; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.entity.api.ResourcePropertiesEdit; import org.sakaiproject.event.cover.NotificationService; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.portal.util.PortalUtils; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SiteService.SelectionType; import org.sakaiproject.site.api.SiteService.SortType; import org.sakaiproject.site.cover.SiteService; import org.sakaiproject.time.cover.TimeService; import org.sakaiproject.tool.api.SessionManager; import org.sakaiproject.user.api.Preferences; import org.sakaiproject.user.api.PreferencesEdit; import org.sakaiproject.user.api.PreferencesService; import org.sakaiproject.user.api.UserNotificationPreferencesRegistration; import org.sakaiproject.user.api.UserNotificationPreferencesRegistrationService; import org.sakaiproject.user.cover.UserDirectoryService; import org.sakaiproject.util.ResourceLoader; import org.sakaiproject.util.api.FormattedText; /** * UserPrefsTool is the Sakai end-user tool to view and edit one's preferences. */ @Slf4j @Getter @Setter public class UserPrefsTool { /** * Resource bundle messages */ private static final ResourceLoader msgs = new ResourceLoader("user-tool-prefs"); /** The string to get whether privacy status should be visible */ private static final String ENABLE_PRIVACY_STATUS = "enable.privacy.status"; /** Should research/collab specific preferences (no syllabus) be displayed */ private static final String PREFS_RESEARCH = "prefs.research.collab"; public static final String PREFS_EXPAND = "prefs.expand"; private static final String PREFS_EXPAND_TRUE = "1"; private static final String PREFS_EXPAND_FALSE = "0"; /** * Represents a name value pair in a keyed preferences set. */ @Getter @Setter public class KeyNameValue { /** Is this value a list?. */ protected boolean isList = false; /** The key. */ protected String key = null; /** The name. */ protected String name = null; /** The original is this value a list?. */ protected boolean origIsList = false; /** The original key. */ protected String origKey = null; /** The original name. */ protected String origName = null; /** The original value. */ protected String origValue = null; /** The value. */ protected String value = null; public KeyNameValue(String key, String name, String value, boolean isList) { this.key = key; this.origKey = key; this.name = name; this.origName = name; this.value = value; this.origValue = value; this.isList = isList; this.origIsList = isList; } public boolean isChanged() { return ((!name.equals(origName)) || (!value.equals(origValue)) || (!key.equals(origKey)) || (isList != origIsList)); } } /** The PreferencesEdit being worked on. */ protected PreferencesEdit m_edit = null; /** Preferences service (injected dependency) */ protected PreferencesService preferencesService = null; protected UserNotificationPreferencesRegistrationService userNotificationPreferencesRegistrationService = null; /** Session manager (injected dependency) */ protected SessionManager sessionManager = null; /** The PreferencesEdit in KeyNameValue collection form. */ protected Collection m_stuff = null; // /** The user id (from the end user) to edit. */ // protected String m_userId = null; /** For display and selection of Items in JSF-- edit.jsp */ private List prefExcludeItems = new ArrayList(); private List prefOrderItems = new ArrayList(); private List<SelectItem> prefTimeZones = new ArrayList<>(); private List<SelectItem> prefLocales = new ArrayList<SelectItem>(); // SAK-23895 private String prefTabLabel = null; private int DEFAULT_TAB_LABEL = 1; private String[] selectedExcludeItems; private String[] selectedOrderItems; private String prefTabString = null; private String prefHiddenString = null; private String[] tablist; private int noti_selection, tab_selection, timezone_selection, language_selection, privacy_selection, hidden_selection, editor_selection, theme_selection, j; private String hiddenSitesInput = null; //The preference list names private String Notification="prefs_noti_title"; private String Timezone="prefs_timezone_title"; private String Language="prefs_lang_title"; private String Privacy="prefs_privacy_title"; private String Hidden="prefs_hidden_title"; private String Editor="prefs_editor_title"; private String Theme="prefs_theme_title"; private boolean refreshMode=false; protected final static String EXCLUDE_SITE_LISTS = "exclude"; protected final static String ORDER_SITE_LISTS = "order"; protected final static String TAB_LABEL_PREF = "tab:label"; protected final static String EDITOR_TYPE = "editor:type"; protected final static String THEME_PREF = "sakai:portal:theme"; protected boolean isNewUser = false; // user's currently selected time zone private TimeZone m_timeZone = null; // user's currently selected editor type private String m_editorType = null; // user's currently selected regional language locale private Locale m_locale = null; // user's currently selected Sakai theme private String m_theme = null; /** The user id retrieved from UsageSessionService */ private String userId = ""; private String m_TabOutcome = "tab"; private Map<String, Integer> m_sortedTypes = new HashMap<>(); private List<DecoratedNotificationPreference> registereddNotificationItems = new ArrayList<>(); private List<Site> m_sites = new ArrayList<>(); // SAK-23895 private boolean prefShowTabLabelOption = true; // SAK-45006: only show Themes preference page if themes are enabled private boolean prefShowThemePreferences = false; // //////////////////////////////// PROPERTY GETTER AND SETTER //////////////////////////////////////////// public boolean isPrefShowTabLabelOption() { return prefShowTabLabelOption; } public boolean isPrefShowThemePreferences() { return prefShowThemePreferences; } /** * @return Returns the prefHiddenItems. */ public List getPrefHiddenItems() { return prefExcludeItems; } public String getPrefTabString() { return ""; } public void setPrefTabString(String inp) { inp = inp.trim(); prefTabString = inp; if ( inp.length() < 1 ) prefTabString = null; return; } public String getPrefHiddenString() { return ""; } public void setPrefHiddenString(String inp) { inp = inp.trim(); prefHiddenString = inp; if ( inp.length() < 1 ) prefHiddenString = null; return; } /** * @return Returns the prefTimeZones. */ public List<SelectItem> getPrefTimeZones() { if (prefTimeZones.size() == 0) { String[] timeZoneArray = TimeZone.getAvailableIDs(); Arrays.sort(timeZoneArray); for (int i = 0; i < timeZoneArray.length; i++) { String tzt = timeZoneArray[i]; if (StringUtils.contains(tzt, '/') && !StringUtils.startsWith(tzt, "SystemV") && !StringUtils.startsWith(tzt, "Etc/GMT")) { String id = tzt; String name = tzt; if (StringUtils.contains(tzt, '_')) { name = StringUtils.replace(tzt, "_", " "); } prefTimeZones.add(new SelectItem(id, name)); } } } return prefTimeZones; } /** * @return Returns the prefLocales */ public List<SelectItem> getPrefLocales() { // Initialize list of supported locales, if necessary if (prefLocales.isEmpty()) { org.sakaiproject.component.api.ServerConfigurationService scs = (org.sakaiproject.component.api.ServerConfigurationService) ComponentManager.get(org.sakaiproject.component.api.ServerConfigurationService.class); Locale[] localeArray = scs.getSakaiLocales(); for (int i = 0; i < localeArray.length; i++) { if (i == 0 || !localeArray[i].equals(localeArray[i - 1])) { prefLocales.add(new SelectItem(localeArray[i].toString(), msgs.getLocaleDisplayName(localeArray[i]))); } } } return prefLocales; } /** * @return Returns the user's selected TimeZone ID */ public String getSelectedTimeZone() { if (m_timeZone != null) return m_timeZone.getID(); Preferences prefs = (PreferencesEdit) preferencesService.getPreferences(getUserId()); ResourceProperties props = prefs.getProperties(TimeService.APPLICATION_ID); String timeZone = props.getProperty(TimeService.TIMEZONE_KEY); if (hasValue(timeZone)) m_timeZone = TimeZone.getTimeZone(timeZone); else m_timeZone = TimeZone.getDefault(); return m_timeZone.getID(); } /** * @return Returns the user's selected Editor Type */ public String getSelectedEditorType() { if (m_editorType != null) return m_editorType; Preferences prefs = (PreferencesEdit) preferencesService.getPreferences(getUserId()); ResourceProperties props = prefs.getProperties(PreferencesService.EDITOR_PREFS_KEY); String editorType = props.getProperty(PreferencesService.EDITOR_PREFS_TYPE); if (hasValue(editorType)) m_editorType = editorType; else m_editorType = "auto"; return m_editorType; } /** * @return Returns the user's selected Sakai theme */ public String getSelectedTheme() { if (m_theme != null) { return m_theme; } Preferences prefs = (PreferencesEdit) preferencesService.getPreferences(getUserId()); String userTheme = StringUtils.defaultIfEmpty(prefs.getProperties(org.sakaiproject.user.api.PreferencesService.USER_SELECTED_UI_THEME_PREFS).getProperty("theme"), "sakaiUserTheme-notSet"); if (hasValue(userTheme)) { m_theme = userTheme; } else { m_theme = "sakaiUserTheme-notSet"; } return m_theme; } /** * @param selectedTimeZone * The selectedTimeZone to set. */ public void setSelectedTimeZone(String selectedTimeZone) { if (selectedTimeZone != null) m_timeZone = TimeZone.getTimeZone(selectedTimeZone); else log.warn(this + "setSelctedTimeZone() has null TimeZone"); } /** * @param selectedEditorType * The selectedTimeZone to set. */ public void setSelectedEditorType(String selectedEditorType) { if (selectedEditorType != null) m_editorType = selectedEditorType; else log.warn(this + "setSelectedEditorType() has null Editor"); } /** * @param selectedTheme * The selected theme to set. */ public void setSelectedTheme(String selectedTheme) { if (selectedTheme != null) { m_theme = selectedTheme; } else { log.warn(this + "setSelectedTheme() has null theme"); } } /** * @return Returns the user's selected Locale ID */ private Locale getSelectedLocale() { if (m_locale != null) return m_locale; Preferences prefs = (PreferencesEdit) preferencesService.getPreferences(getUserId()); ResourceProperties props = prefs.getProperties(ResourceLoader.APPLICATION_ID); String prefLocale = props.getProperty(ResourceLoader.LOCALE_KEY); if (hasValue(prefLocale)) { org.sakaiproject.component.api.ServerConfigurationService scs = (org.sakaiproject.component.api.ServerConfigurationService) ComponentManager.get(org.sakaiproject.component.api.ServerConfigurationService.class); m_locale = scs.getLocaleFromString(prefLocale); } else { m_locale = Locale.getDefault(); } return m_locale; } /** * @return Returns the user's selected Locale ID */ public String getSelectedLocaleName() { return getSelectedLocale().getDisplayName(); } /** * @return Returns the user's selected Locale ID */ public String getSelectedLocaleString() { return getSelectedLocale().toString(); } /** * @param selectedLocale * The selectedLocale to set. */ public void setSelectedLocaleString(String selectedLocale) { if (selectedLocale != null) { org.sakaiproject.component.api.ServerConfigurationService scs = (org.sakaiproject.component.api.ServerConfigurationService) ComponentManager.get(org.sakaiproject.component.api.ServerConfigurationService.class); m_locale = scs.getLocaleFromString(selectedLocale); } } /** * @return Returns the userId. */ public String getUserId() { return this.sessionManager.getCurrentSessionUserId(); } /** * Init some services that are needed. * Unfortunately they were needed when the constructor was called so * injecting wasn't soon enough. */ private void initServices() { if (userNotificationPreferencesRegistrationService == null) { userNotificationPreferencesRegistrationService = (UserNotificationPreferencesRegistrationService)ComponentManager.get("org.sakaiproject.user.api.UserNotificationPreferencesRegistrationService"); } if (preferencesService == null) { preferencesService = (PreferencesService)ComponentManager.get("org.sakaiproject.user.api.PreferencesService"); } if (sessionManager == null) { sessionManager = (SessionManager) ComponentManager.get("org.sakaiproject.tool.api.SessionManager"); } } // /////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////// /** * no-arg constructor. */ public UserPrefsTool() { // do we show the option to display by site title or short description? boolean show_tab_label_option = ServerConfigurationService.getBoolean("preference.show.tab.label.option", true); setPrefShowTabLabelOption(show_tab_label_option); setPrefShowThemePreferences(ServerConfigurationService.getBoolean("portal.themes", true)); //To indicate that it is in the refresh mode refreshMode=true; String tabOrder = ServerConfigurationService.getString("preference.pages", "prefs_noti_title, prefs_timezone_title, prefs_lang_title, prefs_hidden_title, prefs_hidden_title, prefs_editor_title,prefs_theme_title"); log.debug("Setting preference.pages as " + tabOrder); tablist=tabOrder.split(","); for(int i=0; i<tablist.length; i++) { tablist[i]=tablist[i].trim(); if(tablist[i].equals(Notification)) noti_selection=i+1; else if(tablist[i].equals(Timezone)) timezone_selection=i+1; else if (tablist[i].equals(Language)) language_selection=i+1; else if (tablist[i].equals(Privacy)) privacy_selection=i+1; else if (tablist[i].equals(Hidden)) hidden_selection=i+1; else if (tablist[i].equals(Editor)) editor_selection=i+1; else if (tablist[i].equals(Theme)) theme_selection=i+1; else log.warn(tablist[i] + " is not valid!!! Please fix preference.pages property in sakai.properties"); } initNotificationStructures(); log.debug("new UserPrefsTool()"); } /** * Init a bunch of stuff that we'll need for the notification preferences */ private void initNotificationStructures() { initServices(); //Get my sites m_sites = SiteService.getSites(SelectionType.ACCESS, null, null, null, SortType.TITLE_ASC, null); initRegisteredNotificationItems(); } public int getNoti_selection() { //Loading the data for notification in the refresh mode if (noti_selection==1 && refreshMode==true) { processActionNotiFrmEdit(); } return noti_selection; } public int getTimezone_selection() { //Loading the data for timezone in the refresh mode if (timezone_selection==1 && refreshMode==true) { processActionTZFrmEdit(); } return timezone_selection; } public int getLanguage_selection() { //Loading the data for language in the refresh mode if (language_selection==1 && refreshMode==true) { processActionLocFrmEdit(); } return language_selection; } public int getPrivacy_selection() { //Loading the data for notification in the refresh mode if (privacy_selection==1 && refreshMode==true) { processActionPrivFrmEdit(); } return privacy_selection; } public int getHidden_selection() { //Loading the data for notification in the refresh mode if (hidden_selection==1 && refreshMode==true) { processActionHiddenFrmEdit(); } return hidden_selection; } public int getEditor_selection() { //Loading the data for notification in the refresh mode if (editor_selection==1 && refreshMode==true) { processActionHiddenFrmEdit(); } return editor_selection; } public int getTheme_selection() { //Loading the data for notification in the refresh mode if (theme_selection==1 && refreshMode==true) { processActionHiddenFrmEdit(); } return theme_selection; } public String getTabTitle() { return "tabtitle"; } /** * SAK-29138 - Get the site or section title for the current user for the current site. * Takes into account 'portal.use.sectionTitle' sakai.property; if set to true, * this method will return the title of the section the current user is enrolled * in for the site (if it can be found). Otherwise, it will return the site * title (default behaviour) * * @param site the site in question * @param truncate whether or not to truncate the site title for display purposes * @return the site or section title */ public static String getUserSpecificSiteTitle( Site site, boolean truncate ) { FormattedText formattedText = ComponentManager.get(FormattedText.class); String retVal = SiteService.getUserSpecificSiteTitle( site, UserDirectoryService.getCurrentUser().getId() ); if (truncate) { return formattedText.escapeHtml( formattedText.makeShortenedText( retVal, null, null, null ) ); } else { return formattedText.escapeHtml( retVal ); } } /** * Process the cancel command from the edit view. * * @return navigation outcome to tab customization page (edit) */ public String processActionCancel() { log.debug("processActionCancel()"); prefTabLabel = null; // reset to retrieve original prefs // remove session variables cancelEdit(); // To stay on the same page - load the page data return m_TabOutcome; } /** * Process the cancel command from the edit view. * * @return navigation outcome to Notification page (list) */ public String processActionNotiFrmEdit() { log.debug("processActionNotiFrmEdit()"); refreshMode=false; cancelEdit(); // navigation page data are loaded through getter method as navigation is the default page for 'sakai.preferences' tool. return "noti"; } /** * Process the cancel command from the edit view. * * @return navigation outcome to timezone page (list) */ public String processActionTZFrmEdit() { log.debug("processActionTZFrmEdit()"); refreshMode=false; cancelEdit(); // navigation page data are loaded through getter method as navigation is the default page for 'sakai.preferences' tool. return "timezone"; } /** * Process the cancel command from the edit view. * * @return navigation outcome to editor page (list) */ public String processActionEditorFrmEdit() { log.debug("processActionEditorFrmEdit()"); refreshMode=false; cancelEdit(); // navigation page data are loaded through getter method as navigation is the default page for 'sakai.preferences' tool. return "editor"; } /** * Process the cancel command from the edit view. * * @return navigation outcome to locale page (list) */ public String processActionLocFrmEdit() { log.debug("processActionLocFrmEdit()"); refreshMode=false; cancelEdit(); // navigation page data are loaded through getter method as navigation is the default page for 'sakai.preferences' tool. return "locale"; } /** * Process the cancel command from the edit view of Theme. * * @return navigation outcome to editor page (list) */ public String processActionThemeFrmEdit() { log.debug("processActionThemeFrmEdit()"); refreshMode=false; cancelEdit(); // navigation page data are loaded through getter method as navigation is the default page for 'sakai.preferences' tool. return "theme"; } /** * Process the cancel command from the edit view. * * @return navigation outcome to locale page (list) */ public String processActionPrivFrmEdit() { log.debug("processActionPrivFrmEdit()"); cancelEdit(); // navigation page data are loaded through getter method as navigation is the default page for 'sakai.preferences' tool. return "privacy"; } public String processActionHiddenFrmEdit() { log.debug("processActionHiddenFrmEdit()"); cancelEdit(); // navigation page data are loaded through getter method as navigation is the default page for 'sakai.preferences' tool. return "hidden"; } /** * This is called from edit page for navigation to refresh page * * @return navigation outcome to refresh page (refresh) */ public String processActionRefreshFrmEdit() { log.debug("processActionRefreshFrmEdit()"); // is required as user editing is set on while entering to tab customization page cancelEdit(); loadRefreshData(); return "refresh"; } // //////////////////////////////////// HELPER METHODS TO ACTIONS //////////////////////////////////////////// /** * Cancel the edit and cleanup. */ protected void cancelEdit() { log.debug("cancelEdit()"); // cleanup m_stuff = null; m_edit = null; prefExcludeItems = new ArrayList(); prefOrderItems = new ArrayList(); isNewUser = false; notiUpdated = false; tzUpdated = false; locUpdated = false; refreshUpdated = false; hiddenUpdated = false; editorUpdated = false; themeUpdated = false; } /** * used with processActionAdd() and processActionRemove() * * @return SelectItem */ private SelectItem removeItems(String value, List items, String addtype, String removetype) { if (log.isDebugEnabled()) { log.debug("removeItems(String " + value + ", List " + items + ", String " + addtype + ", String " + removetype + ")"); } SelectItem result = null; for (int i = 0; i < items.size(); i++) { SelectItem item = (SelectItem) items.get(i); if (value.equals(item.getValue())) { result = (SelectItem) items.remove(i); break; } } return result; } /** * Set editing mode on for user and add user if not existing */ protected void setUserEditingOn() { log.debug("setUserEditingOn()"); try { m_edit = preferencesService.edit(getUserId()); } catch (IdUnusedException e) { try { m_edit = preferencesService.add(getUserId()); isNewUser = true; } catch (Exception ee) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(ee.toString())); } } catch (Exception e) { FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.toString())); } } /** * Save any changed values from the edit and cleanup. */ protected void saveEdit() { log.debug("saveEdit()"); // user editing is required as commit() disable isActive() flag setUserEditingOn(); // move the stuff from m_stuff into the edit if (m_stuff != null) { for (Iterator i = m_stuff.iterator(); i.hasNext();) { KeyNameValue knv = (KeyNameValue) i.next(); // find the original to remove (unless this one was new) if (!knv.getOrigKey().equals("")) { ResourcePropertiesEdit props = m_edit.getPropertiesEdit(knv.getOrigKey()); props.removeProperty(knv.getOrigName()); } // add the new if we have a key and name and value if ((!knv.getKey().equals("")) && (!knv.getName().equals("")) && (!knv.getValue().equals(""))) { ResourcePropertiesEdit props = m_edit.getPropertiesEdit(knv.getKey()); if (knv.isList()) { // split by ", " String[] parts = knv.getValue().split(", "); for (int p = 0; p < parts.length; p++) { props.addPropertyToList(knv.getName(), parts[p]); } } else { props.addProperty(knv.getName(), knv.getValue()); } } } } // save the preferences, release the edit preferencesService.commit(m_edit); } /** * Check String has value, not null * * @return boolean */ protected boolean hasValue(String eval) { if (log.isDebugEnabled()) { log.debug("hasValue(String " + eval + ")"); } if (eval != null && !eval.trim().equals("")) { return true; } else { return false; } } // Copied from CheronPortal.java /** * Find the site in the list that has this id - return the position. * * * @param value * The site id to find. * @param siteList * The list of Site objects. * @return The index position in siteList of the site with site id = value, or -1 if not found. */ protected int indexOf(String value, List siteList) { if (log.isDebugEnabled()) { log.debug("indexOf(String " + value + ", List " + siteList + ")"); } for (int i = 0; i < siteList.size(); i++) { Site site = (Site) siteList.get(i); if (site.getId().equals(value)) { return i; } } return -1; } // ////////////////////////////////// NOTIFICATION ACTIONS //////////////////////////////// private DecoratedNotificationPreference currentDecoratedNotificationPreference = null; @Getter @Setter protected boolean notiUpdated = false; @Getter @Setter protected boolean tzUpdated = false; @Getter @Setter protected boolean locUpdated = false; @Getter @Setter protected boolean hiddenUpdated = false; @Getter @Setter protected boolean editorUpdated = false; @Getter @Setter protected boolean themeUpdated = false; // ///////////////////////////////////////NOTIFICATION ACTION - copied from NotificationprefsAction.java//////// // TODO - clean up method call. These are basically copied from legacy legacy implementations. /** * Process the save command from the edit view. * * @return navigation outcome to notification page */ public String processActionNotiSave() { log.debug("processActionNotiSave()"); // get an edit setUserEditingOn(); if (m_edit != null) { List<DecoratedNotificationPreference> items = getRegisteredNotificationItems(); for(UserNotificationPreferencesRegistration upr : userNotificationPreferencesRegistrationService.getRegisteredItems()) { readTypePrefs(upr.getType(), upr.getPrefix(), m_edit, getSelectedNotificationItemByKey(upr.getType(), items)); DecoratedNotificationPreference dnp = getDecoItemByKey(upr.getType(), items); if (dnp != null) { readOverrideTypePrefs(upr.getType() + NotificationService.NOTI_OVERRIDE_EXTENSION, upr.getPrefix(), m_edit, dnp.getSiteOverrides()); } } // update the edit and release it preferencesService.commit(m_edit); } processRegisteredNotificationItems(); notiUpdated = true; return "noti"; } /** * process notification cancel * * @return navigation outcome to notification page */ public String processActionNotiCancel() { log.debug("processActionNotiCancel()"); initRegisteredNotificationItems(); return "noti"; } /** * Process the save command from the edit view. * * @return navigation outcome to timezone page */ public String processActionTzSave() { setUserEditingOn(); ResourcePropertiesEdit props = m_edit.getPropertiesEdit(TimeService.APPLICATION_ID); props.addProperty(TimeService.TIMEZONE_KEY, m_timeZone.getID()); preferencesService.commit(m_edit); TimeService.clearLocalTimeZone(getUserId()); // clear user's cached timezone tzUpdated = true; // set for display of text message return "timezone"; } /** * * Processes the save command from the edit vieprefShowEditorLabelOptionw * @return navigation outcome to editor page */ public String processActionEditorSave() { setUserEditingOn(); ResourcePropertiesEdit props = m_edit.getPropertiesEdit(PreferencesService.EDITOR_PREFS_KEY); props.addProperty(PreferencesService.EDITOR_PREFS_TYPE, m_editorType); preferencesService.commit(m_edit); editorUpdated = true; // set for display of text message return "editor"; } /** * process timezone cancel * * @return navigation outcome to timezone page */ public String processActionTzCancel() { log.debug("processActionTzCancel()"); // restore original time zone m_timeZone = null; getSelectedTimeZone(); return "timezone"; } /** * process editor cancel * * @return navigation outcome to editor page */ public String processActionEditorCancel() { log.debug("processActionEditorCancel()"); // restore original editor m_editorType = null; getSelectedEditorType(); return "editor"; } /** * Process the save command from the edit view. * * @return navigation outcome to locale page */ public String processActionLocSave() { setUserEditingOn(); ResourcePropertiesEdit props = m_edit.getPropertiesEdit(ResourceLoader.APPLICATION_ID); props.addProperty(ResourceLoader.LOCALE_KEY, m_locale.toString()); preferencesService.commit(m_edit); TimeService.clearLocalTimeZone(getUserId()); // clear user's cached timezone //Save the preference in the session also ResourceLoader rl = new ResourceLoader(); Locale loc = rl.setContextLocale(null); // reset notification items with the locale initRegisteredNotificationItems(); locUpdated = true; // set for display of text message return "locale"; } /** * process locale cancel * * @return navigation outcome to locale page */ public String processActionLocCancel() { log.debug("processActionLocCancel()"); // restore original locale m_locale = null; getSelectedLocale(); return "locale"; } /** * Process the save command from the theme view. * * @return navigation outcome to theme page */ public String processActionThemeSave() { setUserEditingOn(); ResourcePropertiesEdit props = m_edit.getPropertiesEdit(PreferencesService.USER_SELECTED_UI_THEME_PREFS); props.addProperty("theme", m_theme); preferencesService.commit(m_edit); themeUpdated = true; // set for display of text message return "theme"; } /** * process theme cancel * * @return navigation outcome to theme page */ public String processActionThemeCancel() { log.debug("processActionThemeCancel()"); // restore original theme m_theme = null; getSelectedTheme(); return "theme"; } /** * This is called from notification page for navigation to Refresh page * * @return navigation outcome to refresh page */ public String processActionRefreshFrmNoti() { log.debug("processActionRefreshFrmNoti()"); loadRefreshData(); return "refresh"; } // ////////////////////////////////////// HELPER METHODS FOR NOTIFICATIONS ///////////////////////////////////// /** * Read the two context references for defaults for this type from the form. * * @param type * The resource type (i.e. a service name). * @param prefix * The prefix for context references. * @param edit * The preferences being edited. * @param data * The rundata with the form fields. */ protected void readTypePrefs(String type, String prefix, PreferencesEdit edit, String data) { if (log.isDebugEnabled()) { log.debug("readTypePrefs(String " + type + ", String " + prefix + ", PreferencesEdit " + edit + ", String " + data + ")"); } // update the default settings from the form ResourcePropertiesEdit props = edit.getPropertiesEdit(NotificationService.PREFS_TYPE + type); // read the defaults props.addProperty(Integer.toString(NotificationService.NOTI_OPTIONAL), data); } // readTypePrefs /** * Read the two context references for defaults for this type from the form. * * @param type * The resource type (i.e. a service name). * @param prefix * The prefix for context references. * @param edit * The preferences being edited. * @param data * The rundata with the form fields. */ protected void readOverrideTypePrefs(String type, String prefix, PreferencesEdit edit, List<SiteOverrideBean> data) { if (log.isDebugEnabled()) { log.debug("readOverrideTypePrefs(String " + type + ", String " + prefix + ", PreferencesEdit " + edit + ", String " + data + ")"); } List<SiteOverrideBean> toDel = new ArrayList<>(); // update the default settings from the form ResourcePropertiesEdit props = edit.getPropertiesEdit(NotificationService.PREFS_TYPE + type); // read the defaults for (SiteOverrideBean sob : data) { if (!sob.remove) { props.addProperty(sob.getSiteId(), sob.getOption()); } else { props.removeProperty(sob.getSiteId()); toDel.add(sob); } } data.removeAll(toDel); } // readOverrideTypePrefs /** * Read the two context references for defaults for this type from the form. * * @param type * The resource type (i.e. a service name). * @param edit * The preferences being edited. * @param data * The rundata with the form fields. */ protected void readOverrideTypePrefs(String type, PreferencesEdit edit, List<SiteOverrideBean> data) { if (log.isDebugEnabled()) { log.debug("readOverrideTypePrefs(String " + type + ", PreferencesEdit " + edit + ", String " + data + ")"); } // update the default settings from the form ResourcePropertiesEdit props = edit.getPropertiesEdit(NotificationService.PREFS_TYPE + type); // read the defaults for (SiteOverrideBean sob : data) { props.addProperty(sob.getSiteId(), sob.getOption()); } } // readOverrideTypePrefs /** * delete the preferences for this type. * * @param type * The resource type (i.e. a service name). * @param prefix * The prefix for context references. * @param edit * The preferences being edited. * @param data * The rundata with the form fields. */ protected void deleteOverrideTypePrefs(String type, String prefix, PreferencesEdit edit, List<String> data) { if (log.isDebugEnabled()) { log.debug("deleteOverrideTypePrefs(String " + type + ", String " + prefix + ", PreferencesEdit " + edit + ", String " + data + ")"); } ResourcePropertiesEdit props = edit.getPropertiesEdit(NotificationService.PREFS_TYPE + type); // delete for (String siteId : data) { props.removeProperty(siteId); } } // deleteOverrideTypePrefs /** * Add the two context references for defaults for this type. * * @param type * The resource type (i.e. a service name). * @param prefix * The prefix for context references. * @param context * The context. * @param prefs * The full set of preferences. */ protected String buildTypePrefsContext(String type, String prefix, String context, Preferences prefs) { if (log.isDebugEnabled()) { log.debug("buildTypePrefsContext(String " + type + ", String " + prefix + ", String " + context + ", Preferences " + prefs + ")"); } ResourceProperties props = prefs.getProperties(NotificationService.PREFS_TYPE + type); String value = props.getProperty(new Integer(NotificationService.NOTI_OPTIONAL).toString()); return value; } /** * Add the two context references for defaults for this type. * * @param type * The resource type (i.e. a service name). * @param prefix * The prefix for context references. * @param context * The context. * @param prefs * The full set of preferences. */ protected List<SiteOverrideBean> buildOverrideTypePrefsContext(String type, String prefix, String context, Preferences prefs) { if (log.isDebugEnabled()) { log.debug("buildOverrideTypePrefsContext(String " + type + ", String " + prefix + ", String " + context + ", Preferences " + prefs + ")"); } ResourceProperties props = prefs.getProperties(NotificationService.PREFS_TYPE + type); List<SiteOverrideBean> result = new ArrayList<>(); for (Iterator<String> i = props.getPropertyNames(); i.hasNext();) { String propName = i.next(); SiteOverrideBean sob = new SiteOverrideBean(propName, props.getProperty(propName)); result.add(sob); } Collections.sort(result, new SiteOverrideBeanSorter()); return result; } // SAK-23895 private String selectedTabLabel = ""; private String getPrefTabLabel(){ if ( prefTabLabel != null ) return prefTabLabel; Preferences prefs = (PreferencesEdit) preferencesService.getPreferences(getUserId()); ResourceProperties props = prefs.getProperties(PreferencesService.SITENAV_PREFS_KEY); prefTabLabel = props.getProperty(TAB_LABEL_PREF); if ( prefTabLabel == null ) prefTabLabel = String.valueOf(DEFAULT_TAB_LABEL); return prefTabLabel; } /** * @return Returns the getSelectedTabLabel. */ public String getSelectedTabLabel() { this.selectedTabLabel= getPrefTabLabel(); return this.selectedTabLabel; } /** * @param label * The tab label to set. */ public void setSelectedTabLabel(String label) { this.prefTabLabel = label; this.selectedTabLabel = label; } // ////////////////////////////////////// REFRESH ////////////////////////////////////////// private String selectedRefreshItem = ""; protected boolean refreshUpdated = false; /** * @return Returns the selectedRefreshItem. */ public String getSelectedRefreshItem() { return selectedRefreshItem; } /** * @param selectedRefreshItem * The selectedRefreshItem to set. */ public void setSelectedRefreshItem(String selectedRefreshItem) { if (log.isDebugEnabled()) { log.debug("setSelectedRefreshItem(String " + selectedRefreshItem + ")"); } this.selectedRefreshItem = selectedRefreshItem; } /** * Process cancel and navigate to list page. * * @return navigation outcome to refresh page */ public String processActionRefreshCancel() { log.debug("processActionRefreshCancel()"); loadRefreshData(); return "refresh"; } /** * Process cancel and navigate to list page. * * @return navigation outcome to notification page */ public String processActionNotiFrmRefresh() { log.debug("processActionNotiFrmRefresh()"); return "noti"; //return "tab"; } // ///////////////////////////////////// HELPER METHODS FOR REFRESH ///////////////////////// /** * Load refresh data from stored information. This is called when navigated into this page for first time. */ protected void loadRefreshData() { log.debug("loadRefreshData()"); selectedRefreshItem = ""; refreshUpdated = false; if (!hasValue(selectedRefreshItem)) { Preferences prefs = (PreferencesEdit) preferencesService.getPreferences(getUserId()); // String a = getStringPref(PortalService.SERVICE_NAME, "refresh", prefs); // if (hasValue(a)) // { // setSelectedRefreshItem(a); // load from saved data // } // else // { // setSelectedRefreshItem("2"); // default setting // } } } /** * Set an integer preference. * * @param pres_base * The name of the group of properties (i.e. a service name) * @param type * The particular property * @param edit * An edit version of the full set of preferences for the current logged in user. * @param newval * The string to be the new preference. */ protected void setStringPref(String pref_base, String type, PreferencesEdit edit, String newval) { if (log.isDebugEnabled()) { log.debug("setStringPref(String " + pref_base + ", String " + type + ", PreferencesEdit " + edit + ", String " + newval + ")"); } ResourcePropertiesEdit props = edit.getPropertiesEdit(pref_base); props.addProperty(type, newval); } // setStringPref /** * Retrieve a preference * * @param pres_base * The name of the group of properties (i.e. a service name) * @param type * The particular property * @param prefs * The full set of preferences for the current logged in user. */ protected String getStringPref(String pref_base, String type, Preferences prefs) { if (log.isDebugEnabled()) { log.debug("getStringPref(String " + pref_base + ", String " + type + ", PreferencesEdit " + prefs + ")"); } ResourceProperties props = prefs.getProperties(pref_base); String a = props.getProperty(type); return a; } // getIntegerPref /** Should we reload the top window? */ protected Boolean m_reloadTop = Boolean.FALSE; /** * Get, and clear, the reload element */ public Boolean getReloadTop() { Boolean rv = m_reloadTop; m_reloadTop = Boolean.FALSE; return rv; } public void setReloadTop(Boolean val) { } /** * Pull whether privacy status should be enabled from sakai.properties */ public boolean isPrivacyEnabled() { //return ServerConfigurationService.getBoolean(ENABLE_PRIVACY_STATUS, false); if (getPrivacy_selection()==0){ return false; } else { return true; } } /** * Should research/collab specific preferences (no syllabus) be displayed? * */ public boolean isResearchCollab() { return ServerConfigurationService.getBoolean(PREFS_RESEARCH, false); } public List<DecoratedNotificationPreference> getRegisteredNotificationItems() { log.debug("getRegisteredNotificationItems()"); return registereddNotificationItems; } public void initRegisteredNotificationItems() { log.debug("initRegisteredNotificationItems()"); registereddNotificationItems.clear(); for (UserNotificationPreferencesRegistration upr : userNotificationPreferencesRegistrationService.getRegisteredItems()) { registereddNotificationItems.addAll(getRegisteredNotificationItems(upr)); } processRegisteredNotificationItems(); } /** * Convenience method to take a string array and put it in a map * The key is the value in the array and the data in the map is the position in the array * @param array * @return */ private Map<String, Integer> stringArrayToMap(String[] array) { Map<String, Integer> retMap = new HashMap<>(); Integer index = 0; if (array != null) { for (String key : array) { retMap.put(key, index); index++; } } return retMap; } /** * Convenience method to take a string (comma delimited list of values) and turn it in to a list. * @param toolIds * @return */ private List<String> stringToList(String toolIds) { if ((toolIds != null) && (toolIds.length() > 0)) { String[] items = toolIds.split(","); return Arrays.asList(items); } return new ArrayList<>(); } /** * Looks at the various hide and stealth properties to determine which tools should be displayed. * This method mostly taken from org.sakaiproject.tool.impl.ToolComponent.init() and modified a bit. * @return */ private String[] getHiddenTools() { // compute the tools to hide: these are the stealth tools plus the hidden tools, minus the visible ones Set<String> toHide = new HashSet(); String hiddenToolsPrefs = ServerConfigurationService.getString("prefs.tool.hidden"); String stealthTools = ServerConfigurationService.getString("stealthTools@org.sakaiproject.tool.api.ActiveToolManager"); String hiddenTools = ServerConfigurationService.getString("hiddenTools@org.sakaiproject.tool.api.ActiveToolManager"); String visibleTools = ServerConfigurationService.getString("visibleTools@org.sakaiproject.tool.api.ActiveToolManager"); if (stealthTools != null) { toHide.addAll(stringToList(stealthTools)); } if (hiddenTools!= null) { toHide.addAll(stringToList(hiddenTools)); } if (visibleTools != null) { toHide.removeAll(stringToList(visibleTools)); } if (hiddenToolsPrefs != null) { toHide.addAll(stringToList(hiddenToolsPrefs)); } return toHide.toArray(new String[]{}); } /** * Determine the sorting and if any should be hidden from view * @param decoItems */ private void processRegisteredNotificationItems() { Map<String, Integer> toolOrderMap = new HashMap<>(); String[] toolOrder = ServerConfigurationService.getStrings("prefs.tool.order"); //String hiddenTools = ServerConfigurationService.getString("prefs.tool.hidden"); String[] parsedHidden = getHiddenTools(); Map<String, Integer> hiddenToolMap = new HashMap<>(); toolOrderMap = stringArrayToMap(toolOrder); hiddenToolMap = stringArrayToMap(parsedHidden); Preferences prefs = preferencesService.getPreferences(getUserId()); for (DecoratedNotificationPreference dnp : registereddNotificationItems) { String toolId = dnp.getUserNotificationPreferencesRegistration().getToolId(); Integer sort = toolOrderMap.get(toolId); if (sort != null) dnp.setSortOrder(sort); if (hiddenToolMap.get(toolId) != null) { dnp.setHidden(true); } ResourceProperties expandProps = prefs.getProperties(PREFS_EXPAND); if (expandProps != null) { String expandProp = expandProps.getProperty(dnp.key); if (expandProp != null) { boolean overrideExpand = expandProp.equalsIgnoreCase(PREFS_EXPAND_TRUE) ? true : false; dnp.setExpandOverride(overrideExpand); } } } Collections.sort(registereddNotificationItems, new DecoratedNotificationPreferenceSorter()); } /** * Get the current preference settings for this registration item * @param upr * @return */ public List<DecoratedNotificationPreference> getRegisteredNotificationItems(UserNotificationPreferencesRegistration upr) { log.debug("getRegisteredNotificationItems(UserNotificationPreferencesRegistration)"); List<DecoratedNotificationPreference> selNotiItems = new ArrayList<>(); Preferences prefs = preferencesService.getPreferences(getUserId()); List<SiteOverrideBean> siteOverrides = new ArrayList<>(); if (upr.isOverrideBySite()) { siteOverrides = buildOverrideTypePrefsContext(upr.getType() + NotificationService.NOTI_OVERRIDE_EXTENSION, upr.getPrefix(), null, prefs); } DecoratedNotificationPreference dnp = new DecoratedNotificationPreference(upr, siteOverrides); String regItem = buildTypePrefsContext(upr.getType(), upr.getPrefix(), dnp.getSelectedOption(), prefs); if (hasValue(regItem)) { dnp.setSelectedOption(regItem); // load from saved data } else { dnp.setSelectedOption(upr.getDefaultValue()); // default setting } selNotiItems.add(dnp); return selNotiItems; } public List<String> getSelectedNotificationItemIds(DecoratedNotificationPreference dnp) { log.debug("getSelectedNotificationItemIds(DecoratedNotificationPreference)"); List<String> result = new ArrayList<>(); for (SiteOverrideBean sob : dnp.getSiteOverrides()) { result.add(sob.siteId); } return result; } public void setCurrentDecoratedNotificationPreference( DecoratedNotificationPreference currentDecoratedNotificationPreference) { this.currentDecoratedNotificationPreference = currentDecoratedNotificationPreference; } public DecoratedNotificationPreference getCurrentDecoratedNotificationPreference() { return currentDecoratedNotificationPreference; } private DecoratedNotificationPreference getDecoItemByKey(String key, List<DecoratedNotificationPreference> decoPreferences) { log.debug("getDecoItemByKey(" + key + ")"); for (DecoratedNotificationPreference dnp : decoPreferences) { if (dnp.getKey().equalsIgnoreCase(key)) { return dnp; } } return null; } private String getSelectedNotificationItemByKey(String key, List<DecoratedNotificationPreference> decoPreferences) { log.debug("getSelectedNotificationItemByKey(" + key + ")"); DecoratedNotificationPreference dnp = getDecoItemByKey(key, decoPreferences); if (dnp != null) { return dnp.getSelectedOption(); } return null; } /** * Get the display name for the site type in question. * If a course site, it will pull the info from the "term" site property * @param site * @return */ private String getSiteTypeDisplay(Site site) { ResourceProperties siteProperties = site.getProperties(); String type = site.getType(); String term = null; if ("course".equals(type)) { term = siteProperties.getProperty("term"); if (term==null) term = msgs.getString("moresite_no_term",""); } else if ("project".equals(type)) { term = msgs.getString("moresite_projects"); } else if ("portfolio".equals(type)) { term = msgs.getString("moresite_portfolios"); } else if ("scs".equals(type)) { term = msgs.getString("moresite_scs"); } else if ("admin".equals(type)) { term = msgs.getString("moresite_administration"); } else { term = msgs.getString("moresite_other"); } return term; } public class DecoratedNotificationPreference { private String key = ""; private UserNotificationPreferencesRegistration userNotificationPreferencesRegistration = null; private String selectedOption = ""; private List<SelectItem> optionSelectItems = new ArrayList<>(); private List<SiteOverrideBean> siteOverrides = new ArrayList<>(); private List<DecoratedSiteTypeBean> siteList = new ArrayList<>(); private Integer sortOrder = Integer.MAX_VALUE; private boolean hidden = false; private Boolean expandOverride = null; public DecoratedNotificationPreference() { log.debug("DecoratedNotificationPreference()"); } public DecoratedNotificationPreference(UserNotificationPreferencesRegistration userNotificationPreferencesRegistration, List<SiteOverrideBean> siteOverrides) { log.debug("DecoratedNotificationPreference(...)"); this.userNotificationPreferencesRegistration = userNotificationPreferencesRegistration; this.key = userNotificationPreferencesRegistration.getType(); this.siteOverrides = siteOverrides; for (String optionKey : userNotificationPreferencesRegistration.getOptions().keySet()) { SelectItem si = new SelectItem(optionKey, userNotificationPreferencesRegistration.getOptions().get(optionKey)); optionSelectItems.add(si); } } public void setKey(String key) { this.key = key; } public String getKey() { return key; } public void setUserNotificationPreferencesRegistration(UserNotificationPreferencesRegistration userNotificationPreferencesRegistration) { this.userNotificationPreferencesRegistration = userNotificationPreferencesRegistration; } public UserNotificationPreferencesRegistration getUserNotificationPreferencesRegistration() { return userNotificationPreferencesRegistration; } public void setSelectedOption(String selectedOption) { this.selectedOption = selectedOption; } public String getSelectedOption() { return selectedOption; } public void setOptionSelectItems(List<SelectItem> optionSelectItems) { this.optionSelectItems = optionSelectItems; } public List<SelectItem> getOptionSelectItems() { return optionSelectItems; } public void setSiteOverrides(List<SiteOverrideBean> siteOverrides) { this.siteOverrides = siteOverrides; } public List<SiteOverrideBean> getSiteOverrides() { return siteOverrides; } public List<DecoratedSiteTypeBean> getSiteList() { return siteList; } public void setSiteList(List<DecoratedSiteTypeBean> siteList) { this.siteList = siteList; } public Integer getSortOrder() { return sortOrder; } public void setSortOrder(Integer sortOrder) { this.sortOrder = sortOrder; } public boolean isHidden() { return hidden; } public void setHidden(boolean hidden) { this.hidden = hidden; } public Boolean getExpandOverride() { return expandOverride; } public void setExpandOverride(Boolean expandOverride) { this.expandOverride = expandOverride; } public boolean getExpand() { Boolean override = getExpandOverride(); if (override != null) return override; else return this.getUserNotificationPreferencesRegistration().isExpandByDefault(); } public String processActionAddOverrides() { setCurrentDecoratedNotificationPreference(this); initSiteList(); return "noti_addSiteOverride"; } /** * Initializing the site structures */ private void initSiteList() { Map<String, List<DecoratedSiteBean>> siteTypeMap = new HashMap<>(); Map<String, String> siteTypeKeyMap = new HashMap<>(); List<String> selectedSites = getSelectedNotificationItemIds(this); for (Site site : m_sites) { if (site.getToolForCommonId(userNotificationPreferencesRegistration.getToolId()) != null) { String typeDisplay = getSiteTypeDisplay(site); List<DecoratedSiteBean> sitesList = siteTypeMap.get(typeDisplay); if (sitesList == null) { sitesList = new ArrayList<>(); } boolean selected = selectedSites.contains(site.getId()); sitesList.add(new DecoratedSiteBean(site, selected)); siteTypeMap.put(typeDisplay, sitesList); siteTypeKeyMap.put(typeDisplay, site.getType()); } } String expandTypeString = ServerConfigurationService.getString("prefs.type.autoExpanded", "portfolio"); String[] sortedTypeList = ServerConfigurationService.getStrings("prefs.type.order"); if(sortedTypeList == null) { sortedTypeList = new String[] {"portfolio","course","project"}; } String[] termOrder = ServerConfigurationService.getStrings("portal.term.order"); List<String> myTermOrder = new ArrayList<>(); if (termOrder != null) { for (int i = 0; i < termOrder.length; i++) { if (siteTypeMap.containsKey(termOrder[i])) { myTermOrder.add(termOrder[i]); } } } int count = 0; for (int i = 0; i < sortedTypeList.length; i++) { if ("course".equalsIgnoreCase(sortedTypeList[i])) { boolean firstCourse = true; for (String value : myTermOrder) { if (value != null && !value.equals("")) { m_sortedTypes.put(value, count); count++; if (firstCourse) { expandTypeString = expandTypeString.concat("," + value); firstCourse=false; } } } } else { String value = sortedTypeList[i]; if (value != null && !value.equals("")) { m_sortedTypes.put(value, count); count++; } } } //List<DecoratedSiteTypeBean> siteOverrideList = new ArrayList<DecoratedSiteTypeBean>(); List<String> expandedTypes = Arrays.asList(expandTypeString.split(",")); siteList = getFullSiteOverrideList(siteTypeMap, siteTypeKeyMap, expandedTypes); } /** * Get all the sites by type and determine if the div should be expanded. * @return */ private List<DecoratedSiteTypeBean> getFullSiteOverrideList(Map<String, List<DecoratedSiteBean>> siteTypeMap, Map<String, String> siteTypeKeyMap, List<String> expandedTypes) { log.debug("getFullSiteOverrideList()"); List<DecoratedSiteTypeBean> list = new ArrayList<>(); for (String keyText : siteTypeMap.keySet()) { boolean expand = false; String typeKey = siteTypeKeyMap.get(keyText); if (expandedTypes.contains(typeKey) || expandedTypes.contains(keyText.toUpperCase())) expand = true; list.add(new DecoratedSiteTypeBean(typeKey, keyText, siteTypeMap.get(keyText), expand)); } Collections.sort(list, new SiteTypeSorter()); return list; } /** * Do the save action * @return */ public String processActionSiteOverrideSave() { log.debug("processActionSiteOverrideSave()"); // get an edit setUserEditingOn(); if (m_edit != null) { List<SiteOverrideBean> toAdd = new ArrayList<>(); List<String> toDel = new ArrayList<>(); /** previously saved choices */ List<String> existingList = convertToStringList(getSiteOverrides()); log.debug("processActionSiteOverrideSave().existingList: " + convertListToString(existingList)); for (DecoratedSiteTypeBean dstb : siteList) { for (DecoratedSiteBean dsb : dstb.getSites()) { String siteId = dsb.getSite().getId(); log.debug("processActionSiteOverrideSave().selected?: " +siteId + ": " + dsb.selected); SiteOverrideBean sob = new SiteOverrideBean(siteId, Integer.toString(NotificationService.PREF_NONE)); if (dsb.selected && !existingList.contains(siteId)) { toAdd.add(sob); //siteOverrides.add(sob); } else if (!dsb.selected && existingList.contains(siteId)) { toDel.add(siteId); //siteOverrides.remove(sob); } } } log.debug("processActionSiteOverrideSave().toAdd: " + convertListToString(toAdd)); log.debug("processActionSiteOverrideSave().toDel: " + convertListToString(toDel)); //adds readOverrideTypePrefs(userNotificationPreferencesRegistration.getType() + NotificationService.NOTI_OVERRIDE_EXTENSION, m_edit, toAdd); //deletes deleteOverrideTypePrefs(userNotificationPreferencesRegistration.getType() + NotificationService.NOTI_OVERRIDE_EXTENSION, userNotificationPreferencesRegistration.getPrefix(), m_edit, toDel); // update the edit and release it preferencesService.commit(m_edit); //make sure the list gets updated initRegisteredNotificationItems(); } notiUpdated = true; return "noti"; } /** * For display/debug purposes. Turns a List into a readable string * @param list * @return */ private String convertListToString(List list) { String retVal = "["; int counter = 0; for (Iterator i = list.iterator(); i.hasNext();) { Object rawValue = i.next(); String val = ""; if (rawValue instanceof SiteOverrideBean) { val = ((SiteOverrideBean)rawValue).getSiteId(); } else { val = (String) rawValue; } if (counter > 0) retVal = retVal.concat(","); retVal = retVal.concat(val); counter++; } return retVal.concat("]"); } /** * For display/debug purposes. Turns a List of SiteOverrideBeans into a readable string * @param list * @return */ private List<String> convertToStringList(List<SiteOverrideBean> list) { List<String> retList = new ArrayList<>(list.size()); for (SiteOverrideBean sob : list) { retList.add(sob.getSiteId()); } return retList; } /** * Do the cancel action * @return */ public String processActionSiteOverrideCancel() { log.debug("processActionSiteOverrideCancel()"); processRegisteredNotificationItems(); return "noti"; } } public String processHiddenSites() { setUserEditingOn(); if (m_edit != null) { // Remove existing property ResourcePropertiesEdit props = m_edit.getPropertiesEdit(PreferencesService.SITENAV_PREFS_KEY); List currentFavoriteSites = props.getPropertyList(ORDER_SITE_LISTS); if (currentFavoriteSites == null) { currentFavoriteSites = Collections.<String>emptyList(); } props.removeProperty(TAB_LABEL_PREF); props.removeProperty(ORDER_SITE_LISTS); props.removeProperty(EXCLUDE_SITE_LISTS); preferencesService.commit(m_edit); cancelEdit(); // Set favorites and hidden sites setUserEditingOn(); props = m_edit.getPropertiesEdit(PreferencesService.SITENAV_PREFS_KEY); for (Object siteId : currentFavoriteSites) { props.addPropertyToList(ORDER_SITE_LISTS, (String)siteId); } if (hiddenSitesInput != null && !hiddenSitesInput.isEmpty()) { for (String siteId : hiddenSitesInput.split(",")) { props.addPropertyToList(EXCLUDE_SITE_LISTS, siteId); } } props.addProperty(TAB_LABEL_PREF, prefTabLabel); preferencesService.commit(m_edit); cancelEdit(); hiddenUpdated = true; m_reloadTop = Boolean.TRUE; } return "hidden"; } public class SiteOverrideBean { private String siteId = ""; private String siteTitle = ""; private String option = ""; private boolean remove = false; public SiteOverrideBean() { log.debug("SiteOverrideBean()"); } public SiteOverrideBean(String siteId, String option) { log.debug("SiteOverrideBean(String, String)"); this.siteId = siteId; this.option = option; try { Site site = SiteService.getSite(siteId); this.siteTitle = getUserSpecificSiteTitle(site, true); } catch (IdUnusedException e) { log.warn("Unable to get Site object for id: " + siteId, e); } } public String getSiteId() { return siteId; } public void setSiteId(String siteId) { this.siteId = siteId; } public String getSiteTitle() { return siteTitle; } public void setSiteTitle(String siteTitle) { this.siteTitle = siteTitle; } public String getOption() { return option; } public void setOption(String option) { this.option = option; } public void setRemove(boolean remove) { this.remove = remove; } public boolean isRemove() { return remove; } } public class DecoratedSiteTypeBean { private String typeKey = ""; private String typeText = ""; private String condensedTypeText = ""; private List<DecoratedSiteBean> sites = new ArrayList<>(); private List<SelectItem> sitesAsSelects = new ArrayList<>(); private boolean defaultOpen = false; public DecoratedSiteTypeBean() { log.debug("DecoratedSiteTypeBean()"); } public DecoratedSiteTypeBean(String typeKey, String typeText, List<DecoratedSiteBean> sites, boolean defaultOpen) { log.debug("DecoratedSiteTypeBean(...)"); this.setTypeKey(typeKey); this.typeText = typeText; this.sites = sites; this.condensedTypeText = typeText.replace(" ", ""); this.defaultOpen = defaultOpen; for (DecoratedSiteBean dsb : sites) { sitesAsSelects.add(new SelectItem(dsb.getSite().getId(), getUserSpecificSiteTitle(dsb.getSite(), true))); } } public String getStyle() { String style = "display: none;"; if (defaultOpen) style = "display: block;"; return style; } public String getIconUrl() { String url = "/library/image/sakai/expand.gif"; if (defaultOpen) url = "/library/image/sakai/collapse.gif"; return url; } public String getShowHideText() { String key = "hideshowdesc_toggle_show"; if (defaultOpen) key = "hideshowdesc_toggle_hide"; return msgs.getString(key); } public Integer getSortOrder() { Integer sort = null; if (typeKey.equals("course")) { sort = m_sortedTypes.get(typeText.toUpperCase()); } else { sort = m_sortedTypes.get(typeKey); } if (sort == null) sort = Integer.MAX_VALUE; return sort; } public void setTypeKey(String typeKey) { this.typeKey = typeKey; } public String getTypeKey() { return typeKey; } public String getTypeText() { return typeText; } public void setTypeText(String typeText) { this.typeText = typeText; } public String getCondensedTypeText() { return condensedTypeText; } public void setCondensedTypeText(String condensedTypeText) { this.condensedTypeText = condensedTypeText; } public List<DecoratedSiteBean> getSites() { return sites; } public void setSites(List<DecoratedSiteBean> sites) { this.sites = sites; } public List<SelectItem> getSitesAsSelects() { return sitesAsSelects; } public void setSitesAsSelects(List<SelectItem> sitesAsSelects) { this.sitesAsSelects = sitesAsSelects; } public void setDefaultOpen(boolean defaultOpen) { this.defaultOpen = defaultOpen; } public boolean isDefaultOpen() { return defaultOpen; } } public class DecoratedSiteBean { private Site site = null; private boolean selected = false; public DecoratedSiteBean() { log.debug("DecoratedSiteBean()"); } public DecoratedSiteBean(Site site) { log.debug("DecoratedSiteBean(Site)"); this.site = site; } public DecoratedSiteBean(Site site, boolean selected) { log.debug("DecoratedSiteBean(Site, boolean)"); this.site = site; this.selected = selected; } public Site getSite() { return site; } public void setSite(Site site) { this.site = site; } public boolean isSelected() { return selected; } public void setSelected(boolean selected) { this.selected = selected; } public void checkBoxChanged(ValueChangeEvent vce) { log.debug("checkBoxChanged()" + site.getId() + ": " + vce.getOldValue().toString() + "-->" + vce.getNewValue().toString()); Boolean tmpSelected = (Boolean)vce.getNewValue(); if (tmpSelected != null) { selected = tmpSelected; } } } /** * Class that figures out the order of the site types * @author chrismaurer * */ class SiteTypeSorter implements Comparator<DecoratedSiteTypeBean> { public int compare(DecoratedSiteTypeBean first, DecoratedSiteTypeBean second) { if (first == null || second == null) return 0; Integer firstSort = first.getSortOrder(); Integer secondSort = second.getSortOrder(); if (firstSort != null) return firstSort.compareTo(secondSort); return 0; } } /** * Class that figures out the order of the site types * @author chrismaurer * */ class SiteOverrideBeanSorter implements Comparator<SiteOverrideBean> { public int compare(SiteOverrideBean first, SiteOverrideBean second) { if (first == null || second == null) return 0; String firstSort = first.getSiteTitle(); String secondSort = second.getSiteTitle(); if (firstSort != null) return firstSort.toLowerCase().compareTo(secondSort.toLowerCase()); return 0; } } /** * Class that figures out the order of the site types * @author chrismaurer * */ class DecoratedNotificationPreferenceSorter implements Comparator<DecoratedNotificationPreference> { public int compare(DecoratedNotificationPreference first, DecoratedNotificationPreference second) { if (first == null || second == null) return 0; Integer firstSort = first.getSortOrder(); Integer secondSort = second.getSortOrder(); if (firstSort != null) return firstSort.compareTo(secondSort); return 0; } } public class TermSites { private List<Term> terms; private List <String> termOrder; public class Term implements Comparable<Term> { private String label; private List<Site> sites; public Term(String label, List<Site> sites) { if (sites.isEmpty()) { throw new RuntimeException("List of sites can't be empty"); } this.label = label; this.sites = sites; } public String getLabel() { return label; } public List<Site> getSites() { return sites; } public String getType() { return this.getSites().get(0).getType(); } public int compareTo(Term other) { if (termOrder != null && (termOrder.contains(this.label) || termOrder.contains(other.label))) { return(NumberUtils.compare(termOrder.indexOf(this.label), termOrder.indexOf(other.label))); } String myType = this.getType(); String theirType = other.getType(); // Otherwise if not found in a term course sites win out over non-course-sites if (myType == null) { return 1; } else if (theirType == null) { return -1; } else if (myType.equals(theirType)) { return 0; } else if ("course".equals(myType)) { return -1; } else { return 1; } } } public TermSites(List<Site> sites) { List<String> termNames = new ArrayList<>(); Map<String, List<Site>> termsToSites = new HashMap<>(); for (Site site : sites) { String term = determineTerm(site); if (!termNames.contains(term)) { termNames.add(term); termsToSites.put(term, new ArrayList<>(1)); } // This is being used to display the full site title in the tool tip. // It's necessary to pack this into some random/unused field of the Site object // because the tool is using an old JSF version, which does not support calling // methods with parameters in a JSP file to a backing bean. So, as a hack, we stuff // the untruncated site title into the 'infoUrl' String to accomplish this. // The site object is never saved, so we don't have to worry about overwriting the 'infoUrl' value site.setInfoUrl(getUserSpecificSiteTitle(site, false)); site.setTitle(getUserSpecificSiteTitle(site, true)); termsToSites.get(term).add(site); } terms = new ArrayList<>(); for (String name : termNames) { terms.add(new Term(name, termsToSites.get(name))); } termOrder = PortalUtils.getPortalTermOrder(null); Collections.sort(terms); } public List<Term> getTerms() { return terms; } private String determineTerm(Site site) { ResourceProperties siteProperties = site.getProperties(); String type = site.getType(); if (isCourseType(type)) { String term = siteProperties.getProperty(Site.PROP_SITE_TERM); if (term == null) { term = msgs.getString("moresite_no_term"); } return term; } else if (isProjectType(type)) { return msgs.getString("moresite_projects"); } else if ("portfolio".equals(type)) { return msgs.getString("moresite_portfolios"); } else if ("admin".equals(type)) { return msgs.getString("moresite_administration"); } else { return msgs.getString("moresite_other"); } } public List<String> getSiteTypeStrings(String type) { String[] siteTypes = ServerConfigurationService.getStrings(type + "SiteType"); if (siteTypes == null || siteTypes.length == 0) { siteTypes = new String[] {type}; } return Arrays.asList(siteTypes); } private boolean isCourseType(String type) { return getSiteTypeStrings("course").contains(type); } private boolean isProjectType(String type) { return getSiteTypeStrings("project").contains(type); } } public TermSites getTermSites() { List<Site> mySites = (List<Site>)SiteService.getSites(org.sakaiproject.site.api.SiteService.SelectionType.ACCESS, null, null, null, org.sakaiproject.site.api.SiteService.SortType.TITLE_ASC, null); return new TermSites(mySites); } public String getHiddenSites() { Preferences prefs = preferencesService.getPreferences(getUserId()); ResourceProperties props = prefs.getProperties(PreferencesService.SITENAV_PREFS_KEY); List currentHiddenSites = props.getPropertyList(EXCLUDE_SITE_LISTS); StringBuilder result = new StringBuilder(); if (currentHiddenSites != null) { for (Object siteId : currentHiddenSites) { if (result.length() > 0) { result.append(","); } result.append(siteId); } } return result.toString(); } public void setHiddenSites(String hiddenSiteCSV) { this.hiddenSitesInput = hiddenSiteCSV; } /** * Gets the name of the service. * @return The name of the service that should be shown to users. */ public String getServiceName() { return ServerConfigurationService.getString("ui.service", "Sakai"); } }
/* * Copyright (c) 2018-present, iQIYI, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package org.qiyi.video.svg.transfer.service; import android.os.IBinder; import org.qiyi.video.svg.bean.BinderBean; /** * Created by wangallen on 2018/1/9. */ public interface IRemoteServiceTransfer { //IBinder getRemoteService(LifecycleOwner owner, String serviceCanonicalName); //IBinder getRemoteService(String serviceCanonicalName); BinderBean getRemoteServiceBean(String serviceCanonicalName); //其实是registerStubService void registerStubService(String serviceCanonicalName, IBinder stubBinder); /** * 要注销本进程的某个服务,注意它与 * * @param serviceCanonicalName */ void unregisterStubService(String serviceCanonicalName); }
package designpattern.factory.factory; import designpattern.factory.factory.pizza.Pizza; /** * 芝加哥比萨 * * @author wangdongxing * @since 2018/11/15 2:59 PM */ public class ChicagoPizzaStore extends PizzaStore { @Override public Pizza createPizza(String type) { SimplePizzaFactory factory = new ChicagoPizzaFactory(); return factory.createPizza(type); } }
package sch.frog.sparrow.doodle; import java.util.Arrays; /** * 深度优先搜索算法演示 */ public class DFS { public static void main(String[] args){ int len = 3; dfsSearch(6, 0, 1, new int[len], len); } /** * 把正整数num分解为3个不同的正整数, 如: 6 = 1 + 2 + 3, 排在后面的数必须大于等于前面的数, 输出所有方案. * @param num 需要分解的正整数 * @param min 最小值 * @param depth 搜索深度 * @param arr 结果数组 * @param limit 最大深度 */ private static void dfsSearch(int num, int min, int depth, int[] arr, int limit){ if(num == 0){ System.out.println(Arrays.toString(arr)); }else if(depth <= limit){ for(int j = min; j <= num; j++){ arr[depth - 1] = j; dfsSearch(num - j, j, depth + 1, arr, limit); } } } }
/* * Copyright 2011 CodeGist.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. * * =================================================================== * * More information at http://www.codegist.org. */ package org.codegist.crest.deserialization.crest; import org.codegist.crest.CRestBuilder; import org.codegist.crest.annotate.*; import org.codegist.crest.deserialization.common.CommonComplexObjectDeserializationsTest; import org.codegist.crest.deserialization.common.IComplexObjectDeserializations; import org.codegist.crest.handler.DefaultResponseHandler; import org.codegist.crest.util.model.jackson.JacksonSomeData; import org.junit.runners.Parameterized; import java.util.Collection; import java.util.List; /** * @author Laurent Gilles (laurent.gilles@codegist.org) */ public class ComplexObjectDeserializationsWithJacksonTest extends CommonComplexObjectDeserializationsTest<ComplexObjectDeserializationsWithJacksonTest.ComplexObjectDeserializationsWithJackson> { public ComplexObjectDeserializationsWithJacksonTest(CRestHolder crest) { super(crest, ComplexObjectDeserializationsWithJackson.class); } @Parameterized.Parameters public static Collection<CRestHolder[]> getData() { return crest(arrify(forEachBaseBuilder(new Builder() { public CRestHolder build(CRestBuilder builder) { return new CRestHolder(builder.build()); } }))); } /** * @author laurent.gilles@codegist.org */ @EndPoint("{crest.server.end-point}") @Path("deserialization/complexobject") @GET @ResponseHandler(DefaultResponseHandler.class) public static interface ComplexObjectDeserializationsWithJackson extends IComplexObjectDeserializations { @Path("json") JacksonSomeData someDataGuessed( @QueryParam("date-format") String dateFormat, @QueryParam("boolean-true") String booleanTrue, @QueryParam("boolean-false") String booleanFalse); @Consumes("application/json") JacksonSomeData someDataForced( @QueryParam("date-format") String dateFormat, @QueryParam("boolean-true") String booleanTrue, @QueryParam("boolean-false") String booleanFalse); @Path("jsons") JacksonSomeData[] someDatas( @QueryParam("date-format") String dateFormat, @QueryParam("boolean-true") String booleanTrue, @QueryParam("boolean-false") String booleanFalse); @Path("jsons") List<JacksonSomeData> someDatas2( @QueryParam("date-format") String dateFormat, @QueryParam("boolean-true") String booleanTrue, @QueryParam("boolean-false") String booleanFalse); } }
package br.com.cod3r.strategy.worker; import br.com.cod3r.strategy.worker.jobs.Developer; import br.com.cod3r.strategy.worker.jobs.HispsterDeveloper; import br.com.cod3r.strategy.worker.jobs.Pilot; import br.com.cod3r.strategy.worker.jobs.Worker; public class Client { public static void presentYourself(Worker worker, String name) { System.out.println("Hi, I'm " + name); worker.eat(); worker.move(); worker.work(); System.out.println("----------------"); } public static void main(String[] args) { Worker jhon = new Developer(); presentYourself(jhon, "Jhon"); Worker ann = new Pilot(); presentYourself(ann, "Ann"); Worker carol = new HispsterDeveloper(); presentYourself(carol, "carol"); } }
/* * Copyright 2017 PayPal * * 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.squbs.testkit.japi.testng; import akka.http.javadsl.marshallers.jackson.Jackson; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.testkit.TestRoute; import org.squbs.testkit.japi.InfoRoute; import org.squbs.testkit.japi.RouteInfo; import org.squbs.testkit.japi.TestNGRouteTest; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class RouteTestTest extends TestNGRouteTest { @Test public void testSimpleRoute() { TestRoute simpleRoute = testRoute(InfoRoute.class); RouteInfo routeInfo = simpleRoute.run(HttpRequest.GET("/context-info")) .assertStatusCode(200) .entity(Jackson.unmarshaller(RouteInfo.class)); assertEquals(routeInfo.getWebContext(), ""); assertTrue(routeInfo.getActorPath().startsWith("akka://"), "ActorPath: " + routeInfo.getActorPath() + " does not start with akka://"); } @Test public void testSimpleRouteWithContext() { TestRoute simpleRoute = testRoute("my-context", InfoRoute.class); RouteInfo routeInfo = simpleRoute.run(HttpRequest.GET("/my-context/context-info")) .assertStatusCode(200) .entity(Jackson.unmarshaller(RouteInfo.class)); assertEquals(routeInfo.getWebContext(), "my-context"); assertTrue(routeInfo.getActorPath().startsWith("akka://"), "ActorPath: " + routeInfo.getActorPath() + " does not start with akka://"); } }
/* Copyright 2021 Fausto Spoto 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 io.hotmoka.verification.internal; import java.lang.reflect.Executable; import java.util.HashSet; import java.util.LinkedList; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.apache.bcel.Const; import org.apache.bcel.classfile.BootstrapMethod; import org.apache.bcel.classfile.BootstrapMethods; import org.apache.bcel.classfile.Constant; import org.apache.bcel.classfile.ConstantClass; import org.apache.bcel.classfile.ConstantInterfaceMethodref; import org.apache.bcel.classfile.ConstantInvokeDynamic; import org.apache.bcel.classfile.ConstantMethodHandle; import org.apache.bcel.classfile.ConstantMethodref; import org.apache.bcel.classfile.ConstantNameAndType; import org.apache.bcel.classfile.ConstantUtf8; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.INVOKEDYNAMIC; import org.apache.bcel.generic.INVOKESTATIC; import org.apache.bcel.generic.Instruction; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.InstructionList; import org.apache.bcel.generic.InvokeInstruction; import org.apache.bcel.generic.MethodGen; import org.apache.bcel.generic.ObjectType; import org.apache.bcel.generic.ReferenceType; import org.apache.bcel.generic.Type; import io.hotmoka.verification.Bootstraps; import io.hotmoka.verification.IncompleteClasspathError; /** * An object that provides utility methods about the lambda bootstraps * contained in a class. */ public class BootstrapsImpl implements Bootstraps { /** * The class whose bootstraps are considered. */ private final VerifiedClassImpl verifiedClass; /** * The constant pool of the class whose bootstraps are considered. */ private final ConstantPoolGen cpg; /** * The bootstrap methods of the class. */ private final BootstrapMethod[] bootstrapMethods; /** * The bootstrap methods of the class that lead to an entry, possibly indirectly. */ private final Set<BootstrapMethod> bootstrapMethodsLeadingToEntries = new HashSet<>(); /** * The set of lambdas that are reachable from the entries of the class. They can * be considered as part of the code of the entries. */ private final Set<MethodGen> lambdasPartOfEntries = new HashSet<>(); private final static BootstrapMethod[] NO_BOOTSTRAPS = new BootstrapMethod[0]; BootstrapsImpl(VerifiedClassImpl clazz, MethodGen[] methods) { this.verifiedClass = clazz; this.cpg = clazz.getConstantPool(); this.bootstrapMethods = computeBootstraps(); collectBootstrapsLeadingToEntries(methods); collectLambdasOfEntries(methods); } /** * Creates a deep clone of the given bootstrap methods. * * @param original the object to clone */ BootstrapsImpl(BootstrapsImpl original) { this.verifiedClass = original.verifiedClass; this.cpg = original.cpg; this.bootstrapMethods = new BootstrapMethod[original.bootstrapMethods.length]; for (int pos = 0; pos < original.bootstrapMethods.length; pos++) { BootstrapMethod clone = this.bootstrapMethods[pos] = original.bootstrapMethods[pos].copy(); // the array of arguments is shared by copy(), hence we clone it explicitly clone.setBootstrapArguments(original.bootstrapMethods[pos].getBootstrapArguments().clone()); if (original.bootstrapMethodsLeadingToEntries.contains(original.bootstrapMethods[pos])) this.bootstrapMethodsLeadingToEntries.add(clone); } } @Override public boolean lambdaIsEntry(BootstrapMethod bootstrap) { if (bootstrap.getNumBootstrapArguments() == 3) { Constant constant = cpg.getConstant(bootstrap.getBootstrapArguments()[1]); if (constant instanceof ConstantMethodHandle) { ConstantMethodHandle mh = (ConstantMethodHandle) constant; Constant constant2 = cpg.getConstant(mh.getReferenceIndex()); if (constant2 instanceof ConstantMethodref) { ConstantMethodref mr = (ConstantMethodref) constant2; int classNameIndex = ((ConstantClass) cpg.getConstant(mr.getClassIndex())).getNameIndex(); String className = ((ConstantUtf8) cpg.getConstant(classNameIndex)).getBytes().replace('/', '.'); ConstantNameAndType nt = (ConstantNameAndType) cpg.getConstant(mr.getNameAndTypeIndex()); String methodName = ((ConstantUtf8) cpg.getConstant(nt.getNameIndex())).getBytes(); String methodSignature = ((ConstantUtf8) cpg.getConstant(nt.getSignatureIndex())).getBytes(); return verifiedClass.jar.annotations.isFromContract(className, methodName, Type.getArgumentTypes(methodSignature), Type.getReturnType(methodSignature)); } } } return false; } @Override public boolean lambdaIsRedPayable(BootstrapMethod bootstrap) { if (bootstrap.getNumBootstrapArguments() == 3) { Constant constant = cpg.getConstant(bootstrap.getBootstrapArguments()[1]); if (constant instanceof ConstantMethodHandle) { ConstantMethodHandle mh = (ConstantMethodHandle) constant; Constant constant2 = cpg.getConstant(mh.getReferenceIndex()); if (constant2 instanceof ConstantMethodref) { ConstantMethodref mr = (ConstantMethodref) constant2; int classNameIndex = ((ConstantClass) cpg.getConstant(mr.getClassIndex())).getNameIndex(); String className = ((ConstantUtf8) cpg.getConstant(classNameIndex)).getBytes().replace('/', '.'); ConstantNameAndType nt = (ConstantNameAndType) cpg.getConstant(mr.getNameAndTypeIndex()); String methodName = ((ConstantUtf8) cpg.getConstant(nt.getNameIndex())).getBytes(); String methodSignature = ((ConstantUtf8) cpg.getConstant(nt.getSignatureIndex())).getBytes(); return verifiedClass.jar.annotations.isRedPayable(className, methodName, Type.getArgumentTypes(methodSignature), Type.getReturnType(methodSignature)); } } } return false; } @Override public Stream<BootstrapMethod> getBootstraps() { return Stream.of(bootstrapMethods); } @Override public Stream<BootstrapMethod> getBootstrapsLeadingToEntries() { return bootstrapMethodsLeadingToEntries.stream(); } @Override public BootstrapMethod getBootstrapFor(INVOKEDYNAMIC invokedynamic) { ConstantInvokeDynamic cid = (ConstantInvokeDynamic) cpg.getConstant(invokedynamic.getIndex()); return bootstrapMethods[cid.getBootstrapMethodAttrIndex()]; } @Override public Optional<? extends Executable> getTargetOf(BootstrapMethod bootstrap) { Constant constant = cpg.getConstant(bootstrap.getBootstrapMethodRef()); if (constant instanceof ConstantMethodHandle) { ConstantMethodHandle mh = (ConstantMethodHandle) constant; Constant constant2 = cpg.getConstant(mh.getReferenceIndex()); if (constant2 instanceof ConstantMethodref) { ConstantMethodref mr = (ConstantMethodref) constant2; int classNameIndex = ((ConstantClass) cpg.getConstant(mr.getClassIndex())).getNameIndex(); String className = ((ConstantUtf8) cpg.getConstant(classNameIndex)).getBytes().replace('/', '.'); ConstantNameAndType nt = (ConstantNameAndType) cpg.getConstant(mr.getNameAndTypeIndex()); String methodName = ((ConstantUtf8) cpg.getConstant(nt.getNameIndex())).getBytes(); String methodSignature = ((ConstantUtf8) cpg.getConstant(nt.getSignatureIndex())).getBytes(); return getTargetOfCallSite(bootstrap, className, methodName, methodSignature); } } return Optional.empty(); } @Override public boolean isPartOfFromContract(MethodGen lambda) { return lambdasPartOfEntries.contains(lambda); } /** * Yields the lambda bridge method called by the given bootstrap. * It must belong to the same class that we are processing. * * @param bootstrap the bootstrap * @param methods the methods of the class under verification * @return the lambda bridge method */ private Optional<MethodGen> getLambdaFor(BootstrapMethod bootstrap, MethodGen[] methods) { if (bootstrap.getNumBootstrapArguments() == 3) { Constant constant = cpg.getConstant(bootstrap.getBootstrapArguments()[1]); if (constant instanceof ConstantMethodHandle) { ConstantMethodHandle mh = (ConstantMethodHandle) constant; Constant constant2 = cpg.getConstant(mh.getReferenceIndex()); if (constant2 instanceof ConstantMethodref) { ConstantMethodref mr = (ConstantMethodref) constant2; int classNameIndex = ((ConstantClass) cpg.getConstant(mr.getClassIndex())).getNameIndex(); String className = ((ConstantUtf8) cpg.getConstant(classNameIndex)).getBytes().replace('/', '.'); ConstantNameAndType nt = (ConstantNameAndType) cpg.getConstant(mr.getNameAndTypeIndex()); String methodName = ((ConstantUtf8) cpg.getConstant(nt.getNameIndex())).getBytes(); String methodSignature = ((ConstantUtf8) cpg.getConstant(nt.getSignatureIndex())).getBytes(); // a lambda bridge can only be present in the same class that calls it if (className.equals(verifiedClass.getClassName())) return Stream.of(methods) .filter(method -> method.getName().equals(methodName) && method.getSignature().equals(methodSignature)) .findFirst(); } } } return Optional.empty(); } private Optional<? extends Executable> getTargetOfCallSite(BootstrapMethod bootstrap, String className, String methodName, String methodSignature) { if ("java.lang.invoke.LambdaMetafactory".equals(className) && "metafactory".equals(methodName) && "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;".equals(methodSignature)) { // this is the standard factory used to create call sites Constant constant = cpg.getConstant(bootstrap.getBootstrapArguments()[1]); if (constant instanceof ConstantMethodHandle) { ConstantMethodHandle mh = (ConstantMethodHandle) constant; Constant constant2 = cpg.getConstant(mh.getReferenceIndex()); if (constant2 instanceof ConstantMethodref) { ConstantMethodref mr = (ConstantMethodref) constant2; int classNameIndex = ((ConstantClass) cpg.getConstant(mr.getClassIndex())).getNameIndex(); String className2 = ((ConstantUtf8) cpg.getConstant(classNameIndex)).getBytes().replace('/', '.'); ConstantNameAndType nt = (ConstantNameAndType) cpg.getConstant(mr.getNameAndTypeIndex()); String methodName2 = ((ConstantUtf8) cpg.getConstant(nt.getNameIndex())).getBytes(); String methodSignature2 = ((ConstantUtf8) cpg.getConstant(nt.getSignatureIndex())).getBytes(); Class<?>[] args = verifiedClass.jar.bcelToClass.of(Type.getArgumentTypes(methodSignature2)); Class<?> returnType = verifiedClass.jar.bcelToClass.of(Type.getReturnType(methodSignature2)); if (Const.CONSTRUCTOR_NAME.equals(methodName2)) return verifiedClass.resolver.resolveConstructorWithPossiblyExpandedArgs(className2, args); else return verifiedClass.resolver.resolveMethodWithPossiblyExpandedArgs(className2, methodName2, args, returnType); } else if (constant2 instanceof ConstantInterfaceMethodref) { ConstantInterfaceMethodref mr = (ConstantInterfaceMethodref) constant2; int classNameIndex = ((ConstantClass) cpg.getConstant(mr.getClassIndex())).getNameIndex(); String className2 = ((ConstantUtf8) cpg.getConstant(classNameIndex)).getBytes().replace('/', '.'); ConstantNameAndType nt = (ConstantNameAndType) cpg.getConstant(mr.getNameAndTypeIndex()); String methodName2 = ((ConstantUtf8) cpg.getConstant(nt.getNameIndex())).getBytes(); String methodSignature2 = ((ConstantUtf8) cpg.getConstant(nt.getSignatureIndex())).getBytes(); Class<?>[] args = verifiedClass.jar.bcelToClass.of(Type.getArgumentTypes(methodSignature2)); Class<?> returnType = verifiedClass.jar.bcelToClass.of(Type.getReturnType(methodSignature2)); return verifiedClass.resolver.resolveInterfaceMethodWithPossiblyExpandedArgs(className2, methodName2, args, returnType); } } } else if ("java.lang.invoke.StringConcatFactory".equals(className) && "makeConcatWithConstants".equals(methodName) && "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;".equals(methodSignature)) { // this factory is used to create call sites that lead to string concatenation of every // possible argument type. Generically, we yield the Objects.toString(Object) method, since // all parameters must be checked in order for the call to be white-listed try { return Optional.of(Objects.class.getMethod("toString", Object.class)); } catch (NoSuchMethodException | SecurityException e) { throw new IncompleteClasspathError(new ClassNotFoundException("java.util.Objects")); } } return Optional.empty(); } private BootstrapMethod[] computeBootstraps() { Optional<BootstrapMethods> bootstraps = Stream.of(verifiedClass.getAttributes()) .filter(attribute -> attribute instanceof BootstrapMethods) .map(attribute -> (BootstrapMethods) attribute) .findFirst(); return bootstraps.isPresent() ? bootstraps.get().getBootstrapMethods() : NO_BOOTSTRAPS; } private void collectBootstrapsLeadingToEntries(MethodGen[] methods) { int initialSize; do { initialSize = bootstrapMethodsLeadingToEntries.size(); getBootstraps() .filter(bootstrap -> lambdaIsEntry(bootstrap) || lambdaCallsEntry(bootstrap, methods)) .forEach(bootstrapMethodsLeadingToEntries::add); } while (bootstrapMethodsLeadingToEntries.size() > initialSize); } /** * Collects the lambdas that are called from an {@code @@Entry} method. * * @param methods the methods of the class under verification */ private void collectLambdasOfEntries(MethodGen[] methods) { // we collect all lambdas reachable from the @Entry methods, possibly indirectly // (that is, a lambda can call another lambda); we use a working set that starts // with the @Entry methods LinkedList<MethodGen> ws = new LinkedList<>(); Stream.of(methods) .filter(method -> verifiedClass.jar.annotations.isFromContract(verifiedClass.getClassName(), method.getName(), method.getArgumentTypes(), method.getReturnType())) .forEach(ws::add); while (!ws.isEmpty()) { MethodGen current = ws.removeFirst(); InstructionList instructionsList = current.getInstructionList(); if (instructionsList != null) { Stream.of(instructionsList.getInstructions()) .filter(ins -> ins instanceof INVOKEDYNAMIC) .map(ins -> (INVOKEDYNAMIC) ins) .map(this::getBootstrapFor) .map(bootstrap -> getLambdaFor(bootstrap, methods)) .filter(Optional::isPresent) .map(Optional::get) .filter(lambda -> lambda.isPrivate() && lambda.isSynthetic()) .filter(lambdasPartOfEntries::add) .forEach(ws::addLast); } } } /** * Determines if the given lambda method calls an {@code @@Entry}, possibly indirectly. * * @param bootstrap the lambda method * @param methods the methods of the class under verification * @return true if that condition holds */ private boolean lambdaCallsEntry(BootstrapMethod bootstrap, MethodGen[] methods) { Optional<MethodGen> lambda = getLambdaFor(bootstrap, methods); if (lambda.isPresent()) { InstructionList instructions = lambda.get().getInstructionList(); if (instructions != null) return StreamSupport.stream(instructions.spliterator(), false).anyMatch(this::leadsToEntry); } return false; } /** * Determines if the given instruction calls an {@code @@Entry}, possibly indirectly. * * @param ih the instruction * @return true if that condition holds */ private boolean leadsToEntry(InstructionHandle ih) { Instruction instruction = ih.getInstruction(); if (instruction instanceof INVOKEDYNAMIC) return bootstrapMethodsLeadingToEntries.contains(getBootstrapFor((INVOKEDYNAMIC) instruction)); else if (instruction instanceof InvokeInstruction && !(instruction instanceof INVOKESTATIC)) { InvokeInstruction invoke = (InvokeInstruction) instruction; ReferenceType receiver = invoke.getReferenceType(cpg); return receiver instanceof ObjectType && verifiedClass.jar.annotations.isFromContract (((ObjectType) receiver).getClassName(), invoke.getMethodName(cpg), invoke.getArgumentTypes(cpg), invoke.getReturnType(cpg)); } else return false; } }
/* * Copyright 2013-2017 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 com.greenhouse.gateway.enhanced.filter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.isomorphism.util.TokenBucket; import org.isomorphism.util.TokenBuckets; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.Ordered; import org.springframework.http.HttpStatus; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; import java.util.concurrent.TimeUnit; /** * Sample throttling filter. * See https://github.com/bbeck/token-bucket */ public class ThrottleGatewayFilterFactory implements GlobalFilter, Ordered { private static final Log log = LogFactory.getLog(ThrottleGatewayFilterFactory.class); private TokenBucket tokenBucket; public ThrottleGatewayFilterFactory(int capacity, int refillTokens, int refillPeriod, TimeUnit refillUnit) { this.tokenBucket = TokenBuckets.builder() .withCapacity(capacity) .withFixedIntervalRefillStrategy(refillTokens, refillPeriod, refillUnit) .build(); } @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { //TODO: get a token bucket for a key log.debug("TokenBucket capacity: " + tokenBucket.getCapacity()); boolean consumed = tokenBucket.tryConsume(); if (consumed) { return chain.filter(exchange); } exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS); return exchange.getResponse().setComplete(); } /** * Get the order value of this object. * <p>Higher values are interpreted as lower priority. As a consequence, * the object with the lowest value has the highest priority (somewhat * analogous to Servlet {@code load-on-startup} values). * <p>Same order values will result in arbitrary sort positions for the * affected objects. * * @return the order value * @see #HIGHEST_PRECEDENCE * @see #LOWEST_PRECEDENCE */ @Override public int getOrder() { return -300; } }
package com.example.ordermgr; import org.springframework.context.annotation.Bean; import io.opentracing.contrib.metrics.MetricLabel; import io.opentracing.contrib.metrics.label.BaggageMetricLabel; import io.opentracing.contrib.metrics.label.ConstMetricLabel; import org.springframework.context.annotation.Configuration; @Configuration public class MetricsConfiguration { @Bean public MetricLabel transactionLabel() { return new BaggageMetricLabel("transaction", "n/a"); } @Bean public MetricLabel versionLabel() { return new ConstMetricLabel("version", System.getenv("VERSION")); } }
package Radium.PostProcessing.Effects; import Radium.Graphics.Shader.Shader; import Radium.PostProcessing.EffectField; import Radium.PostProcessing.PostProcessingEffect; public class Sharpen extends PostProcessingEffect { @EffectField public float intensity = 0.8f; public Sharpen() { name = "sharpen"; } public void SetUniforms(Shader shader) { shader.SetUniform("sharpenIntensity", intensity); } }
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * The Apereo Foundation 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.unitime.timetable.server.admin; import java.io.IOException; import org.springframework.stereotype.Service; import org.unitime.timetable.export.ExportHelper; import org.unitime.timetable.export.PDFPrinter; import org.unitime.timetable.export.PDFPrinter.A; import org.unitime.timetable.export.PDFPrinter.F; import org.unitime.timetable.gwt.shared.SimpleEditInterface; import org.unitime.timetable.gwt.shared.SimpleEditInterface.Field; import org.unitime.timetable.gwt.shared.SimpleEditInterface.FieldType; import org.unitime.timetable.gwt.shared.SimpleEditInterface.Record; /** * @author Tomas Muller */ @Service("org.unitime.timetable.export.Exporter:admin-report.pdf") public class AdminExportToPDF extends AdminExportToCSV { @Override public String reference() { return "admin-report.pdf"; } protected void export(SimpleEditInterface data, ExportHelper helper, String hidden) throws IOException { PDFPrinter out = new PDFPrinter(helper.getOutputStream(), false); try { helper.setup(out.getContentType(), helper.getParameter("type") + ".pdf", false); boolean hasDetails = hasDetails(data); for (int i = 0; i < data.getFields().length; i++) { boolean visible = data.getFields()[i].isVisible() && (hidden == null || !hidden.contains("|" + data.getFields()[i].getName() + "|")); if (hasDetails && i == 0) visible = false; if (!visible) out.hideColumn(i); } String[] header = new String[data.getFields().length]; for (int i = 0; i < data.getFields().length; i++) header[i] = header(data, data.getFields()[i]); out.printHeader(header); boolean visible = true; for (Record r: data.getRecords()) { if (hasDetails) { if ("-".equals(r.getField(0))) visible = true; else if ("+".equals(r.getField(0))) visible = false; else if (!visible) continue; } A[] line = new A[data.getFields().length]; for (int i = 0; i < data.getFields().length; i++) line[i] = pdfCell(data.getFields()[i], r, i); if (isParent(data, r)) { for (A cell: line) { cell.setBackground("#f3f3f3"); if (cell.getText().isEmpty()) cell.setText(" "); } } else if (hasDetails) { for (int i = 0; i < line.length; i++) if (i > 0 && data.getFields()[i].getName().contains("|") && !isParent(data, r)) line[i].setText(" " + line[i].getText()); } out.printLine(line); } } finally { out.close(); } } protected A pdfCell(Field field, Record record, int index) { A cell = new A(cell(field, record, index)); if (field.getType() == FieldType.number) cell.set(F.RIGHT); return cell; } }
/* * Javassist, a Java-bytecode translator toolkit. * Copyright (C) 1999-2007 Shigeru Chiba. All Rights Reserved. * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. Alternatively, the contents of this file may be used under * the terms of the GNU Lesser General Public License Version 2.1 or later. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. */ package javassist.convert; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; import javassist.CodeConverter.ArrayAccessReplacementMethodNames; import javassist.bytecode.BadBytecode; import javassist.bytecode.CodeIterator; import javassist.bytecode.ConstPool; import javassist.bytecode.Descriptor; import javassist.bytecode.MethodInfo; import javassist.bytecode.analysis.Analyzer; import javassist.bytecode.analysis.Frame; /** * A transformer which replaces array access with static method invocations. * * @author <a href="kabir.khan@jboss.com">Kabir Khan</a> * @author Jason T. Greene * @version $Revision: 1.8 $ */ public final class TransformAccessArrayField extends Transformer { private final String methodClassname; private final ArrayAccessReplacementMethodNames names; private Frame[] frames; private int offset; public TransformAccessArrayField(Transformer next, String methodClassname, ArrayAccessReplacementMethodNames names) throws NotFoundException { super(next); this.methodClassname = methodClassname; this.names = names; } public void initialize(ConstPool cp, CtClass clazz, MethodInfo minfo) throws CannotCompileException { /* * This transformer must be isolated from other transformers, since some * of them affect the local variable and stack maximums without updating * the code attribute to reflect the changes. This screws up the * data-flow analyzer, since it relies on consistent code state. Even * if the attribute values were updated correctly, we would have to * detect it, and redo analysis, which is not cheap. Instead, we are * better off doing all changes in initialize() before everyone else has * a chance to muck things up. */ CodeIterator iterator = minfo.getCodeAttribute().iterator(); while (iterator.hasNext()) { try { int pos = iterator.next(); int c = iterator.byteAt(pos); if (c == AALOAD) initFrames(clazz, minfo); if (c == AALOAD || c == BALOAD || c == CALOAD || c == DALOAD || c == FALOAD || c == IALOAD || c == LALOAD || c == SALOAD) { pos = replace(cp, iterator, pos, c, getLoadReplacementSignature(c)); } else if (c == AASTORE || c == BASTORE || c == CASTORE || c == DASTORE || c == FASTORE || c == IASTORE || c == LASTORE || c == SASTORE) { pos = replace(cp, iterator, pos, c, getStoreReplacementSignature(c)); } } catch (Exception e) { throw new CannotCompileException(e); } } } public void clean() { frames = null; offset = -1; } public int transform(CtClass tclazz, int pos, CodeIterator iterator, ConstPool cp) throws BadBytecode { // Do nothing, see above comment return pos; } private Frame getFrame(int pos) throws BadBytecode { return frames[pos - offset]; // Adjust pos } private void initFrames(CtClass clazz, MethodInfo minfo) throws BadBytecode { if (frames == null) { frames = ((new Analyzer())).analyze(clazz, minfo); offset = 0; // start tracking changes } } private int updatePos(int pos, int increment) { if (offset > -1) offset += increment; return pos + increment; } private String getTopType(int pos) throws BadBytecode { Frame frame = getFrame(pos); if (frame == null) return null; CtClass clazz = frame.peek().getCtClass(); return clazz != null ? Descriptor.toJvmName(clazz) : null; } private int replace(ConstPool cp, CodeIterator iterator, int pos, int opcode, String signature) throws BadBytecode { String castType = null; String methodName = getMethodName(opcode); if (methodName != null) { // See if the object must be cast if (opcode == AALOAD) { castType = getTopType(iterator.lookAhead()); // Do not replace an AALOAD instruction that we do not have a type for // This happens when the state is guaranteed to be null (Type.UNINIT) // So we don't really care about this case. if (castType == null) return pos; if ("java/lang/Object".equals(castType)) castType = null; } // The gap may include extra padding // Write a nop in case the padding pushes the instruction forward iterator.writeByte(NOP, pos); CodeIterator.Gap gap = iterator.insertGapAt(pos, castType != null ? 5 : 2, false); pos = gap.position; int mi = cp.addClassInfo(methodClassname); int methodref = cp.addMethodrefInfo(mi, methodName, signature); iterator.writeByte(INVOKESTATIC, pos); iterator.write16bit(methodref, pos + 1); if (castType != null) { int index = cp.addClassInfo(castType); iterator.writeByte(CHECKCAST, pos + 3); iterator.write16bit(index, pos + 4); } pos = updatePos(pos, gap.length); } return pos; } private String getMethodName(int opcode) { String methodName = null; switch (opcode) { case AALOAD: methodName = names.objectRead(); break; case BALOAD: methodName = names.byteOrBooleanRead(); break; case CALOAD: methodName = names.charRead(); break; case DALOAD: methodName = names.doubleRead(); break; case FALOAD: methodName = names.floatRead(); break; case IALOAD: methodName = names.intRead(); break; case SALOAD: methodName = names.shortRead(); break; case LALOAD: methodName = names.longRead(); break; case AASTORE: methodName = names.objectWrite(); break; case BASTORE: methodName = names.byteOrBooleanWrite(); break; case CASTORE: methodName = names.charWrite(); break; case DASTORE: methodName = names.doubleWrite(); break; case FASTORE: methodName = names.floatWrite(); break; case IASTORE: methodName = names.intWrite(); break; case SASTORE: methodName = names.shortWrite(); break; case LASTORE: methodName = names.longWrite(); break; } if (methodName.equals("")) methodName = null; return methodName; } private String getLoadReplacementSignature(int opcode) throws BadBytecode { switch (opcode) { case AALOAD: return "(Ljava/lang/Object;I)Ljava/lang/Object;"; case BALOAD: return "(Ljava/lang/Object;I)B"; case CALOAD: return "(Ljava/lang/Object;I)C"; case DALOAD: return "(Ljava/lang/Object;I)D"; case FALOAD: return "(Ljava/lang/Object;I)F"; case IALOAD: return "(Ljava/lang/Object;I)I"; case SALOAD: return "(Ljava/lang/Object;I)S"; case LALOAD: return "(Ljava/lang/Object;I)J"; } throw new BadBytecode(opcode); } private String getStoreReplacementSignature(int opcode) throws BadBytecode { switch (opcode) { case AASTORE: return "(Ljava/lang/Object;ILjava/lang/Object;)V"; case BASTORE: return "(Ljava/lang/Object;IB)V"; case CASTORE: return "(Ljava/lang/Object;IC)V"; case DASTORE: return "(Ljava/lang/Object;ID)V"; case FASTORE: return "(Ljava/lang/Object;IF)V"; case IASTORE: return "(Ljava/lang/Object;II)V"; case SASTORE: return "(Ljava/lang/Object;IS)V"; case LASTORE: return "(Ljava/lang/Object;IJ)V"; } throw new BadBytecode(opcode); } }
package com.hk.lua; class LuaBody extends LuaBlock { private final String func; LuaBody(LuaStatement[] sts, String source, String func) { super(sts, source); this.func = func; } Object execute(LuaInterpreter interp, Environment fenv, String[] argNames, LuaObject[] args) { Environment env = interp.env; interp.env = new Environment(interp, fenv, false);//func != null); if(argNames.length > 0 && argNames[argNames.length - 1] == null) { int i; for(i = 0; i < argNames.length - 1; i++) interp.env.setLocal(argNames[i], i < args.length ? args[i] : LuaNil.NIL); if(args.length >= argNames.length) { LuaObject[] tmp = new LuaObject[args.length - argNames.length + 1]; for(int j = 0; j < tmp.length; j++) tmp[j] = args[i + j]; interp.env.varargs = new LuaArgs(tmp); } else interp.env.varargs = LuaNil.NIL; } else { for(int i = 0; i < Math.min(args.length, argNames.length); i++) interp.env.setLocal(argNames[i], args[i]); } Object res = run(interp); interp.env = env; return res; } /** {@inheritDoc} */ protected LuaException exception(LuaStatement st, LuaException e) { if(func != null) { new LuaException(source, st.line, "in function '" + func + "'", e); e.internal = false; return e; } else return super.exception(st, e); } }
package org.wso2.developerstudio.datamapper.diagram.preferences; import org.eclipse.gmf.runtime.diagram.ui.preferences.AppearancePreferencePage; import org.wso2.developerstudio.datamapper.diagram.part.DataMapperDiagramEditorPlugin; /** * @generated */ public class DiagramAppearancePreferencePage extends AppearancePreferencePage { /** * @generated */ public DiagramAppearancePreferencePage() { setPreferenceStore(DataMapperDiagramEditorPlugin.getInstance().getPreferenceStore()); } }
package com.example.daily.common; /** * @author: zhiyuan * @date: 2017年12月5日 * @project: spring-boot-demo * @description: */ public enum Color { RED("红色", "0001"), GREEN("绿色", "0002"), BLANK("白色", "0003"), YELLO("黄色", "0004"); // 成员变量 private String name; private String code; // 构造方法 private Color(String name, String code) { this.name = name; this.code = code; } // 普通方法 public String getName() { // 完全没必要,因为每个枚举对象就是一个实例 for (Color c : Color.values()) { if (c == this) { return c.name; } } return null; } /** * * @return */ public String getCode() { for (Color c : Color.values()) { if (c == this) { return c.code; } } return null; } }
package mg.news.service; import lombok.AllArgsConstructor; import mg.news.util.RadiotUrlBuilder; import mg.utils.JSONConsumer; import mg.utils.JSONHelper; import org.json.JSONArray; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional @AllArgsConstructor public class RadiotExternalApiService { private static final int NUMBER_OF_ARTICLES_TO_FETCH = 100; private final JSONConsumer jsonConsumer; private final RadiotUrlBuilder radiotUrlBuilder; public JSONArray fetchArticles() { return jsonConsumer.getJsonArray(radiotUrlBuilder.buildNewsUrl(NUMBER_OF_ARTICLES_TO_FETCH)); } public JSONArray fetchPodcasts() { return jsonConsumer.getJsonArray(radiotUrlBuilder.buildPodcastUrl()); } }
package com.company.eshop.domain; import java.io.Serializable; public class OpinionPK implements Serializable{ private static final long serialVersionUID = 1L; private int opinionId; public int getOpinionId() { return opinionId; } public void setOpinionId(int opinionId) { this.opinionId = opinionId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + opinionId; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof OpinionPK)) return false; OpinionPK other = (OpinionPK) obj; if (opinionId != other.opinionId) return false; return true; } }
package com.example.gpc1.datamodel; public class DataModel1 { private int id; private String timestamp; private String result; public DataModel1(String timestamp, String result) { this.timestamp = timestamp; this.result = result; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } }
package com.tg.tgt.ui; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.text.InputFilter; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.hyphenate.EMCallBack; import com.hyphenate.easeui.utils.PhoneUtil; import com.hyphenate.easeui.widget.EaseTitleBar; import com.jakewharton.rxbinding2.view.RxView; import com.tg.tgt.ActMgrs; import com.tg.tgt.App; import com.tg.tgt.Constant; import com.tg.tgt.DemoHelper; import com.tg.tgt.R; import com.tg.tgt.http.ApiManger2; import com.tg.tgt.http.BaseObserver2; import com.tg.tgt.http.EmptyData; import com.tg.tgt.http.HttpResult; import com.tg.tgt.http.model2.NonceBean; import com.tg.tgt.logger.Logger; import com.tg.tgt.utils.CodeUtils; import com.tg.tgt.utils.RSAHandlePwdUtil; import com.tg.tgt.utils.ToastUtils; import java.util.concurrent.TimeUnit; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; /** * * @author yiyang */ public class UpdatePwdAct extends BaseActivity{ private Button confirm; private android.widget.EditText etoldpwd; private android.widget.EditText etnewpwd; private android.widget.EditText etrepwd; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_update_pwd); this.confirm = (Button) findViewById(R.id.confirm); this.etrepwd = (EditText) findViewById(R.id.et_re_pwd); this.etnewpwd = (EditText) findViewById(R.id.et_new_pwd); this.etoldpwd = (EditText) findViewById(R.id.et_old_pwd); etrepwd.setFilters(new InputFilter[]{CodeUtils.fil}); etnewpwd.setFilters(new InputFilter[]{CodeUtils.fil}); etoldpwd.setFilters(new InputFilter[]{CodeUtils.filter}); EaseTitleBar titleb = (EaseTitleBar) findViewById(R.id.title_bar); titleb.setLeftLayoutClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); // confirm.setOnClickListener(this); RxView.clicks(confirm) .throttleFirst(1, TimeUnit.SECONDS) .subscribeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<Object>() { @Override public void accept(@NonNull Object o) throws Exception { confirm(); } }); } public void confirm() { // rePwdSuccess(); // if(true) // return; final String oldPwd = etoldpwd.getText().toString(); // String stringValue = SharedPreStorageMgr.getIntance().getStringValue(this, Constant.PWD); // Logger.d(oldPwd+":"+stringValue); String newPwd = etnewpwd.getText().toString(); final String rePwd = etrepwd.getText().toString(); if(TextUtils.isEmpty(oldPwd)){ ToastUtils.showToast(getApplicationContext(), R.string.old_cannot_be_empty); return; }if(TextUtils.isEmpty(newPwd)){ ToastUtils.showToast(getApplicationContext(), R.string.new_pwd_cannot_be_empty); return; }else if(TextUtils.isEmpty(rePwd)){ ToastUtils.showToast(getApplicationContext(), R.string.Confirm_password_cannot_be_empty); return; }else if( newPwd.length()<6){ ToastUtils.showToast(App.applicationContext, R.string.register_editpassword); return; }else if(!rePwd.equals(newPwd)){ ToastUtils.showToast(App.applicationContext, R.string.re_pwd_wrong); return; } if(oldPwd.equals(newPwd)){ ToastUtils.showToast(getApplicationContext(), R.string.ti); return; } ApiManger2.getApiService() .servernonce(Constant.MYUID) .compose(this.<HttpResult<NonceBean>>bindToLifeCyclerAndApplySchedulers(null)) .subscribe(new BaseObserver2<NonceBean>() { @Override protected void onSuccess(NonceBean emptyData) { Log.i("dcz",emptyData.getValue()); setdata(RSAHandlePwdUtil.jia(oldPwd+"#"+emptyData.getValue()),RSAHandlePwdUtil.jia(rePwd+"#"+emptyData.getValue()),emptyData.getKey()); } }); /*ApiManger.getApiService() .rePwd(App.getMyUid(), rePwd) .compose(RxUtils.<BaseHttpResult>applySchedulers()) .subscribe(new BaseObserver<BaseHttpResult>(this) { @Override protected void onSuccess(BaseHttpResult result) { SharedPreStorageMgr.getIntance().saveStringValue(App.applicationContext,Constant.PWD, rePwd); rePwdSuccess(); } });*/ } private void setdata(String oldPwd,String rePwd,String nonce){ ApiManger2.getApiService() .modifyPassword(oldPwd,rePwd,nonce) .compose(this.<HttpResult<EmptyData>>bindToLifeCyclerAndApplySchedulers()) .subscribe(new BaseObserver2<EmptyData>() { @Override protected void onSuccess(EmptyData emptyData) { rePwdSuccess(); } }); } private void layout(){ DemoHelper.getInstance().logout(false,new EMCallBack() { @Override public void onSuccess() { runOnUiThread(new Runnable() { @Override public void run() { ActMgrs.getActManager().popAllActivity(); Intent intent = new Intent(mActivity, LoginActivity.class); startActivity(intent); } }); } @Override public void onProgress(int progress, String status) { } @Override public void onError(int code, String message) { runOnUiThread(new Runnable() { @Override public void run() { dismissProgress(); Toast.makeText(App.applicationContext, "unbind devicetokens failed", Toast.LENGTH_SHORT).show(); } }); } }); } private void rePwdSuccess() { View successView = LayoutInflater.from(this).inflate(R.layout.dialog_update_pwd_success, null); final Dialog dialog = new Dialog(this, R.style.DialogTranslucentStyle); dialog.setContentView(successView, new ViewGroup.LayoutParams(/*(int) (PhoneUtil.getScreenWidth(this) * 0.82)*/ViewGroup.LayoutParams.WRAP_CONTENT, (int) (PhoneUtil.getScreenHeight(this) * 0.58))); dialog.setCancelable(false); //设置dialog位置 Window window = dialog.getWindow(); window.setGravity(Gravity.TOP); dialog.show(); final TextView backTimeTv = (TextView) successView.findViewById(R.id.back_time); successView.findViewById(R.id.backButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); layout(); } }); final int s = 3; Observable.interval(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread()) .take(s) .subscribe(new Observer<Long>() { @Override public void onSubscribe(@NonNull Disposable d) { // clearDisposabl(); // addRxDestroy(d); UpdatePwdAct.this.d = d; } @Override public void onNext(@NonNull Long aLong) { Logger.d(aLong); backTimeTv.setText(s-1-aLong.intValue()+"s"); } @Override public void onError(@NonNull Throwable e) { e.printStackTrace(); dialog.dismiss(); finish(); } @Override public void onComplete() { dialog.dismiss(); layout(); } }); // addRxDestroy(Observable.interval(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread()) //// .delay(1, TimeUnit.SECONDS) // .take(s) // .doOnTerminate(new Action() { // @Override // public void run() throws Exception { // dialog.dismiss(); // finish(); // } // }) // .subscribe(new Consumer<Long>() { // @Override // public void accept(@NonNull Long aLong) throws Exception { // backTimeTv.setText(s-1-aLong.intValue()+"s"); // } // })); } public Disposable d; @Override protected void onDestroy() { if(d != null){ d.dispose(); } super.onDestroy(); } }
package com.yahtzee.core; public class Globals { public static final int MAX_PLAYERS = 3; public static final int MAX_ROLLS = 3; public static final int MAX_ROUNDS = 13; public static final int UPPER_SECTION_BONUS_SCORE = 35; public static final int FULL_HOUSE_SCORE = 25; public static final int SMALL_STRAIGHT_SCORE = 30; public static final int LARGE_STRAIGHT_SCORE = 40; public static final int YAHTZEE_SCORE = 50; public static final int YAHTZEE_BONUS_SCORE = 100; }
/* * Copyright (C) 2011 The Android Open Source Project * Copyright (C) 2014 kaytat * * 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.kaytat.simpleprotocolplayer; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioTrack; import android.os.Handler; import android.util.Log; import android.widget.Toast; import java.util.concurrent.ArrayBlockingQueue; /** * group everything belongs a stream together,makes multi stream easier * including NetworkReadThread BufferToAudioTrackThread and AudioTrack */ public class WorkerThreadPair { private static final String TAG = WorkerThreadPair.class.getSimpleName(); private final BufferToAudioTrackThread audioThread; private final NetworkReadThread networkThread; final AudioTrack mTrack; public WorkerThreadPair( MusicService musicService, String serverAddr, int serverPort, int sample_rate, boolean stereo, int buffer_ms, boolean retry) { this.musicService = musicService; int format = stereo ? AudioFormat.CHANNEL_OUT_STEREO : AudioFormat.CHANNEL_OUT_MONO; // Sanitize input, just in case if (sample_rate <= 0) { sample_rate = MusicService.DEFAULT_SAMPLE_RATE; } if (buffer_ms <= 5) { buffer_ms = MusicService.DEFAULT_BUFFER_MS; } int minBuf = AudioTrack.getMinBufferSize(sample_rate, format, AudioFormat.ENCODING_PCM_16BIT); packet_size = calcPacketSize(sample_rate, stereo, minBuf, buffer_ms); // The agreement here is that mTrack will be shutdown by the helper mTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sample_rate, format, AudioFormat.ENCODING_PCM_16BIT, minBuf, AudioTrack.MODE_STREAM); audioThread = new BufferToAudioTrackThread(this, "audio:" + serverAddr + ":" + serverPort); networkThread = new NetworkReadThread(this, serverAddr, serverPort, retry, "net:" + serverAddr + ":" + serverPort); audioThread.start(); networkThread.start(); } static int calcPacketSize(int sample_rate, boolean stereo, int minBuf, int buffer_ms) { // Assume 16 bits per sample int bytesPerSecond = sample_rate * 2; if (stereo) { bytesPerSecond *= 2; } int result = (bytesPerSecond * buffer_ms) / 1000; if ((result & 1) != 0) { result++; } Log.d(TAG, "initNetworkData:bytes / second:" + (bytesPerSecond)); Log.d(TAG, "initNetworkData:minBuf:" + minBuf); Log.d(TAG, "initNetworkData:packet_size:" + result); return result; } static public final int NUM_PACKETS = 3; // The amount of data to read from the network before sending to AudioTrack final int packet_size; final ArrayBlockingQueue<byte[]> dataQueue = new ArrayBlockingQueue<>( NUM_PACKETS); public void stopAndInterrupt() { for (ThreadStoppable it : new ThreadStoppable[]{audioThread, networkThread}) { try { it.customStop(); it.interrupt(); // Do not join since this can take some time. The // workers should be able to shutdown independently. // t.join(); } catch (Exception e) { Log.e(TAG, "join exception:" + e); } } } private final MusicService musicService; public void brokenShutdown() { // Broke out of loop unexpectedly. Shutdown. Handler h = new Handler(musicService.getMainLooper()); Runnable r = () -> { Toast.makeText(musicService.getApplicationContext(), "Unable to stream", Toast.LENGTH_SHORT).show(); musicService.processStopRequest(); }; h.post(r); } }
/* * MIT License * * Copyright (c) ReformCloud-Team * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package systems.reformcloud.reformcloud2.executor.api.common.groups.template.backend; import org.jetbrains.annotations.NotNull; import systems.reformcloud.reformcloud2.executor.api.common.groups.ProcessGroup; import systems.reformcloud.reformcloud2.executor.api.common.groups.template.Template; import systems.reformcloud.reformcloud2.executor.api.common.utility.name.Nameable; import systems.reformcloud.reformcloud2.executor.api.common.utility.task.Task; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; /** * Represents a template backend which manages the template for all groups */ public interface TemplateBackend extends Nameable { /** * Checks if the specified template for the group exists * * @param group The group of which the template should be * @param template The name of the template which should get checked * @return If the specified template exists in the group */ boolean existsTemplate(@NotNull String group, @NotNull String template); /** * Creates a new template for the group * * @param group The name of the group the template should be for * @param template The name of the template which should get created */ void createTemplate(@NotNull String group, @NotNull String template); /** * Loads a template from a group to the specified path * * @param group The group name of the group in which the template is located * @param template The name of the template which should get loaded * @param target The path the template should get copied to * @return A task which will get completed after the successful template copy to the path */ @NotNull Task<Void> loadTemplate(@NotNull String group, @NotNull String template, @NotNull Path target); /** * Loads all global templates from the specified group * * @param group The group in which the template is located * @param target The path the global template(s) should get copied to * @return A task which will get completed when all templates are copied * @see Template#isGlobal() */ @NotNull Task<Void> loadGlobalTemplates(@NotNull ProcessGroup group, @NotNull Path target); /** * Loads a specific path * * @param path The path which should get loaded * @param target The target path to which the specified path should get copied * @return A task which get completed after the successful copy */ @NotNull Task<Void> loadPath(@NotNull String path, @NotNull Path target); /** * Deploys the specified template of the specified group from the current operating path * * @param group The group in which the template is located * @param template The name of the template which should get deployed * @param current The current operating path which should get deployed */ default void deployTemplate(@NotNull String group, @NotNull String template, @NotNull Path current) { this.deployTemplate(group, template, current, new ArrayList<>()); } /** * Deploys the specified template of the specified group from the current operating path * * @param group The group in which the template is located * @param template The name of the template which should get deployed * @param current The current operating path which should get deployed * @param excluded The file names of the excluded files which should not get deployed */ void deployTemplate(@NotNull String group, @NotNull String template, @NotNull Path current, @NotNull Collection<String> excluded); /** * Deletes the specified template * * @param group The name of the group the template is located in * @param template The name of the template which should get deleted */ void deleteTemplate(@NotNull String group, @NotNull String template); }
// // ======================================================================== // Copyright (c) 1995-2020 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.websocket.common; import java.io.IOException; import java.util.Collections; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import org.eclipse.jetty.util.component.AbstractLifeCycle; import org.eclipse.jetty.util.component.Dumpable; import org.eclipse.jetty.util.component.LifeCycle; public class SessionTracker extends AbstractLifeCycle implements WebSocketSessionListener, Dumpable { private CopyOnWriteArraySet<WebSocketSession> sessions = new CopyOnWriteArraySet<>(); public Set<WebSocketSession> getSessions() { return Collections.unmodifiableSet(sessions); } @Override public void onSessionCreated(WebSocketSession session) { LifeCycle.start(session); sessions.add(session); } @Override public void onSessionClosed(WebSocketSession session) { sessions.remove(session); LifeCycle.stop(session); } @Override protected void doStop() throws Exception { for (WebSocketSession session : sessions) { LifeCycle.stop(session); } super.doStop(); } @Override public void dump(Appendable out, String indent) throws IOException { Dumpable.dumpObjects(out, indent, this, sessions); } }
/* * Copyright (C) 2019 Lightbend Inc. <https://www.lightbend.com> */ package jdoc.akka.serialization.jackson.v2a; import com.fasterxml.jackson.annotation.JsonCreator; import jdoc.akka.serialization.jackson.MySerializable; import java.util.Optional; // #add-optional public class ItemAdded implements MySerializable { public final String shoppingCartId; public final String productId; public final int quantity; public final Optional<Double> discount; public final String note; @JsonCreator public ItemAdded( String shoppingCartId, String productId, int quantity, Optional<Double> discount, String note) { this.shoppingCartId = shoppingCartId; this.productId = productId; this.quantity = quantity; this.discount = discount; // default for note is "" if not included in json if (note == null) this.note = ""; else this.note = note; } public ItemAdded( String shoppingCartId, String productId, int quantity, Optional<Double> discount) { this(shoppingCartId, productId, quantity, discount, ""); } } // #add-optional
/* * 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.accumulo.master.tableOps; import static org.junit.Assert.assertEquals; import org.apache.accumulo.master.Master; import org.apache.accumulo.server.ServerConstants; import org.apache.accumulo.server.fs.VolumeManager; import org.easymock.EasyMock; import org.gaul.modernizer_maven_annotations.SuppressModernizer; import org.junit.Test; import com.google.common.base.Optional; /** * */ @SuppressModernizer public class ImportTableTest { @Test public void testTabletDir() { Master master = EasyMock.createMock(Master.class); VolumeManager volumeManager = EasyMock.createMock(VolumeManager.class); ImportedTableInfo iti = new ImportedTableInfo(); iti.tableId = "5"; // Different volumes with different paths String[] volumes = new String[] {"hdfs://nn1:8020/apps/accumulo1", "hdfs://nn2:8020/applications/accumulo"}; // This needs to be unique WRT the importtable command String tabletDir = "/c-00000001"; EasyMock.expect(master.getFileSystem()).andReturn(volumeManager); // Choose the 2nd element EasyMock.expect(volumeManager.choose(Optional.of(iti.tableId), volumes)).andReturn(volumes[1]); EasyMock.replay(master, volumeManager); PopulateMetadataTable pmt = new PopulateMetadataTable(iti); assertEquals(volumes[1] + "/" + ServerConstants.TABLE_DIR + "/" + iti.tableId + "/" + tabletDir, pmt.getClonedTabletDir(master, volumes, tabletDir)); EasyMock.verify(master, volumeManager); } }
package cz.habarta.typescript.generator.parser; import cz.habarta.typescript.generator.ExcludingTypeProcessor; import cz.habarta.typescript.generator.OptionalProperties; import cz.habarta.typescript.generator.Settings; import cz.habarta.typescript.generator.TypeProcessor; import cz.habarta.typescript.generator.util.Pair; import cz.habarta.typescript.generator.util.PropertyMember; import cz.habarta.typescript.generator.util.Utils; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.json.bind.annotation.JsonbCreator; import javax.json.bind.annotation.JsonbProperty; import javax.json.bind.annotation.JsonbTransient; import javax.json.bind.annotation.JsonbVisibility; import javax.json.bind.config.PropertyNamingStrategy; import javax.json.bind.config.PropertyVisibilityStrategy; // simplified+dependency free version of apache johnzon JsonbAccessMode public class JsonbParser extends ModelParser { private final Class<? extends Annotation> johnzonAny; public static class Factory extends ModelParser.Factory { @Override public TypeProcessor getSpecificTypeProcessor() { return new ExcludingTypeProcessor(Collections.emptyList()); } @Override public JsonbParser create(Settings settings, TypeProcessor commonTypeProcessor, List<RestApplicationParser> restApplicationParsers) { return new JsonbParser(settings, commonTypeProcessor, restApplicationParsers); } } public JsonbParser(Settings settings, TypeProcessor commonTypeProcessor) { this(settings, commonTypeProcessor, Collections.emptyList()); } public JsonbParser(Settings settings, TypeProcessor commonTypeProcessor, List<RestApplicationParser> restApplicationParsers) { super(settings, commonTypeProcessor, restApplicationParsers); johnzonAny = loadJohnzonAnyClass(); } @SuppressWarnings("unchecked") private Class<? extends Annotation> loadJohnzonAnyClass() { try { return (Class<? extends Annotation>) settings.classLoader .loadClass("org.apache.johnzon.mapper.JohnzonAny"); } catch (ClassNotFoundException e) { return null; } } @Override protected DeclarationModel parseClass(final SourceType<Class<?>> sourceClass) { if (sourceClass.type.isEnum()) { return ModelParser.parseEnum(sourceClass); } else { return parseBean(sourceClass); } } // simplistic impl handling @JsonbProperty and @JsonbTransient on fields private BeanModel parseBean(final SourceType<Class<?>> sourceClass) { final JsonbPropertyExtractor extractor = createExtractor(); final List<PropertyModel> properties = extractor.visit(sourceClass.type); final Type superclass = sourceClass.type.getGenericSuperclass() == Object.class ? null : sourceClass.type.getGenericSuperclass(); if (superclass != null) { addBeanToQueue(new SourceType<>(superclass, sourceClass.type, "<superClass>")); } final List<Type> interfaces = Arrays.asList(sourceClass.type.getGenericInterfaces()); for (Type aInterface : interfaces) { addBeanToQueue(new SourceType<>(aInterface, sourceClass.type, "<interface>")); } return new BeanModel( sourceClass.type, superclass, null, null, null, interfaces, properties, null); } private JsonbPropertyExtractor createExtractor() { return new JsonbPropertyExtractor( johnzonAny, new PropertyNamingStrategyFactory(Optional.ofNullable(settings.jsonbConfiguration).map(c -> c.namingStrategy).orElse("IDENTITY")).create(), new DefaultPropertyVisibilityStrategy(settings.classLoader), new FieldAndMethodAccessMode(johnzonAny)); } private class JsonbPropertyExtractor { private final Class<? extends Annotation> johnzonAny; private final PropertyNamingStrategy naming; private final PropertyVisibilityStrategy visibility; private final BaseAccessMode delegate; private JsonbPropertyExtractor( final Class<? extends Annotation> johnzonAny, final PropertyNamingStrategy propertyNamingStrategy, final PropertyVisibilityStrategy visibilityStrategy, final BaseAccessMode delegate) { this.johnzonAny = johnzonAny; this.naming = propertyNamingStrategy; this.visibility = visibilityStrategy; this.delegate = delegate; } private List<PropertyModel> visit(final Class<?> clazz) { return Stream.of(clazz.getConstructors()) .filter(it -> it.isAnnotationPresent(JsonbCreator.class)) .findFirst() .map(it -> new ArrayList<>(Stream.concat(visitConstructor(it), visitClass(clazz).stream()) .collect(Collectors.toMap(PropertyModel::getName, Function.identity(), (a, b) -> a)) // merge models .values())) .orElseGet(() -> new ArrayList<>(visitClass(clazz))); } private Stream<PropertyModel> visitConstructor(final Constructor<?> constructor) { // JSON-B 1.0 assumes all constructor params are required even if impls can diverge on that due // to user feedbacks so for our libraryDefinition let's assume it is true. // only exception is about optional wrappers which can be optional indeed final List<Type> parameterTypes = settings.getTypeParser().getConstructorParameterTypes(constructor); final List<Pair<Parameter, Type>> parameters = Utils.zip(Arrays.asList(constructor.getParameters()), parameterTypes); return parameters.stream() .map(it -> { final Type type = it.getValue2(); final Parameter parameter = it.getValue1(); final Optional<JsonbProperty> property = Optional.ofNullable( parameter.getAnnotation(JsonbProperty.class)); final PropertyMember propertyMember = new PropertyMember( parameter, it.getValue2(), parameter.getAnnotatedType(), parameter::getAnnotation); return JsonbParser.this.processTypeAndCreateProperty( property .map(JsonbProperty::value) .filter(p -> !p.isEmpty()) .orElseGet(parameter::getName), type, null, settings.optionalProperties != OptionalProperties.useLibraryDefinition ? isPropertyOptional(propertyMember) : (isOptional(type) || OptionalInt.class == type || OptionalLong.class == type || OptionalDouble.class == type || property.map(JsonbProperty::nillable).orElse(false)), constructor.getDeclaringClass(), new ParameterMember(parameter), null, null); }); } private List<PropertyModel> visitClass(final Class<?> clazz) { return delegate.find(clazz).entrySet().stream() .filter(e -> !isTransient(e.getValue(), visibility)) .filter(e -> johnzonAny == null || e.getValue().getAnnotation(johnzonAny) == null) .map(e -> { final DecoratedType decoratedType = e.getValue(); final Member member = findMember(decoratedType); final PropertyMember propertyMember = wrapMember( settings.getTypeParser(), member, decoratedType::getAnnotation, member.getName(), member.getDeclaringClass()); final JsonbProperty property = decoratedType.getAnnotation(JsonbProperty.class); final String key = property == null || property.value().isEmpty() ? naming.translateName(e.getKey()) : property.value(); return JsonbParser.this.processTypeAndCreateProperty( key, Field.class.isInstance(member) ? settings.getTypeParser().getFieldType(Field.class.cast(member)) : settings.getTypeParser().getMethodReturnType(Method.class.cast(member)), null, settings.optionalProperties == OptionalProperties.useLibraryDefinition || JsonbParser.this.isPropertyOptional(propertyMember), clazz, member, null, null); }) .sorted(Comparator.comparing(PropertyModel::getName)) .collect(Collectors.toList()); } private Member findMember(final DecoratedType value) { if (FieldAndMethodAccessMode.CompositeDecoratedType.class.isInstance(value)) { // unwrap to use the right reader final FieldAndMethodAccessMode.CompositeDecoratedType<?> decoratedType = FieldAndMethodAccessMode.CompositeDecoratedType.class.cast(value); final DecoratedType type1 = decoratedType.getType1(); final DecoratedType type2 = decoratedType.getType2(); if (FieldAccessMode.FieldDecoratedType.class.isInstance(type1)) { return findMember(type1); } return findMember(type2); } else if (JsonbParser.FieldAccessMode.FieldDecoratedType.class.isInstance(value)){ return JsonbParser.FieldAccessMode.FieldDecoratedType.class.cast(value).getField(); } else if (MethodAccessMode.MethodDecoratedType.class.isInstance(value)){ return MethodAccessMode.MethodDecoratedType.class.cast(value).getMethod(); } throw new IllegalArgumentException("Unsupported reader: " + value); } private Type findOptionalType(final Type writerType) { return ParameterizedType.class.cast(writerType).getActualTypeArguments()[0]; } private boolean isOptional(final Type type) { return ParameterizedType.class.isInstance(type) && Optional.class == ParameterizedType.class.cast(type).getRawType(); } private boolean isOptionalArray(final Type value) { return GenericArrayType.class.isInstance(value) && isOptional(GenericArrayType.class.cast(value).getGenericComponentType()); } private boolean isTransient(final JsonbParser.DecoratedType dt, final PropertyVisibilityStrategy visibility) { if (!FieldAndMethodAccessMode.CompositeDecoratedType.class.isInstance(dt)) { return isTransient(dt) || shouldSkip(visibility, dt); } final FieldAndMethodAccessMode.CompositeDecoratedType<?> cdt = FieldAndMethodAccessMode.CompositeDecoratedType.class.cast(dt); return isTransient(cdt.getType1()) || isTransient(cdt.getType2()) || (shouldSkip(visibility, cdt.getType1()) && shouldSkip(visibility, cdt.getType2())); } private boolean shouldSkip(final PropertyVisibilityStrategy visibility, final JsonbParser.DecoratedType t) { return isNotVisible(visibility, t); } private boolean isTransient(final JsonbParser.DecoratedType t) { if (t.getAnnotation(JsonbTransient.class) != null) { return true; } if (JsonbParser.FieldAccessMode.FieldDecoratedType.class.isInstance(t)) { final Field field = JsonbParser.FieldAccessMode.FieldDecoratedType.class.cast(t).getField(); return Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers()); } return false; } private boolean isNotVisible(final PropertyVisibilityStrategy visibility, final JsonbParser.DecoratedType t) { return !(JsonbParser.FieldAccessMode.FieldDecoratedType.class.isInstance(t) ? visibility.isVisible(JsonbParser.FieldAccessMode.FieldDecoratedType.class.cast(t).getField()) : (MethodAccessMode.MethodDecoratedType.class.isInstance(t) && visibility.isVisible(MethodAccessMode.MethodDecoratedType.class.cast(t).getMethod()))); } } private interface DecoratedType { Type getType(); <T extends Annotation> T getAnnotation(Class<T> clazz); <T extends Annotation> T getClassOrPackageAnnotation(Class<T> clazz); } private interface BaseAccessMode { Map<String, JsonbParser.DecoratedType> find(Class<?> clazz); } private static class FieldAccessMode implements BaseAccessMode { private final Class<? extends Annotation> johnzonAny; public FieldAccessMode(final Class<? extends Annotation> johnzonAny) { this.johnzonAny = johnzonAny; } @Override public Map<String, JsonbParser.DecoratedType> find(final Class<?> clazz) { final Map<String, JsonbParser.DecoratedType> readers = new HashMap<>(); for (final Map.Entry<String, Field> f : fields(clazz, true).entrySet()) { final String key = f.getKey(); if (isIgnored(key) || (johnzonAny != null && Meta.getAnnotation(f.getValue(), johnzonAny) != null)) { continue; } final Field field = f.getValue(); readers.put(key, new FieldDecoratedType(field, field.getGenericType())); } return readers; } protected boolean isIgnored(final String key) { return key.contains("$"); } protected Map<String, Field> fields(final Class<?> clazz, final boolean includeFinalFields) { final Map<String, Field> fields = new HashMap<>(); Class<?> current = clazz; while (current != null && current != Object.class) { for (final Field f : current.getDeclaredFields()) { final String name = f.getName(); final int modifiers = f.getModifiers(); if (fields.containsKey(name) || Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers) || (!includeFinalFields && Modifier.isFinal(modifiers))) { continue; } fields.put(name, f); } current = current.getSuperclass(); } return fields; } private static class FieldDecoratedType implements JsonbParser.DecoratedType { protected final Field field; protected final Type type; public FieldDecoratedType(final Field field, final Type type) { this.field = field; this.field.setAccessible(true); this.type = type; } @Override public <T extends Annotation> T getClassOrPackageAnnotation(final Class<T> clazz) { return Meta.getClassOrPackageAnnotation(field, clazz); } public Field getField() { return field; } @Override public Type getType() { return type; } @Override public <T extends Annotation> T getAnnotation(final Class<T> clazz) { return Meta.getAnnotation(field, clazz); } @Override public String toString() { return "FieldDecoratedType{" + "field=" + field + '}'; } } } private static class MethodAccessMode implements BaseAccessMode { private final Class<? extends Annotation> johnzonAny; public MethodAccessMode(final Class<? extends Annotation> johnzonAny) { this.johnzonAny = johnzonAny; } @Override public Map<String, DecoratedType> find(final Class<?> clazz) { final Map<String, DecoratedType> readers = new HashMap<>(); if (Records.isRecord(clazz)) { readers.putAll(Stream.of(clazz.getMethods()) .filter(it -> it.getDeclaringClass() != Object.class && it.getParameterCount() == 0) .filter(it -> !"toString".equals(it.getName()) && !"hashCode".equals(it.getName())) .filter(it -> !isIgnored(it.getName()) && johnzonAny != null && Meta.getAnnotation(it, johnzonAny) == null) .collect(Collectors.toMap(Method::getName, it -> new MethodDecoratedType(it, it.getGenericReturnType()) { }))); } else { final PropertyDescriptor[] propertyDescriptors = getPropertyDescriptors(clazz); for (final PropertyDescriptor descriptor : propertyDescriptors) { final Method readMethod = descriptor.getReadMethod(); final String name = descriptor.getName(); if (readMethod != null && readMethod.getDeclaringClass() != Object.class) { if (isIgnored(name) || johnzonAny != null && Meta.getAnnotation(readMethod, johnzonAny) != null) { continue; } readers.put(name, new MethodDecoratedType(readMethod, readMethod.getGenericReturnType())); } else if (readMethod == null && descriptor.getWriteMethod() != null && // isXXX, not supported by javabeans (descriptor.getPropertyType() == Boolean.class || descriptor.getPropertyType() == boolean.class)) { try { final Method method = clazz.getMethod( "is" + Character.toUpperCase(name.charAt(0)) + (name.length() > 1 ? name.substring(1) : "")); readers.put(name, new MethodDecoratedType(method, method.getGenericReturnType())); } catch (final NoSuchMethodException e) { // no-op } } } } return readers; } protected boolean isIgnored(final String name) { return name.equals("metaClass") || name.contains("$"); } private PropertyDescriptor[] getPropertyDescriptors(final Class<?> clazz) { final PropertyDescriptor[] propertyDescriptors; try { propertyDescriptors = Introspector.getBeanInfo(clazz).getPropertyDescriptors(); } catch (final IntrospectionException e) { throw new IllegalStateException(e); } return propertyDescriptors; } public static class MethodDecoratedType implements DecoratedType { protected final Method method; protected final Type type; public MethodDecoratedType(final Method method, final Type type) { this.method = method; method.setAccessible(true); this.type = type; } @Override public <T extends Annotation> T getClassOrPackageAnnotation(final Class<T> clazz) { return Meta.getClassOrPackageAnnotation(method, clazz); } public Method getMethod() { return method; } @Override public Type getType() { return type; } @Override public <T extends Annotation> T getAnnotation(final Class<T> clazz) { return Meta.getAnnotation(method, clazz); } @Override public String toString() { return "MethodDecoratedType{" + "method=" + method + '}'; } } } private static class FieldAndMethodAccessMode implements BaseAccessMode { private final FieldAccessMode fields; private final MethodAccessMode methods; private FieldAndMethodAccessMode(final Class<? extends Annotation> johnzonAny) { this.fields = new FieldAccessMode(johnzonAny); this.methods = new MethodAccessMode(johnzonAny); } @Override public Map<String, JsonbParser.DecoratedType> find(final Class<?> clazz) { final Map<String, JsonbParser.DecoratedType> methodReaders = this.methods.find(clazz); final boolean record = Records.isRecord(clazz); if (record) { return methodReaders; } final Map<String, JsonbParser.DecoratedType> fieldsReaders = this.fields.find(clazz); final Map<String, JsonbParser.DecoratedType> readers = new HashMap<>(fieldsReaders); for (final Map.Entry<String, JsonbParser.DecoratedType> entry : methodReaders.entrySet()) { final Method mr = MethodAccessMode.MethodDecoratedType.class.cast(entry.getValue()).getMethod(); final String fieldName = record ? mr.getName() : Introspector.decapitalize(mr.getName().startsWith("is") ? mr.getName().substring(2) : mr.getName().substring(3)); final Field f = getField(fieldName, clazz); final JsonbParser.DecoratedType existing = readers.get(entry.getKey()); if (existing == null) { if (f != null) { // useful to hold the Field and transient state for example, just as fallback readers.put(entry.getKey(), new CompositeDecoratedType<>( entry.getValue(), new FieldAccessMode.FieldDecoratedType(f, f.getType()))); } else { readers.put(entry.getKey(), entry.getValue()); } } else { readers.put(entry.getKey(), new CompositeDecoratedType<>(entry.getValue(), existing)); } } return readers; } private Field getField(final String fieldName, final Class<?> type) { Class<?> t = type; while (t != Object.class && t != null) { try { return t.getDeclaredField(fieldName); } catch (final NoSuchFieldException e) { // no-op } t = t.getSuperclass(); } return null; } public static class CompositeDecoratedType<T extends DecoratedType> implements DecoratedType { protected final T type1; protected final T type2; private CompositeDecoratedType(final T type1, final T type2) { this.type1 = type1; this.type2 = type2; } @Override public <A extends Annotation> A getClassOrPackageAnnotation(final Class<A> clazz) { final A found = type1.getClassOrPackageAnnotation(clazz); return found == null ? type2.getClassOrPackageAnnotation(clazz) : found; } @Override public <A extends Annotation> A getAnnotation(final Class<A> clazz) { final A found = type1.getAnnotation(clazz); return found == null ? type2.getAnnotation(clazz) : found; } @Override public Type getType() { return type1.getType(); } public DecoratedType getType1() { return type1; } public DecoratedType getType2() { return type2; } @Override public String toString() { return "CompositeDecoratedType{" + "type1=" + type1 + ", type2=" + type2 + '}'; } } } private static class DefaultPropertyVisibilityStrategy implements PropertyVisibilityStrategy { private final ClassLoader classLoader; private final ConcurrentMap<Class<?>, PropertyVisibilityStrategy> strategies = new ConcurrentHashMap<>(); public DefaultPropertyVisibilityStrategy(ClassLoader classLoader) { this.classLoader = classLoader; } @Override public boolean isVisible(final Field field) { if (field.getAnnotation(JsonbProperty.class) != null) { return true; } final PropertyVisibilityStrategy strategy = strategies.computeIfAbsent( field.getDeclaringClass(), this::visibilityStrategy); return strategy == this ? Modifier.isPublic(field.getModifiers()) : strategy.isVisible(field); } @Override public boolean isVisible(final Method method) { final PropertyVisibilityStrategy strategy = strategies.computeIfAbsent( method.getDeclaringClass(), this::visibilityStrategy); return strategy == this ? Modifier.isPublic(method.getModifiers()) : strategy.isVisible(method); } private PropertyVisibilityStrategy visibilityStrategy(final Class<?> type) { JsonbVisibility visibility = type.getAnnotation(JsonbVisibility.class); if (visibility != null) { try { return visibility.value().getConstructor().newInstance(); } catch (final ReflectiveOperationException e) { throw new IllegalArgumentException(e); } } Package p = type.getPackage(); while (p != null) { visibility = p.getAnnotation(JsonbVisibility.class); if (visibility != null) { try { return visibility.value().getConstructor().newInstance(); } catch (final ReflectiveOperationException e) { throw new IllegalArgumentException(e); } } final String name = p.getName(); final int end = name.lastIndexOf('.'); if (end < 0) { break; } final String parentPack = name.substring(0, end); p = Package.getPackage(parentPack); if (p == null) { try { p = classLoader.loadClass(parentPack + ".package-info").getPackage(); } catch (final ClassNotFoundException e) { // no-op } } } return this; } } private static class PropertyNamingStrategyFactory { private final Object value; public PropertyNamingStrategyFactory(final Object value) { this.value = value; } public PropertyNamingStrategy create() { if (String.class.isInstance(value)) { final String val = value.toString(); switch (val) { case PropertyNamingStrategy.IDENTITY: return propertyName -> propertyName; case PropertyNamingStrategy.LOWER_CASE_WITH_DASHES: return new ConfigurableNamingStrategy(Character::toLowerCase, '-'); case PropertyNamingStrategy.LOWER_CASE_WITH_UNDERSCORES: return new ConfigurableNamingStrategy(Character::toLowerCase, '_'); case PropertyNamingStrategy.UPPER_CAMEL_CASE: return camelCaseStrategy(); case PropertyNamingStrategy.UPPER_CAMEL_CASE_WITH_SPACES: final PropertyNamingStrategy camelCase = camelCaseStrategy(); final PropertyNamingStrategy space = new ConfigurableNamingStrategy(Function.identity(), ' '); return propertyName -> camelCase.translateName(space.translateName(propertyName)); case PropertyNamingStrategy.CASE_INSENSITIVE: return propertyName -> propertyName; default: throw new IllegalArgumentException(val + " unknown as PropertyNamingStrategy"); } } if (PropertyNamingStrategy.class.isInstance(value)) { return PropertyNamingStrategy.class.cast(value); } throw new IllegalArgumentException(value + " not supported as PropertyNamingStrategy"); } private PropertyNamingStrategy camelCaseStrategy() { return propertyName -> Character.toUpperCase(propertyName.charAt(0)) + (propertyName.length() > 1 ? propertyName.substring(1) : ""); } private static class ConfigurableNamingStrategy implements PropertyNamingStrategy { private final Function<Character, Character> converter; private final char separator; public ConfigurableNamingStrategy(final Function<Character, Character> wordConverter, final char sep) { this.converter = wordConverter; this.separator = sep; } @Override public String translateName(final String propertyName) { final StringBuilder global = new StringBuilder(); final StringBuilder current = new StringBuilder(); for (int i = 0; i < propertyName.length(); i++) { final char c = propertyName.charAt(i); if (Character.isUpperCase(c)) { final char transformed = converter.apply(c); if (current.length() > 0) { global.append(current).append(separator); current.setLength(0); } current.append(transformed); } else { current.append(c); } } if (current.length() > 0) { global.append(current); } else { global.setLength(global.length() - 1); // remove last sep } return global.toString(); } } } private static class Records { private static final Method IS_RECORD; static { Method isRecord = null; try { isRecord = Class.class.getMethod("isRecord"); } catch (final NoSuchMethodException e) { // no-op } IS_RECORD = isRecord; } private Records() { // no-op } public static boolean isRecord(final Class<?> clazz) { try { return IS_RECORD != null && Boolean.class.cast(IS_RECORD.invoke(clazz)); } catch (final InvocationTargetException | IllegalAccessException e) { return false; } } } private static final class Meta { private Meta() { // no-op } private static <T extends Annotation> T getAnnotation(final AnnotatedElement holder, final Class<T> api) { return getDirectAnnotation(holder, api); } private static <T extends Annotation> T getClassOrPackageAnnotation(final Method holder, final Class<T> api) { return getIndirectAnnotation(api, holder::getDeclaringClass, () -> holder.getDeclaringClass().getPackage()); } private static <T extends Annotation> T getClassOrPackageAnnotation(final Field holder, final Class<T> api) { return getIndirectAnnotation(api, holder::getDeclaringClass, () -> holder.getDeclaringClass().getPackage()); } private static <T extends Annotation> T getDirectAnnotation(final AnnotatedElement holder, final Class<T> api) { final T annotation = holder.getAnnotation(api); if (annotation != null) { return annotation; } return findMeta(holder.getAnnotations(), api); } private static <T extends Annotation> T getIndirectAnnotation(final Class<T> api, final Supplier<Class<?>> ownerSupplier, final Supplier<Package> packageSupplier) { final T ownerAnnotation = ownerSupplier.get().getAnnotation(api); if (ownerAnnotation != null) { return ownerAnnotation; } final Package pck = packageSupplier.get(); if (pck != null) { return pck.getAnnotation(api); } return null; } public static <T extends Annotation> T findMeta(final Annotation[] annotations, final Class<T> api) { for (final Annotation a : annotations) { final Class<? extends Annotation> userType = a.annotationType(); final T aa = userType.getAnnotation(api); if (aa != null) { boolean overriden = false; final Map<String, Method> mapping = new HashMap<String, Method>(); for (final Class<?> cm : Arrays.asList(api, userType)) { for (final Method m : cm.getMethods()) { overriden = mapping.put(m.getName(), m) != null || overriden; } } if (!overriden) { return aa; } return api.cast(newAnnotation(mapping, a, aa)); } } return null; } @SuppressWarnings("unchecked") private static <T extends Annotation> T newAnnotation(final Map<String, Method> methodMapping, final Annotation user, final T johnzon) { return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{johnzon.annotationType()}, (proxy, method, args) -> { final Method m = methodMapping.get(method.getName()); try { if (m.getDeclaringClass() == user.annotationType()) { return m.invoke(user, args); } return m.invoke(johnzon, args); } catch (final InvocationTargetException ite) { throw ite.getTargetException(); } }); } } private static class ParameterMember implements Member, AnnotatedElement { private final Parameter parameter; public ParameterMember(final Parameter parameter) { this.parameter = parameter; } @Override public Class<?> getDeclaringClass() { return parameter.getDeclaringExecutable().getDeclaringClass(); } @Override public String getName() { return parameter.getName(); } @Override public int getModifiers() { return parameter.getModifiers(); } @Override public boolean isSynthetic() { return parameter.isSynthetic(); } @Override public <T extends Annotation> T getAnnotation(final Class<T> type) { return parameter.getAnnotation(type); } @Override public Annotation[] getAnnotations() { return parameter.getAnnotations(); } @Override public Annotation[] getDeclaredAnnotations() { return parameter.getDeclaredAnnotations(); } } }
/* * Copyright 2000-2016 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.openapi.vfs.newvfs.impl; import com.intellij.openapi.application.ApplicationAdapter; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.vfs.InvalidVirtualFileAccessException; import com.intellij.openapi.vfs.newvfs.NewVirtualFileSystem; import com.intellij.openapi.vfs.newvfs.persistent.FSRecords; import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS; import com.intellij.openapi.vfs.newvfs.persistent.PersistentFSImpl; import com.intellij.util.ArrayUtil; import com.intellij.util.BitUtil; import com.intellij.util.Functions; import com.intellij.util.ObjectUtils; import com.intellij.util.concurrency.AtomicFieldUpdater; import com.intellij.util.containers.ConcurrentBitSet; import com.intellij.util.containers.ConcurrentIntObjectMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.IntObjectMap; import com.intellij.util.keyFMap.KeyFMap; import com.intellij.util.text.ByteArrayCharSequence; import com.intellij.util.text.CharSequenceHashingStrategy; import gnu.trove.THashSet; import gnu.trove.TIntHashSet; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.concurrent.atomic.AtomicIntegerArray; import java.util.concurrent.atomic.AtomicReferenceArray; import static com.intellij.openapi.vfs.newvfs.impl.VirtualFileSystemEntry.ALL_FLAGS_MASK; import static com.intellij.util.ObjectUtils.assertNotNull; /** * The place where all the data is stored for VFS parts loaded into a memory: name-ids, flags, user data, children. * * The purpose is to avoid holding this data in separate immortal file/directory objects because that involves space overhead, significant * when there are hundreds of thousands of files. * * The data is stored per-id in blocks of {@link #SEGMENT_SIZE}. File ids in one project tend to cluster together, * so the overhead for non-loaded id should not be large in most cases. * * File objects are still created if needed. There might be several objects for the same file, so equals() should be used instead of ==. * * The lifecycle of a file object is as follows: * * 1. The file has not been instantiated yet, so {@link #getFileById} returns null. * * 2. A file is explicitly requested by calling getChildren or findChild on its parent. The parent initializes all the necessary data (in a thread-safe context) * and creates the file instance. See {@link #initFile} * * 3. After that the file is live, an object representing it can be retrieved any time from its parent. File system roots are * kept on hard references in {@link PersistentFS} * * 4. If a file is deleted (invalidated), then its data is not needed anymore, and should be removed. But this can only happen after * all the listener have been notified about the file deletion and have had their chance to look at the data the last time. See {@link #killInvalidatedFiles()} * * 5. The file with removed data is marked as "dead" (see {@link #myDeadMarker}, any access to it will throw {@link InvalidVirtualFileAccessException} * Dead ids won't be reused in the same session of the IDE. * * @author peter */ public class VfsData { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.newvfs.impl.VfsData"); private static final int SEGMENT_BITS = 9; private static final int SEGMENT_SIZE = 1 << SEGMENT_BITS; private static final int OFFSET_MASK = SEGMENT_SIZE - 1; private final Object myDeadMarker = ObjectUtils.sentinel("dead file"); private final ConcurrentIntObjectMap<Segment> mySegments = ContainerUtil.createConcurrentIntObjectMap(); private final ConcurrentBitSet myInvalidatedIds = new ConcurrentBitSet(); private TIntHashSet myDyingIds = new TIntHashSet(); private final IntObjectMap<VirtualDirectoryImpl> myChangedParents = ContainerUtil.createConcurrentIntObjectMap(); public VfsData() { ApplicationManager.getApplication().addApplicationListener(new ApplicationAdapter() { @Override public void writeActionFinished(@NotNull Object action) { // after top-level write action is finished, all the deletion listeners should have processed the deleted files // and their data is considered safe to remove. From this point on accessing a removed file will result in an exception. if (!ApplicationManager.getApplication().isWriteAccessAllowed()) { killInvalidatedFiles(); } } }); } private void killInvalidatedFiles() { synchronized (myDeadMarker) { if (!myDyingIds.isEmpty()) { for (int id : myDyingIds.toArray()) { Segment segment = assertNotNull(getSegment(id, false)); segment.myObjectArray.set(getOffset(id), myDeadMarker); myChangedParents.remove(id); } myDyingIds = new TIntHashSet(); } } } @Nullable VirtualFileSystemEntry getFileById(int id, @NotNull VirtualDirectoryImpl parent) { PersistentFSImpl persistentFS = (PersistentFSImpl)PersistentFS.getInstance(); VirtualFileSystemEntry dir = persistentFS.getCachedDir(id); if (dir != null) return dir; Segment segment = getSegment(id, false); if (segment == null) return null; int offset = getOffset(id); Object o = segment.myObjectArray.get(offset); if (o == null) return null; if (o == myDeadMarker) { throw reportDeadFileAccess(new VirtualFileImpl(id, segment, parent)); } final int nameId = segment.getNameId(id); if (nameId <= 0) { FSRecords.invalidateCaches(); throw new AssertionError("nameId=" + nameId + "; data=" + o + "; parent=" + parent + "; parent.id=" + parent.getId() + "; db.parent=" + FSRecords.getParent(id)); } return o instanceof DirectoryData ? persistentFS.getOrCacheDir(id, segment, (DirectoryData)o, parent) : new VirtualFileImpl(id, segment, parent); } private static InvalidVirtualFileAccessException reportDeadFileAccess(VirtualFileSystemEntry file) { return new InvalidVirtualFileAccessException("Accessing dead virtual file: " + file.getUrl()); } private static int getOffset(int id) { return id & OFFSET_MASK; } @Nullable @Contract("_,true->!null") public Segment getSegment(int id, boolean create) { int key = id >>> SEGMENT_BITS; Segment segment = mySegments.get(key); if (segment != null || !create) return segment; return mySegments.cacheOrGet(key, new Segment(this)); } public boolean hasLoadedFile(int id) { Segment segment = getSegment(id, false); return segment != null && segment.myObjectArray.get(getOffset(id)) != null; } public static class FileAlreadyCreatedException extends Exception { private FileAlreadyCreatedException(String message) { super(message); } } public static void initFile(int id, Segment segment, int nameId, @NotNull Object data) throws FileAlreadyCreatedException { assert id > 0; int offset = getOffset(id); segment.setNameId(id, nameId); Object existingData = segment.myObjectArray.get(offset); if (existingData != null) { FSRecords.invalidateCaches(); int parent = FSRecords.getParent(id); String msg = "File already created: " + nameId + ", data=" + existingData + "; parentId=" + parent; if (parent > 0) { msg += "; parent.name=" + FSRecords.getName(parent); msg += "; parent.children=" + Arrays.toString(FSRecords.listAll(id)); } throw new FileAlreadyCreatedException(msg); } segment.myObjectArray.set(offset, data); } CharSequence getNameByFileId(int id) { return FileNameCache.getVFileName(assertNotNull(getSegment(id, false)).getNameId(id)); } boolean isFileValid(int id) { return !myInvalidatedIds.get(id); } @Nullable VirtualDirectoryImpl getChangedParent(int id) { return myChangedParents.get(id); } void changeParent(int id, VirtualDirectoryImpl parent) { myChangedParents.put(id, parent); } void invalidateFile(int id) { myInvalidatedIds.set(id); synchronized (myDeadMarker) { myDyingIds.add(id); } } public static class Segment { // user data for files, DirectoryData for folders private final AtomicReferenceArray<Object> myObjectArray = new AtomicReferenceArray<>(SEGMENT_SIZE); // <nameId, flags> pairs, "flags" part containing flags per se and modification stamp private final AtomicIntegerArray myIntArray = new AtomicIntegerArray(SEGMENT_SIZE * 2); final VfsData vfsData; Segment(VfsData vfsData) { this.vfsData = vfsData; } int getNameId(int fileId) { return myIntArray.get(getOffset(fileId) * 2); } void setNameId(int fileId, int nameId) { myIntArray.set(getOffset(fileId) * 2, nameId); } void setUserMap(int fileId, @NotNull KeyFMap map) { myObjectArray.set(getOffset(fileId), map); } KeyFMap getUserMap(VirtualFileSystemEntry file, int id) { Object o = myObjectArray.get(getOffset(id)); if (!(o instanceof KeyFMap)) { throw reportDeadFileAccess(file); } return (KeyFMap)o; } boolean changeUserMap(int fileId, KeyFMap oldMap, KeyFMap newMap) { return myObjectArray.compareAndSet(getOffset(fileId), oldMap, newMap); } boolean getFlag(int id, int mask) { assert (mask & ~ALL_FLAGS_MASK) == 0 : "Unexpected flag"; return (myIntArray.get(getOffset(id) * 2 + 1) & mask) != 0; } void setFlag(int id, int mask, boolean value) { if (LOG.isTraceEnabled()) { LOG.trace("Set flag " + Integer.toHexString(mask) + "=" + value + " for id=" + id); } assert (mask & ~ALL_FLAGS_MASK) == 0 : "Unexpected flag"; int offset = getOffset(id) * 2 + 1; while (true) { int oldInt = myIntArray.get(offset); int updated = BitUtil.set(oldInt, mask, value); if (myIntArray.compareAndSet(offset, oldInt, updated)) { return; } } } long getModificationStamp(int id) { return myIntArray.get(getOffset(id) * 2 + 1) & ~ALL_FLAGS_MASK; } void setModificationStamp(int id, long stamp) { int offset = getOffset(id) * 2 + 1; while (true) { int oldInt = myIntArray.get(offset); int updated = (oldInt & ALL_FLAGS_MASK) | ((int)stamp & ~ALL_FLAGS_MASK); if (myIntArray.compareAndSet(offset, oldInt, updated)) { return; } } } } // non-final field accesses are synchronized on this instance, but this happens in VirtualDirectoryImpl public static class DirectoryData { private static final AtomicFieldUpdater<DirectoryData, KeyFMap> MY_USER_MAP_UPDATER = AtomicFieldUpdater.forFieldOfType(DirectoryData.class, KeyFMap.class); @NotNull volatile KeyFMap myUserMap = KeyFMap.EMPTY_MAP; /** * sorted by {@link VfsData#getNameByFileId(int)} * assigned under lock(this) only; never modified in-place * @see VirtualDirectoryImpl#findIndex(int[], CharSequence, boolean) */ @NotNull volatile int[] myChildrenIds = ArrayUtil.EMPTY_INT_ARRAY; // guarded by this private static final AtomicFieldUpdater<DirectoryData, Set> MY_ADOPTED_NAMES_UPDATER = AtomicFieldUpdater.forFieldOfType(DirectoryData.class, Set.class); // assigned under lock(this) only; modified under lock(myAdoptedNames) private volatile Set<CharSequence> myAdoptedNames; @NotNull VirtualFileSystemEntry[] getFileChildren(int fileId, @NotNull VirtualDirectoryImpl parent) { assert fileId > 0; int[] ids = myChildrenIds; VirtualFileSystemEntry[] children = new VirtualFileSystemEntry[ids.length]; for (int i = 0; i < ids.length; i++) { children[i] = assertNotNull(parent.mySegment.vfsData.getFileById(ids[i], parent)); } return children; } boolean changeUserMap(KeyFMap oldMap, KeyFMap newMap) { return MY_USER_MAP_UPDATER.compareAndSet(this, oldMap, newMap); } boolean isAdoptedName(@NotNull CharSequence name) { Set<CharSequence> adopted = myAdoptedNames; if (adopted == null) { return false; } synchronized (adopted) { return adopted.contains(name); } } /** * must call removeAdoptedName() before adding new child with the same name * or otherwise {@link VirtualDirectoryImpl#doFindChild(String, boolean, NewVirtualFileSystem, boolean)} would risk finding already non-existing child */ void removeAdoptedName(@NotNull CharSequence name) { Set<CharSequence> adopted = myAdoptedNames; if (adopted == null) { return; } synchronized (adopted) { boolean removed = adopted.remove(name); if (removed && adopted.isEmpty()) { // if failed then somebody's nulled it already, no need to retry MY_ADOPTED_NAMES_UPDATER.compareAndSet(this, adopted, null); } } } void addAdoptedName(@NotNull CharSequence name, boolean caseSensitive) { Set<CharSequence> adopted = getOrCreateAdoptedNames(caseSensitive); CharSequence sequence = ByteArrayCharSequence.convertToBytesIfPossible(name); synchronized (adopted) { adopted.add(sequence); } } @NotNull private Set<CharSequence> getOrCreateAdoptedNames(boolean caseSensitive) { Set<CharSequence> adopted; while (true) { adopted = myAdoptedNames; if (adopted != null) break; adopted = new THashSet<>(0, caseSensitive ? CharSequenceHashingStrategy.CASE_SENSITIVE : CharSequenceHashingStrategy.CASE_INSENSITIVE); if (MY_ADOPTED_NAMES_UPDATER.compareAndSet(this, null, adopted)) { break; } } return adopted; } void addAdoptedNames(@NotNull Collection<? extends CharSequence> names, boolean caseSensitive) { Set<CharSequence> adopted = getOrCreateAdoptedNames(caseSensitive); synchronized (adopted) { adopted.addAll(names); } } @NotNull List<String> getAdoptedNames() { Set<CharSequence> adopted = myAdoptedNames; if (adopted == null) return Collections.emptyList(); synchronized (adopted) { return ContainerUtil.map(adopted, Functions.TO_STRING()); } } void clearAdoptedNames() { myAdoptedNames = null; } @Override public String toString() { return "DirectoryData{" + "myUserMap=" + myUserMap + ", myChildrenIds=" + Arrays.toString(myChildrenIds) + ", myAdoptedNames=" + myAdoptedNames + '}'; } } }
package de.dominikschadow.javasecurity.logging.home; public class Login { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
/***************************************************************** JADE - Java Agent DEvelopment Framework is a framework to develop multi-agent systems in compliance with the FIPA specifications. Copyright (C) 2000 CSELT S.p.A. GNU Lesser General Public License This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 2.1 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *****************************************************************/ package jade.tools.SocketProxyAgent; import java.net.*; import java.io.*; import java.util.*; import jade.core.Agent; import jade.util.Logger; /** * this class is a thread to listen for connections on the desired port. */ class Server extends Thread { /** my logger */ private final static Logger logger = Logger.getMyLogger(Server.class.getName()); private ServerSocket listen_socket; private Agent myAgent; private Vector myOnlyReceivers; private boolean done = false; private Socket client_socket; private Connection c; /** * Constructor of the class. * It creates a ServerSocket to listen for connections on. * @param port is the port number to listen for. If 0, then it uses * the default port number. * @param a is the pointer to agent to be used to send messages. * @param receivers vector with the names of all the agents that * wish to receive messages through this proxy. */ Server(int port, Agent a, Vector receivers) { myAgent = a; setName (myAgent.getLocalName() + "-SocketListener"); if (port == 0) { port = SocketProxyAgent.DEFAULT_PORT; } myOnlyReceivers = receivers; try { listen_socket = new ServerSocket(port); } catch (IOException e) { e.printStackTrace(); myAgent.doDelete(); return; } logger.log( Logger.CONFIG, getName() + ": Listening on port: " + port); start(); } /** * The body of the server thread. * It is executed when the start() method of the server object is called. * Loops forever, listening for and accepting connections from clients. * For each connection, creates a Connection object to handle communication * through the new Socket. Each Connection object is a new thread. * The maximum queue length for incoming connection indications * (a request to connect) is set to 50 (that is the default for the * ServerSocket constructor). If a connection indication * arrives when the queue is full, the connection is refused. */ public void run() { try { done = false; while (!done) { client_socket = listen_socket.accept(); if ( logger.isLoggable( Logger.FINE ) ) { logger.log( Logger.FINE, "New Connection with " + client_socket.getInetAddress().toString() + " on remote port " + client_socket.getPort()); } c = new Connection(client_socket, myAgent, myOnlyReceivers); } } catch (IOException e) { // If the done flag is still false, then we had an unexpected // IOException. if (!done) { logger.log( Logger.WARNING, getName() + " IOException: " + e); myAgent.doDelete(); } } finally { finalize(); } } /** * stop listening */ protected void closeDown() { done = true; try { if (listen_socket != null) { listen_socket.close(); listen_socket = null; } } catch (Exception e) { // Do nothing } } /** * try to clean up on GC */ protected void finalize() { closeDown(); try { if (client_socket != null) { client_socket.close(); client_socket = null; } } catch (Exception e) { // Do nothing } try { if (c != null) { if (c.isAlive()) { c.close(); } c.join(1000); c = null; } } catch (Exception e) { // Do nothing } } }
package com.tokelon.toktales.tools.tiled.model; import java.util.List; import com.tokelon.toktales.tools.tiled.ITiledMapLevelHolder; public interface ITiledMapObjectgroup extends ITiledMapLevelHolder { public String getName(); public String getColor(); public float getOpacity(); public boolean isVisible(); public int getObjectCount(); public ITMXObject getObject(int index); public List<? extends ITMXObject> getObjectList(); public ITiledMapProperties getProperties(); }
package io.github.idilantha.pos.business; public interface SuperBO { }
package com.stylefeng.guns.api.cinema.model; import lombok.Data; import java.io.Serializable; @Data public class AreaVo implements Serializable { private Integer areaId; private String areaName; private boolean isActive; }
/* * Copyright (c) Huawei Technologies Co., Ltd. 2020-2022. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.huawei.chitchatapp.videoplayer.contract; public interface OnDialogInputValueListener { void dialogInputListener(String inputText); }
package cn.loltime.zone.utils; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import android.os.Handler; import android.os.Message; public class HttpUtils { public static void getJSON(final String url, final Handler handler){ new Thread(new Runnable() { @Override public void run() { HttpURLConnection conn; InputStream is; try { conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); is = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = ""; StringBuilder result = new StringBuilder(); while ( (line = reader.readLine()) != null ){ result.append(line); } Message msg = new Message(); msg.obj = result.toString(); handler.sendMessage(msg); } catch (Exception e) { e.printStackTrace(); } } }).start(); } }
/**************************************************************** * 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.james.queue.rabbitmq; import java.util.Objects; import java.util.Optional; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; public final class MailQueueName { static class WorkQueueName { static Optional<WorkQueueName> fromString(String name) { Preconditions.checkNotNull(name); return Optional.of(name) .filter(WorkQueueName::isJamesWorkQueueName) .map(s -> s.substring(WORKQUEUE_PREFIX.length())) .map(WorkQueueName::new); } static boolean isJamesWorkQueueName(String name) { return name.startsWith(WORKQUEUE_PREFIX); } private final String name; private WorkQueueName(String name) { this.name = name; } String asString() { return WORKQUEUE_PREFIX + name; } MailQueueName toMailQueueName() { return MailQueueName.fromString(name); } @Override public final boolean equals(Object o) { if (o instanceof WorkQueueName) { WorkQueueName that = (WorkQueueName) o; return Objects.equals(name, that.name); } return false; } @Override public final int hashCode() { return Objects.hash(name); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("name", name) .toString(); } } static class ExchangeName { private final String name; private ExchangeName(String name) { this.name = name; } String asString() { return EXCHANGE_PREFIX + name; } @Override public final boolean equals(Object o) { if (o instanceof ExchangeName) { ExchangeName that = (ExchangeName) o; return Objects.equals(name, that.name); } return false; } @Override public final int hashCode() { return Objects.hash(name); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("name", name) .toString(); } } private static final String PREFIX = "JamesMailQueue"; private static final String EXCHANGE_PREFIX = PREFIX + "-exchange-"; private static final String DEAD_LETTER_EXCHANGE_PREFIX = PREFIX + "-dead-letter-exchange-"; private static final String DEAD_LETTER_QUEUE_PREFIX = PREFIX + "-dead-letter-queue-"; @VisibleForTesting static final String WORKQUEUE_PREFIX = PREFIX + "-workqueue-"; public static MailQueueName fromString(String name) { Preconditions.checkNotNull(name); return new MailQueueName(name); } static Optional<MailQueueName> fromRabbitWorkQueueName(String workQueueName) { return WorkQueueName.fromString(workQueueName) .map(WorkQueueName::toMailQueueName); } private final String name; private MailQueueName(String name) { this.name = name; } public String asString() { return name; } String toDeadLetterExchangeName() { return DEAD_LETTER_EXCHANGE_PREFIX + name; } String toDeadLetterQueueName() { return DEAD_LETTER_QUEUE_PREFIX + name; } ExchangeName toRabbitExchangeName() { return new ExchangeName(name); } WorkQueueName toWorkQueueName() { return new WorkQueueName(name); } org.apache.james.queue.api.MailQueueName toModel() { return org.apache.james.queue.api.MailQueueName.of(asString()); } @Override public final boolean equals(Object o) { if (o instanceof MailQueueName) { MailQueueName that = (MailQueueName) o; return Objects.equals(name, that.name); } return false; } @Override public final int hashCode() { return Objects.hash(name); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("name", name) .toString(); } }
package weixin.popular.bean.paymch; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "xml") @XmlAccessorType(XmlAccessType.FIELD) public class MchReverse { @XmlElement private String appid; @XmlElement private String mch_id; @XmlElement private String transaction_id; @XmlElement private String out_trade_no; @XmlElement private String nonce_str; @XmlElement private String sign; public String getAppid() { return appid; } public void setAppid(String appid) { this.appid = appid; } public String getMch_id() { return mch_id; } public void setMch_id(String mch_id) { this.mch_id = mch_id; } public String getOut_trade_no() { return out_trade_no; } public void setOut_trade_no(String out_trade_no) { this.out_trade_no = out_trade_no; } public String getNonce_str() { return nonce_str; } public void setNonce_str(String nonce_str) { this.nonce_str = nonce_str; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public String getTransaction_id() { return transaction_id; } public void setTransaction_id(String transaction_id) { this.transaction_id = transaction_id; } }
/* * Copyright 2000-2016 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. */ /* * Created by IntelliJ IDEA. * User: max * Date: Nov 4, 2001 * Time: 5:19:35 PM */ package com.intellij.codeInspection.ui; import com.intellij.codeInspection.CommonProblemDescriptor; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.codeInspection.ex.GlobalInspectionContextImpl; import com.intellij.codeInspection.ex.InspectionToolWrapper; import com.intellij.codeInspection.reference.RefEntity; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.profile.codeInspection.ui.inspectionsTree.InspectionsConfigTreeComparator; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiUtilCore; import com.intellij.ui.TreeSpeedSearch; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.ArrayUtil; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeWillExpandListener; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.ExpandVetoException; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import java.util.*; public class InspectionTree extends Tree { private static final Logger LOG = Logger.getInstance(InspectionTree.class); private static final Comparator<CommonProblemDescriptor> DESCRIPTOR_COMPARATOR = (c1, c2) -> { if (c1 instanceof ProblemDescriptor && c2 instanceof ProblemDescriptor) { return PsiUtilCore.compareElementsByPosition(((ProblemDescriptor)c2).getPsiElement(), ((ProblemDescriptor)c1).getPsiElement()); } return c1.getDescriptionTemplate().compareTo(c2.getDescriptionTemplate()); }; @NotNull private final GlobalInspectionContextImpl myContext; @NotNull private final ExcludedInspectionTreeNodesManager myExcludedManager; @NotNull private InspectionTreeState myState = new InspectionTreeState(); private boolean myQueueUpdate; public InspectionTree(@NotNull Project project, @NotNull GlobalInspectionContextImpl context, @NotNull InspectionResultsView view) { setModel(new DefaultTreeModel(new InspectionRootNode(project, new InspectionTreeUpdater(view)))); myContext = context; myExcludedManager = view.getExcludedManager(); setCellRenderer(new InspectionTreeCellRenderer(view)); setRootVisible(false); setShowsRootHandles(true); UIUtil.setLineStyleAngled(this); addTreeWillExpandListener(new ExpandListener()); myState.getExpandedUserObjects().add(project); TreeUtil.installActions(this); new TreeSpeedSearch(this, o -> InspectionsConfigTreeComparator.getDisplayTextToSort(o.getLastPathComponent().toString())); addTreeSelectionListener(e -> { TreePath newSelection = e.getNewLeadSelectionPath(); if (newSelection != null && !isUnderQueueUpdate()) { myState.setSelectionPath(newSelection); } }); } public void setQueueUpdate(boolean queueUpdate) { myQueueUpdate = queueUpdate; } public boolean isUnderQueueUpdate() { return myQueueUpdate; } public void removeAllNodes() { getRoot().removeAllChildren(); ApplicationManager.getApplication().invokeLater(() -> nodeStructureChanged(getRoot())); } public InspectionTreeNode getRoot() { return (InspectionTreeNode)getModel().getRoot(); } @Nullable public String[] getSelectedGroupPath() { final TreePath[] paths = getSelectionPaths(); if (paths == null) return null; final TreePath commonPath = TreeUtil.findCommonPath(paths); for (Object n : commonPath.getPath()) { if (n instanceof InspectionGroupNode) { return ((InspectionGroupNode)n).getGroupPath(); } } return null; } @Nullable public InspectionToolWrapper getSelectedToolWrapper(boolean allowDummy) { final TreePath[] paths = getSelectionPaths(); if (paths == null) return null; InspectionToolWrapper toolWrapper = null; for (TreePath path : paths) { Object[] nodes = path.getPath(); for (int j = nodes.length - 1; j >= 0; j--) { Object node = nodes[j]; if (node instanceof InspectionGroupNode) { return null; } if (node instanceof InspectionNode) { InspectionToolWrapper wrapper = ((InspectionNode)node).getToolWrapper(); if (!allowDummy && getContext().getPresentation(wrapper).isDummy()) { continue; } if (toolWrapper == null) { toolWrapper = wrapper; } else if (toolWrapper != wrapper) { return null; } break; } } } return toolWrapper; } @Nullable public RefEntity getCommonSelectedElement() { final Object node = getCommonSelectedNode(); return node instanceof RefElementNode ? ((RefElementNode)node).getElement() : null; } @Nullable private Object getCommonSelectedNode() { final TreePath[] paths = getSelectionPaths(); if (paths == null) return null; final Object[][] resolvedPaths = new Object[paths.length][]; for (int i = 0; i < paths.length; i++) { TreePath path = paths[i]; resolvedPaths[i] = path.getPath(); } Object currentCommonNode = null; for (int i = 0; i < resolvedPaths[0].length; i++) { final Object currentNode = resolvedPaths[0][i]; for (int j = 1; j < resolvedPaths.length; j++) { final Object o = resolvedPaths[j][i]; if (!o.equals(currentNode)) { return currentCommonNode; } } currentCommonNode = currentNode; } return currentCommonNode; } @NotNull public RefEntity[] getSelectedElements() { TreePath[] selectionPaths = getSelectionPaths(); if (selectionPaths != null) { InspectionToolWrapper toolWrapper = getSelectedToolWrapper(true); if (toolWrapper == null) return RefEntity.EMPTY_ELEMENTS_ARRAY; Set<RefEntity> result = new LinkedHashSet<>(); for (TreePath selectionPath : selectionPaths) { final InspectionTreeNode node = (InspectionTreeNode)selectionPath.getLastPathComponent(); addElementsInNode(node, result); } return ArrayUtil.reverseArray(result.toArray(new RefEntity[result.size()])); } return RefEntity.EMPTY_ELEMENTS_ARRAY; } private static void addElementsInNode(InspectionTreeNode node, Set<RefEntity> out) { if (!node.isValid()) return; if (node instanceof RefElementNode) { final RefEntity element = ((RefElementNode)node).getElement(); out.add(element); } if (node instanceof ProblemDescriptionNode) { final RefEntity element = ((ProblemDescriptionNode)node).getElement(); out.add(element); } final Enumeration children = node.children(); while (children.hasMoreElements()) { InspectionTreeNode child = (InspectionTreeNode)children.nextElement(); addElementsInNode(child, out); } } public CommonProblemDescriptor[] getAllValidSelectedDescriptors() { return getSelectedDescriptors(false, null, true, false); } public CommonProblemDescriptor[] getSelectedDescriptors() { return getSelectedDescriptors(false, null, false, false); } public CommonProblemDescriptor[] getSelectedDescriptors(boolean sortedByPosition, @Nullable Set<VirtualFile> readOnlyFilesSink, boolean allowResolved, boolean allowSuppressed) { final TreePath[] paths = getSelectionPaths(); if (paths == null) return CommonProblemDescriptor.EMPTY_ARRAY; final TreePath[] selectionPaths = TreeUtil.selectMaximals(paths); final List<CommonProblemDescriptor> descriptors = new ArrayList<>(); MultiMap<Object, ProblemDescriptionNode> parentToChildNode = new MultiMap<>(); final List<InspectionTreeNode> nonDescriptorNodes = new SmartList<>(); for (TreePath path : selectionPaths) { final Object[] pathAsArray = path.getPath(); final int length = pathAsArray.length; final Object node = pathAsArray[length - 1]; if (node instanceof ProblemDescriptionNode) { if (isNodeValidAndIncluded((ProblemDescriptionNode)node, allowResolved, allowSuppressed)) { if (length >= 2) { parentToChildNode.putValue(pathAsArray[length - 2], (ProblemDescriptionNode)node); } else { parentToChildNode.putValue(node, (ProblemDescriptionNode)node); } } } else { nonDescriptorNodes.add((InspectionTreeNode)node); } } for (InspectionTreeNode node : nonDescriptorNodes) { processChildDescriptorsDeep(node, descriptors, sortedByPosition, allowResolved, allowSuppressed, readOnlyFilesSink); } for (Map.Entry<Object, Collection<ProblemDescriptionNode>> entry : parentToChildNode.entrySet()) { final Collection<ProblemDescriptionNode> siblings = entry.getValue(); if (siblings.size() == 1) { final ProblemDescriptionNode descriptorNode = ContainerUtil.getFirstItem(siblings); LOG.assertTrue(descriptorNode != null); CommonProblemDescriptor descriptor = descriptorNode.getDescriptor(); if (descriptor != null) { descriptors.add(descriptor); if (readOnlyFilesSink != null) { collectReadOnlyFiles(descriptor, readOnlyFilesSink); } } } else { List<CommonProblemDescriptor> currentDescriptors = new ArrayList<>(); for (ProblemDescriptionNode sibling : siblings) { final CommonProblemDescriptor descriptor = sibling.getDescriptor(); if (descriptor != null) { if (readOnlyFilesSink != null) { collectReadOnlyFiles(descriptor, readOnlyFilesSink); } currentDescriptors.add(descriptor); } } if (sortedByPosition) { Collections.sort(currentDescriptors, DESCRIPTOR_COMPARATOR); } descriptors.addAll(currentDescriptors); } } return descriptors.toArray(new CommonProblemDescriptor[descriptors.size()]); } public boolean areDescriptorNodesSelected() { final TreePath[] paths = getSelectionPaths(); if (paths == null) return false; for (TreePath path : paths) { if (!(path.getLastPathComponent() instanceof ProblemDescriptionNode)) { return false; } } return true; } public int getSelectedProblemCount(boolean allowSuppressed) { int count = 0; for (TreePath path : TreeUtil.selectMaximals(getSelectionPaths())) { count += ((InspectionTreeNode)path.getLastPathComponent()).getProblemCount(allowSuppressed); } return count; } private void processChildDescriptorsDeep(InspectionTreeNode node, List<CommonProblemDescriptor> descriptors, boolean sortedByPosition, boolean allowResolved, boolean allowSuppressed, @Nullable Set<VirtualFile> readOnlyFilesSink) { List<CommonProblemDescriptor> descriptorChildren = null; for (int i = 0; i < node.getChildCount(); i++) { final TreeNode child = node.getChildAt(i); if (child instanceof ProblemDescriptionNode) { if (isNodeValidAndIncluded((ProblemDescriptionNode)child, allowResolved, allowSuppressed)) { if (sortedByPosition) { if (descriptorChildren == null) { descriptorChildren = new ArrayList<>(); } descriptorChildren.add(((ProblemDescriptionNode)child).getDescriptor()); } else { descriptors.add(((ProblemDescriptionNode)child).getDescriptor()); } } } else { processChildDescriptorsDeep((InspectionTreeNode)child, descriptors, sortedByPosition, allowResolved, allowSuppressed, readOnlyFilesSink); } } if (descriptorChildren != null) { if (descriptorChildren.size() > 1) { Collections.sort(descriptorChildren, DESCRIPTOR_COMPARATOR); } if (readOnlyFilesSink != null) { collectReadOnlyFiles(descriptorChildren, readOnlyFilesSink); } descriptors.addAll(descriptorChildren); } } private boolean isNodeValidAndIncluded(ProblemDescriptionNode node, boolean allowResolved, boolean allowSuppressed) { return node.isValid() && (allowResolved || (!node.isExcluded(myExcludedManager) && (!node.isAlreadySuppressedFromView() || (allowSuppressed && !node.getAvailableSuppressActions().isEmpty())) && !node.isQuickFixAppliedFromView())); } private void nodeStructureChanged(InspectionTreeNode node) { ((DefaultTreeModel)getModel()).nodeStructureChanged(node); } public void queueUpdate() { ((InspectionRootNode) getRoot()).getUpdater().update(null, true); } public void restoreExpansionAndSelection(boolean treeNodesMightChange) { myState.restoreExpansionAndSelection(this, treeNodesMightChange); } public void setState(@NotNull InspectionTreeState state) { myState = state; } public InspectionTreeState getTreeState() { return myState; } public void setTreeState(@NotNull InspectionTreeState treeState) { myState = treeState; } private class ExpandListener implements TreeWillExpandListener { @Override public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException { final InspectionTreeNode node = (InspectionTreeNode)event.getPath().getLastPathComponent(); myState.getExpandedUserObjects().add(node.getUserObject()); } @Override public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException { InspectionTreeNode node = (InspectionTreeNode)event.getPath().getLastPathComponent(); myState.getExpandedUserObjects().remove(node.getUserObject()); } } @NotNull public GlobalInspectionContextImpl getContext() { return myContext; } private static void collectReadOnlyFiles(@NotNull Collection<CommonProblemDescriptor> descriptors, @NotNull Set<VirtualFile> readOnlySink) { for (CommonProblemDescriptor descriptor : descriptors) { collectReadOnlyFiles(descriptor, readOnlySink); } } private static void collectReadOnlyFiles(@NotNull CommonProblemDescriptor descriptor, @NotNull Set<VirtualFile> readOnlySink) { if (descriptor instanceof ProblemDescriptor) { PsiElement psiElement = ((ProblemDescriptor)descriptor).getPsiElement(); if (psiElement != null && !psiElement.isWritable()) { readOnlySink.add(psiElement.getContainingFile().getVirtualFile()); } } } }
package sonar.logistics.api.connecting; import net.minecraft.util.EnumFacing; import sonar.core.api.utils.BlockCoords; import sonar.core.utils.IWorldPosition; import sonar.logistics.api.cache.INetworkCache; /** implemented by Tile Entities which can connect to Data Cables */ public interface ILogicTile extends IWorldPosition { public static enum ConnectionType{ VISUAL, NETWORK, NONE; public boolean canConnect(){ return this==NETWORK; } public boolean canShowConnection(){ return this==VISUAL || canConnect(); } } /** can the Tile connect to cables on the given direction */ public ConnectionType canConnect(EnumFacing dir); /** the {@link BlockCoords} this Block/FMP Part should be registered as on the Network * @return the {@link BlockCoords} */ public BlockCoords getCoords(); /**gets the network cache's ID*/ public int getNetworkID(); /**sets the network this tile is connected to*/ public void setLocalNetworkCache(INetworkCache network); }
package cz.cuni.mff.java.mbeans.rmi; import java.io.IOException; import java.net.MalformedURLException; import javax.management.*; import javax.management.remote.*; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; public class Client { public static void main(String[] args) { try { JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/server"); try (JMXConnector jmxc = JMXConnectorFactory.connect(url, null)) { MBeanServerConnection mbsc = jmxc.getMBeanServerConnection(); ObjectName mname = new ObjectName("cz.cuni.mff.java.mbeans.rmi:type=MyClass"); ObjectInstance inst = null; Set<ObjectInstance> beans = mbsc.queryMBeans(null, null); for (ObjectInstance oi : beans) { ObjectName name = oi.getObjectName(); System.out.println(name); if (name.equals(mname)) { inst = oi; System.out.println("OK"); } } System.out.println(mbsc.getAttribute(mname, "State")); mbsc.setAttribute(mname, new Attribute("State", 100)); MyClassMBean proxy = JMX.newMBeanProxy(mbsc, mname, MyClassMBean.class, true); System.out.println(proxy.getState()); } catch (IOException | MalformedObjectNameException | MBeanException | AttributeNotFoundException | InstanceNotFoundException | ReflectionException | InvalidAttributeValueException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } } catch (MalformedURLException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } } }
package com.karogath.enhancedvanilla.block; import net.minecraftforge.registries.ObjectHolder; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.common.ToolType; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.Dist; import net.minecraft.world.storage.loot.LootContext; import net.minecraft.world.World; import net.minecraft.world.IBlockReader; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.BlockRayTraceResult; import net.minecraft.util.math.BlockPos; import net.minecraft.util.Rotation; import net.minecraft.util.Mirror; import net.minecraft.util.Hand; import net.minecraft.util.Direction; import net.minecraft.util.ActionResultType; import net.minecraft.state.StateContainer; import net.minecraft.state.DirectionProperty; import net.minecraft.item.ItemStack; import net.minecraft.item.Item; import net.minecraft.item.BlockItemUseContext; import net.minecraft.item.BlockItem; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.client.renderer.RenderTypeLookup; import net.minecraft.client.renderer.RenderType; import net.minecraft.block.material.Material; import net.minecraft.block.SoundType; import net.minecraft.block.HorizontalBlock; import net.minecraft.block.BlockState; import net.minecraft.block.Block; import java.util.List; import java.util.Collections; import com.karogath.enhancedvanilla.procedures.AmberEnderEye1Procedure; import com.karogath.enhancedvanilla.EnhancedvanillaModElements; @EnhancedvanillaModElements.ModElement.Tag public class AmberEnderEyeBlock extends EnhancedvanillaModElements.ModElement { @ObjectHolder("enhancedvanilla:amber_ender_eye") public static final Block block = null; public AmberEnderEyeBlock(EnhancedvanillaModElements instance) { super(instance, 344); } @Override public void initElements() { elements.blocks.add(() -> new CustomBlock()); elements.items.add(() -> new BlockItem(block, new Item.Properties().group(null)).setRegistryName(block.getRegistryName())); } @Override @OnlyIn(Dist.CLIENT) public void clientLoad(FMLClientSetupEvent event) { RenderTypeLookup.setRenderLayer(block, RenderType.getTranslucent()); } public static class CustomBlock extends Block { public static final DirectionProperty FACING = HorizontalBlock.HORIZONTAL_FACING; public CustomBlock() { super(Block.Properties.create(Material.GLASS).sound(SoundType.GLASS).hardnessAndResistance(1f, 10f).lightValue(0).harvestLevel(1) .harvestTool(ToolType.PICKAXE).notSolid()); this.setDefaultState(this.stateContainer.getBaseState().with(FACING, Direction.NORTH)); setRegistryName("amber_ender_eye"); } @Override public boolean isNormalCube(BlockState state, IBlockReader worldIn, BlockPos pos) { return false; } @Override public boolean propagatesSkylightDown(BlockState state, IBlockReader reader, BlockPos pos) { return true; } @Override protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) { builder.add(FACING); } public BlockState rotate(BlockState state, Rotation rot) { return state.with(FACING, rot.rotate(state.get(FACING))); } public BlockState mirror(BlockState state, Mirror mirrorIn) { return state.rotate(mirrorIn.toRotation(state.get(FACING))); } @Override public BlockState getStateForPlacement(BlockItemUseContext context) { return this.getDefaultState().with(FACING, context.getPlacementHorizontalFacing().getOpposite()); } @Override public ItemStack getPickBlock(BlockState state, RayTraceResult target, IBlockReader world, BlockPos pos, PlayerEntity player) { return new ItemStack(AmberBlock.block, (int) (1)); } @Override public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) { List<ItemStack> dropsOriginal = super.getDrops(state, builder); if (!dropsOriginal.isEmpty()) return dropsOriginal; return Collections.singletonList(new ItemStack(this, 1)); } @Override public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity entity, Hand hand, BlockRayTraceResult hit) { super.onBlockActivated(state, world, pos, entity, hand, hit); int x = pos.getX(); int y = pos.getY(); int z = pos.getZ(); Direction direction = hit.getFace(); { java.util.HashMap<String, Object> $_dependencies = new java.util.HashMap<>(); $_dependencies.put("entity", entity); $_dependencies.put("x", x); $_dependencies.put("y", y); $_dependencies.put("z", z); $_dependencies.put("world", world); AmberEnderEye1Procedure.executeProcedure($_dependencies); } return ActionResultType.SUCCESS; } } }
package com.google.api.ads.dfp.jaxws.v201408; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * * Updates the specified {@link Company} objects. * * @param companies the companies to update * @return the updated companies * * * <p>Java class for updateCompanies element declaration. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;element name="updateCompanies"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="companies" type="{https://www.google.com/apis/ads/publisher/v201408}Company" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "companies" }) @XmlRootElement(name = "updateCompanies") public class CompanyServiceInterfaceupdateCompanies { protected List<Company> companies; /** * Gets the value of the companies property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the companies property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCompanies().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Company } * * */ public List<Company> getCompanies() { if (companies == null) { companies = new ArrayList<Company>(); } return this.companies; } }
/* * The MIT License * * Copyright 2016 kanjiowl. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package qrcoder; ///** Abandonned due to complexity. Maybe Later. **////// //import org.apache.commons.math3.complexI.Complex; //import org.apache.commons.math3.complex.ComplexUtils; /** * Class containing the Fast Fourier Transform algorithm used for polynomial multiplication. * * @author kanjiowl */ public class FFT { // public static final double PI = 3.141592653589793238460; // // /** // * * // * Implementation of the recursive Cooley-Turkey Forward FFT algorithm. Java port from C++ example found at Rosetta // * Code. // * // * @param a = Complex array of coefficients // */ // public static void forward(int[] a) { // // final int N = a.length; // // if (N <= 1) { // return; // } // // int[] even = new int[N / 2]; // int[] odd = new int[N / 2]; // // for (int i = 0; i < N / 2; i += 1) { // even[i] = a[i * 2]; // odd[i] = a[i * 2 + 1]; // } // // forward(even); // forward(odd); // // for (int k = 0; k < N / 2; ++k) { // int t = GaloisField.multiply(GaloisField.integerToAlphaArray[k], odd[k]); // a[k] = GaloisField.subtract(even[k], t); // a[k + N / 2] = GaloisField.subtract(even[k], t); // } // // } // // /** // * Implementation of the inverse FFT algorithm. Java port from C++ example found at Rosetta Code. // * // * @param a = Complex array of coefficients // */ // public static void inverse(Complex[] a) { // for (int i = 0; i < a.length; i++) { // a[i] = a[i].conjugate(); // } // // forward(a); // // for (int i = 0; i < a.length; i++) { // a[i] = a[i].conjugate(); // } // // double size = a.length; // for (int i = 0; i < a.length; ++i) { // a[i] = a[i].divide(size); // } // } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // public static void forward(Complex[] a) { // // final int N = a.length; // if (N <= 1) { // return; // } // // Complex[] even = new Complex[N / 2]; // Complex[] odd = new Complex[N / 2]; // // for (int i = 0; i < N / 2; i += 1) { // even[i] = a [i * 2]; // odd[i] = a [i * 2 + 1]; // } // // forward(even); // forward(odd); // // for (int k = 0; k < N / 2; ++k) { // Complex t = ComplexUtils.polar2Complex(1.0, -2 * PI * k / N).multiply(odd[k]); // a[k] = even[k].add(t); // a[k + N / 2] = even[k].subtract(t); // } // // } // // /** // * Implementation of the inverse FFT algorithm. Java port from C++ example found at Rosetta Code. // * // * @param a = Complex array of coefficients // */ // public static void inverse(Complex[] a) { // for (int i = 0; i < a.length; i++) { // a[i] = a[i].conjugate(); // } // // forward(a); // // for (int i = 0; i < a.length; i++) { // a[i] = a[i].conjugate(); // } // // double size = a.length; // for (int i = 0; i < a.length; ++i) { // a[i] = a[i].divide(size); // } // } }
package io.qameta.allure.aspects; import io.qameta.allure.Allure; import io.qameta.allure.AllureLifecycle; import io.qameta.allure.model.Parameter; import io.qameta.allure.model.Status; import io.qameta.allure.model.StepResult; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import ru.yandex.qatools.allure.annotations.Step; import java.util.List; import java.util.Objects; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.IntStream; import static io.qameta.allure.aspects.Allure1Utils.getName; import static io.qameta.allure.aspects.Allure1Utils.getTitle; import static io.qameta.allure.util.ResultsUtils.getStatus; import static io.qameta.allure.util.ResultsUtils.getStatusDetails; /** * Aspects (AspectJ) for handling {@link Step}. */ @Aspect @SuppressWarnings("unused") public class Allure1StepsAspects { private static AllureLifecycle lifecycle; @Pointcut("@annotation(ru.yandex.qatools.allure.annotations.Step)") public void withStepAnnotation() { //pointcut body, should be empty } @Pointcut("execution(* *(..))") public void anyMethod() { //pointcut body, should be empty } @Before("anyMethod() && withStepAnnotation()") public void stepStart(final JoinPoint joinPoint) { final MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); final String uuid = UUID.randomUUID().toString(); final StepResult result = new StepResult() .setName(createTitle(joinPoint)) .setParameters(getParameters(methodSignature, joinPoint.getArgs())); getLifecycle().startStep(uuid, result); } @AfterThrowing(pointcut = "anyMethod() && withStepAnnotation()", throwing = "e") public void stepFailed(final JoinPoint joinPoint, final Throwable e) { getLifecycle().updateStep(result -> result .setStatus(getStatus(e).orElse(Status.BROKEN)) .setStatusDetails(getStatusDetails(e).orElse(null))); getLifecycle().stopStep(); } @AfterReturning(pointcut = "anyMethod() && withStepAnnotation()", returning = "result") public void stepStop(final JoinPoint joinPoint, final Object result) { getLifecycle().updateStep(step -> step.setStatus(Status.PASSED)); getLifecycle().stopStep(); } public String createTitle(final JoinPoint joinPoint) { final MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); final Step step = methodSignature.getMethod().getAnnotation(Step.class); return step.value().isEmpty() ? getName(methodSignature.getName(), joinPoint.getArgs()) : getTitle(step.value(), methodSignature.getName(), joinPoint.getThis(), joinPoint.getArgs()); } private static List<Parameter> getParameters(final MethodSignature signature, final Object... args) { return IntStream.range(0, args.length).mapToObj(index -> { final String name = signature.getParameterNames()[index]; final String value = Objects.toString(args[index]); return new Parameter().setName(name).setValue(value); }).collect(Collectors.toList()); } /** * For tests only. */ public static void setLifecycle(final AllureLifecycle allure) { lifecycle = allure; } public static AllureLifecycle getLifecycle() { if (Objects.isNull(lifecycle)) { lifecycle = Allure.getLifecycle(); } return lifecycle; } }
package ConditionalStatementsAndLoops; import java.util.Scanner; public class CaloriesCounter { public static void main(String[] args) { Scanner input = new Scanner(System.in); int number = Integer.parseInt(input.nextLine()); String food = ""; int counter = 0; int cheese = 500; int tomatoSauce = 150; int salami = 600; int pepper = 50; for (int i = 1; i <= number; i++) { food = input.nextLine().toLowerCase(); switch (food){ case "cheese":{ counter += cheese; break; } case "tomato sauce":{ counter += tomatoSauce; break; } case "salami":{ counter += salami; break; } case "pepper":{ counter += pepper; break; } default:{ break; } } } System.out.printf("Total calories: %d", counter); } }
package com.alibaba.chaosblade.exec.plugin.jvm.cpu; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.alibaba.chaosblade.exec.common.aop.EnhancerModel; import com.alibaba.chaosblade.exec.common.model.action.ActionExecutor; import com.alibaba.chaosblade.exec.common.util.StringUtil; import com.alibaba.chaosblade.exec.plugin.jvm.JvmConstant; import com.alibaba.chaosblade.exec.plugin.jvm.StoppableActionExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Changjun Xiao */ public class JvmCpuFullLoadExecutor implements ActionExecutor, StoppableActionExecutor { private static final Logger LOGGER = LoggerFactory.getLogger(JvmCpuFullLoadExecutor.class); private volatile ExecutorService executorService; private Object lock = new Object(); private volatile boolean flag; /** * Through the infinite loop to achieve full CPU load. * * @param enhancerModel * @throws Exception */ @Override public void run(EnhancerModel enhancerModel) throws Exception { if (executorService != null && (!executorService.isShutdown())) { throw new IllegalStateException("The jvm cpu full load experiment is running"); } // 绑定 CPU 核心数, 即指定几个核心满载 String cpuCount = enhancerModel.getActionFlag(JvmConstant.FLAG_NAME_CPU_COUNT); // 获取所有核心 int maxProcessors = Runtime.getRuntime().availableProcessors(); int threadCount = maxProcessors; if (!StringUtil.isBlank(cpuCount)) { Integer count = Integer.valueOf(cpuCount.trim()); if (count > 0 && count < maxProcessors) { threadCount = count; } } synchronized (lock) { if (executorService != null && (!executorService.isShutdown())) { throw new IllegalStateException("The jvm cpu full load experiment is running..."); } // 需要N核心满载,就生成N个的线程, executorService = Executors.newFixedThreadPool(threadCount); } flag = true; for (int i = 0; i < threadCount; i++) { executorService.submit(new Runnable() { @Override public void run() { // 死循环, 循环内什么都不要做 while (flag) { } } }); LOGGER.info("start jvm cpu full load thread, {}", i); } } @Override public void stop(EnhancerModel enhancerModel) throws Exception { flag = false; if (executorService != null && !executorService.isShutdown()) { // 关闭 executorService.shutdownNow(); // 设置为 null , 加快 GC executorService = null; LOGGER.info("jvm cpu full load stopped"); } } }
/* * 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.qpid.jms.message.facade.test; import org.apache.qpid.jms.message.facade.JmsTextMessageFacade; /** * Test implementation of the JmsTextMessageFacade. */ public final class JmsTestTextMessageFacade extends JmsTestMessageFacade implements JmsTextMessageFacade { private String text; @Override public JmsMsgType getMsgType() { return JmsMsgType.TEXT; } @Override public JmsTestTextMessageFacade copy() { JmsTestTextMessageFacade copy = new JmsTestTextMessageFacade(); copyInto(copy); if (text != null) { copy.setText(text); } return copy; } @Override public void clearBody() { this.text = null; } @Override public String getText() { return text; } @Override public void setText(String text) { this.text = text; } }
 import static org.junit.Assert.*; /* * Exercício - Introducao ao JUnit * * Descomentar o teste, ver o teste falar e fazer * a mudança necessária para o teste passar. * */ public class JUnitBasicoTest { public void testAssertTrue() { assertTrue(false); } public void testAssertFalse() { assertFalse(true); } /* * O JUnit informa o resultado esperado e o obtido. */ public void testAssertEqualInts() { assertEquals(1, 2); } public void testCheckingIntCalculation() { int value = 4; int doubled = value * 3; assertEquals(8, doubled); } public void testAssertExactlyEqualDoubles() { double value = 12.0; double result = value / 3; double delta = 0.0; assertEquals(6.0, result, delta); } /* * Quando numeros flutuantes sao comparados previsamos * definit o delta de diferenca nas casas decimais * que podem acontecer. * */ public void testAssertAlmostEqualDoubles() { double numerator = 10.0; double denominator = 3.0; double delta = 0.00001; double expected = 3.333; double quotient = numerator/denominator; assertEquals(expected, quotient, delta); } /* * Strings can be compared too. Make this test pass by fixing * whatToSay. Before you fix it, note how JUnit indicates where the * expected and actual strings differ */ public void testCompareStrings() { String greeting = "Hello"; String greetee = "World"; String whatToSay = greeting + greetee; assertEquals("Hello World", whatToSay); } public void testCompareStrings() { int[] array1 = {1,2,3,4}; int[] array2 = {5,1,2,3,4}; assertArrayEquals(array1, array2); } }
/* * Copyright (C) 2013 Intel Corporation * All rights reserved. */ package com.intel.mtwilson.setup.tasks; import com.intel.dcsg.cpg.io.Platform; import com.intel.dcsg.cpg.validation.ObjectModel; import com.intel.mtwilson.Folders; import com.intel.mtwilson.My; import com.intel.mtwilson.setup.AbstractSetupTask; import com.intel.mtwilson.setup.ConfigurationException; import com.intel.mtwilson.setup.LocalSetupTask; import com.intel.mtwilson.setup.SetupTask; import java.io.File; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.IOUtils; /** * This task checks that required paths are known such as MTWILSON_HOME, and * MTWILSON_CONF. It is not able to configure them because it cannot set * environment variables for the user (well, under Linux we could detect a * ~/.profile and then add someting like . ~/mtwilson.env if that file exists, * and create that file if it doesn't exist with the required vars...) * * @author jbuhacoff */ public class ConfigureFilesystem extends LocalSetupTask { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ConfigureFilesystem.class); private String mtwilsonHome; private String mtwilsonConf; @Override protected void configure() throws Exception { mtwilsonHome = Folders.application(); //My.filesystem().getApplicationPath(); //My.configuration().getMtWilsonHome(); mtwilsonConf = My.configuration().getDirectoryPath(); // My.filesystem().getConfigurationPath(); //My.configuration().getMtWilsonConf(); if (mtwilsonHome == null) { configuration("MTWILSON_HOME is not configured"); } if (mtwilsonConf == null) { configuration("MTWILSON_CONF is not configured"); } } @Override protected void validate() throws Exception { checkFileExists("MTWILSON_HOME", mtwilsonHome); checkFileExists("MTWILSON_CONF", mtwilsonConf); } @Override protected void execute() throws Exception { if (Platform.isWindows()) { if (winHasSetx()) { // we can set the variable! runToVoid("setx MTWILSON_HOME " + mtwilsonHome); runToVoid("setx MTWILSON_CONF " + mtwilsonConf); } runToVoid("cmd /c mkdir " + mtwilsonHome);// mkdir and set are shell commands not stand-alone executables, so if we don't prefix cmd /c we would get java.io.IOException: CreateProcess error=2, The system cannot find the file specified runToVoid("cmd /c mkdir " + mtwilsonConf);// mkdir and set are shell commands not stand-alone executables, so if we don't prefix cmd /c we would get java.io.IOException: CreateProcess error=2, The system cannot find the file specified } if (Platform.isUnix()) { runToVoid("mkdir -p "+mtwilsonHome); runToVoid("mkdir -p "+mtwilsonConf); } } private boolean winHasSetx() throws IOException { String result = runToString("where setx"); return result != null && !result.isEmpty(); } }
/* * 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.pinterest.secor.io.impl; import java.io.IOException; import java.io.StringWriter; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.Lz4Codec; import org.apache.hadoop.io.compress.SnappyCodec; import org.apache.hadoop.io.compress.GzipCodec; import org.apache.orc.CompressionKind; import org.apache.orc.OrcFile; import org.apache.orc.Reader; import org.apache.orc.RecordReader; import org.apache.orc.TypeDescription; import org.apache.orc.Writer; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.pinterest.secor.common.FileRegistry; import com.pinterest.secor.common.LogFilePath; import com.pinterest.secor.common.SecorConfig; import com.pinterest.secor.io.FileReader; import com.pinterest.secor.io.FileReaderWriterFactory; import com.pinterest.secor.io.FileWriter; import com.pinterest.secor.io.KeyValue; import com.pinterest.secor.util.ReflectionUtil; import com.pinterest.secor.util.orc.JsonFieldFiller; import com.pinterest.secor.util.orc.VectorColumnFiller; import com.pinterest.secor.util.orc.VectorColumnFiller.JsonConverter; import com.pinterest.secor.util.orc.schema.ORCSchemaProvider; /** * ORC reader/writer implementation * * @author Ashish (ashu.impetus@gmail.com) * */ public class JsonORCFileReaderWriterFactory implements FileReaderWriterFactory { private static final Logger LOG = LoggerFactory.getLogger(FileRegistry.class); private ORCSchemaProvider schemaProvider; public JsonORCFileReaderWriterFactory(SecorConfig config) throws Exception { schemaProvider = ReflectionUtil.createORCSchemaProvider( config.getORCSchemaProviderClass(), config); } @Override public FileReader BuildFileReader(LogFilePath logFilePath, CompressionCodec codec) throws Exception { return new JsonORCFileReader(logFilePath, codec); } @Override public FileWriter BuildFileWriter(LogFilePath logFilePath, CompressionCodec codec) throws Exception { return new JsonORCFileWriter(logFilePath, codec); } protected class JsonORCFileReader implements FileReader { private int rowIndex = 0; private long offset; private RecordReader rows; private VectorizedRowBatch batch; private TypeDescription schema; @SuppressWarnings("deprecation") public JsonORCFileReader(LogFilePath logFilePath, CompressionCodec codec) throws IOException { schema = schemaProvider.getSchema(logFilePath.getTopic(), logFilePath); Path path = new Path(logFilePath.getLogFilePath()); Reader reader = OrcFile.createReader(path, OrcFile.readerOptions(new Configuration(true))); offset = logFilePath.getOffset(); rows = reader.rows(); batch = reader.getSchema().createRowBatch(); rows.nextBatch(batch); } @Override public KeyValue next() throws IOException { boolean endOfBatch = false; StringWriter sw = new StringWriter(); if (rowIndex > batch.size - 1) { endOfBatch = !rows.nextBatch(batch); rowIndex = 0; } if (endOfBatch) { rows.close(); return null; } try { JsonFieldFiller.processRow(new JSONWriter(sw), batch, schema, rowIndex); } catch (JSONException e) { LOG.error("Unable to parse json {}", sw.toString()); return null; } rowIndex++; return new KeyValue(offset++, sw.toString().getBytes("UTF-8")); } @Override public void close() throws IOException { rows.close(); } } protected class JsonORCFileWriter implements FileWriter { private Gson gson = new Gson(); private Writer writer; private JsonConverter[] converters; private VectorizedRowBatch batch; private int rowIndex; private TypeDescription schema; public JsonORCFileWriter(LogFilePath logFilePath, CompressionCodec codec) throws IOException { Configuration conf = new Configuration(); Path path = new Path(logFilePath.getLogFilePath()); schema = schemaProvider.getSchema(logFilePath.getTopic(), logFilePath); List<TypeDescription> fieldTypes = schema.getChildren(); converters = new JsonConverter[fieldTypes.size()]; for (int c = 0; c < converters.length; ++c) { converters[c] = VectorColumnFiller.createConverter(fieldTypes .get(c)); } writer = OrcFile.createWriter(path, OrcFile.writerOptions(conf) .compress(resolveCompression(codec)).setSchema(schema)); batch = schema.createRowBatch(); } @Override public long getLength() throws IOException { return writer.getRawDataSize(); } @Override public void write(KeyValue keyValue) throws IOException { rowIndex = batch.size++; VectorColumnFiller.fillRow(rowIndex, converters, schema, batch, gson.fromJson(new String(keyValue.getValue()), JsonObject.class)); if (batch.size == batch.getMaxSize()) { writer.addRowBatch(batch); batch.reset(); } } @Override public void close() throws IOException { writer.addRowBatch(batch); writer.close(); } } /** * Used for returning the compression kind used in ORC * * @param codec * @return */ private CompressionKind resolveCompression(CompressionCodec codec) { if (codec instanceof Lz4Codec) return CompressionKind.LZ4; else if (codec instanceof SnappyCodec) return CompressionKind.SNAPPY; // although GZip and ZLIB are not same thing // there is no better named codec for this case, // use hadoop Gzip codec to enable ORC ZLIB compression else if (codec instanceof GzipCodec) return CompressionKind.ZLIB; else return CompressionKind.NONE; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.redhat.ceylon.compiler.typechecker.util; import java.util.HashSet; import java.util.Set; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.IntersectionType; import com.redhat.ceylon.compiler.typechecker.model.Setter; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.UnionType; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Visitor; /** * * @author kulikov */ public class ReferenceCounter extends Visitor { private Set<Declaration> referencedDeclarations = new HashSet<Declaration>(); void referenced(Declaration d) { referencedDeclarations.add(d); //TODO: check that the value is actually assigned! if (d instanceof Value) { Setter setter = ((Value) d).getSetter(); if (setter!=null) { referencedDeclarations.add(setter); } } } boolean isReferenced(Declaration d) { for (Declaration rd: referencedDeclarations) { if (rd.getContainer().equals(d.getContainer()) && rd.getName().equals(d.getName())) { return true; } } return false; } @Override public void visit(Tree.AssignmentOp that) { super.visit(that); } @Override public void visit(Tree.PostfixOperatorExpression that) { super.visit(that); } @Override public void visit(Tree.PrefixOperatorExpression that) { super.visit(that); } @Override public void visit(Tree.MemberOrTypeExpression that) { super.visit(that); Declaration d = that.getDeclaration(); if (d!=null) referenced(d); } @Override public void visit(Tree.SimpleType that) { super.visit(that); TypeDeclaration t = that.getDeclarationModel(); if (t!=null && !(t instanceof UnionType) && !(t instanceof IntersectionType)) { referenced(t); } } @Override public void visit(Tree.MemberLiteral that) { super.visit(that); Declaration d = that.getDeclaration(); if (d!=null) { referenced(d); } } }
// // From.java // // Copyright (c) 2017 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package com.couchbase.lite; import java.util.Arrays; /** * A From represents a FROM clause for specifying the data source of the query. */ public final class From extends AbstractQuery implements JoinRouter, WhereRouter, GroupByRouter, OrderByRouter, LimitRouter { //--------------------------------------------- // Constructor //--------------------------------------------- From(AbstractQuery query, DataSource dataSource) { copy(query); setFrom(dataSource); } //--------------------------------------------- // implementation of JoinRouter //--------------------------------------------- /** * Creates and chains a Joins object for specifying the JOIN clause of the query. * * @param joins The Join objects. * @return The Joins object that represents the JOIN clause of the query. */ @Override public Joins join(Join... joins) { return new Joins(this, Arrays.asList(joins)); } //--------------------------------------------- // implementation of WhereRouter //--------------------------------------------- /** * Create and chain a WHERE component for specifying the WHERE clause of the query. * * @param expression the WHERE clause expression. * @return the WHERE component. */ @Override public Where where(Expression expression) { return new Where(this, expression); } //--------------------------------------------- // implementation of GroupByRouter //--------------------------------------------- /** * Creates and chains a GroupBy object to group the query result. * * @param expressions The group by expression. * @return The GroupBy object that represents the GROUP BY clause of the query. */ @Override public GroupBy groupBy(Expression... expressions) { return new GroupBy(this, Arrays.asList(expressions)); } //--------------------------------------------- // implementation of OrderByRouter //--------------------------------------------- /** * Create and chain an ORDER BY component for specifying the ORDER BY clause of the query. * * @param orderings an array of the ORDER BY expressions. * @return the ORDER BY component. */ @Override public OrderBy orderBy(Ordering... orderings) { return new OrderBy(this, Arrays.asList(orderings)); } //--------------------------------------------- // implementation of LimitRouter //--------------------------------------------- /** * Creates and chains a Limit object to limit the number query results. * * @param limit The limit expression. * @return The Limit object that represents the LIMIT clause of the query. */ @Override public Limit limit(Expression limit) { return new Limit(this, limit, null); } /** * Creates and chains a Limit object to skip the returned results for the given offset * position and to limit the number of results to not more than the given limit value. * * @param limit The limit expression. * @param offset The offset expression. * @return The Limit object that represents the LIMIT clause of the query. */ @Override public Limit limit(Expression limit, Expression offset) { return new Limit(this, limit, offset); } }
package ru.job4j.calculate; /**Car класс для определения пробега машины * @author alexVoronin * @since 05.04.2019 * @version 1 */ public class Car { private double volume; boolean result; /**drive метод определяет оставшийся пробег машины * @param kilometer пробег */ public void drive(int kilometer) { this.volume = this.volume - kilometer; } /**fill метод определяет пробег машины после заправки * @param gas топливо */ public void fill(int gas) { this.volume = this.volume + 10 * gas; } /** * метод определяет может машина ехать или нет */ public boolean canDrive() { result = this.volume > 0; return result; } /** * метод выводит на консоль оставшийся пробег машины */ public void gasInfo() { System.out.println("I can drive" + this.volume + "kilometers."); } }
import com.hydra.tool.object.PojoConstantsUtil; /** * Created by ZhengGong on 15/8/3. * Description 挪账、结算Vo */ public class MoveAccountSettleVo { private String merchantCode; private String amountTran; private String amountNoTran; private long merchantsettleId; private long merchantsettlemoveaccountId; private String trxId; private String businessId; public String getMerchantCode() { return merchantCode; } public void setMerchantCode(String merchantCode) { this.merchantCode = merchantCode; } public String getAmountTran() { return amountTran; } public void setAmountTran(String amountTran) { this.amountTran = amountTran; } public String getAmountNoTran() { return amountNoTran; } public void setAmountNoTran(String amountNoTran) { this.amountNoTran = amountNoTran; } public long getMerchantsettleId() { return merchantsettleId; } public void setMerchantsettleId(long merchantsettleId) { this.merchantsettleId = merchantsettleId; } public long getMerchantsettlemoveaccountId() { return merchantsettlemoveaccountId; } public void setMerchantsettlemoveaccountId(long merchantsettlemoveaccountId) { this.merchantsettlemoveaccountId = merchantsettlemoveaccountId; } public String getTrxId() { return trxId; } public void setTrxId(String trxId) { this.trxId = trxId; } public String getBusinessId() { return businessId; } public void setBusinessId(String businessId) { this.businessId = businessId; } @Override public String toString() { return "MoveAccountSettleVo{" + "merchantCode='" + merchantCode + '\'' + ", amountTran='" + amountTran + '\'' + ", amountNoTran='" + amountNoTran + '\'' + ", merchantsettleId=" + merchantsettleId + ", merchantsettlemoveaccountId=" + merchantsettlemoveaccountId + ", trxId='" + trxId + '\'' + ", businessId='" + businessId + '\'' + '}'; } public static void main(String[] args) { PojoConstantsUtil.console(MoveAccountSettleVo.class); } }
package org.onvif.ver10.schema; import java.util.HashMap; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import javax.xml.namespace.QName; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.cxf.xjc.runtime.JAXBToStringStyle; /** * Describe the option of the color and its transparency. * * <p>Java class for OSDColorOptions complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="OSDColorOptions"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="Color" type="{http://www.onvif.org/ver10/schema}ColorOptions" minOccurs="0"/&gt; * &lt;element name="Transparent" type="{http://www.onvif.org/ver10/schema}IntRange" minOccurs="0"/&gt; * &lt;element name="Extension" type="{http://www.onvif.org/ver10/schema}OSDColorOptionsExtension" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;anyAttribute processContents='lax'/&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "OSDColorOptions", propOrder = { "color", "transparent", "extension" }) public class OSDColorOptions { @XmlElement(name = "Color") protected ColorOptions color; @XmlElement(name = "Transparent") protected IntRange transparent; @XmlElement(name = "Extension") protected OSDColorOptionsExtension extension; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); /** * Gets the value of the color property. * * @return * possible object is * {@link ColorOptions } * */ public ColorOptions getColor() { return color; } /** * Sets the value of the color property. * * @param value * allowed object is * {@link ColorOptions } * */ public void setColor(ColorOptions value) { this.color = value; } /** * Gets the value of the transparent property. * * @return * possible object is * {@link IntRange } * */ public IntRange getTransparent() { return transparent; } /** * Sets the value of the transparent property. * * @param value * allowed object is * {@link IntRange } * */ public void setTransparent(IntRange value) { this.transparent = value; } /** * Gets the value of the extension property. * * @return * possible object is * {@link OSDColorOptionsExtension } * */ public OSDColorOptionsExtension getExtension() { return extension; } /** * Sets the value of the extension property. * * @param value * allowed object is * {@link OSDColorOptionsExtension } * */ public void setExtension(OSDColorOptionsExtension value) { this.extension = value; } /** * Gets a map that contains attributes that aren't bound to any typed property on this class. * * <p> * the map is keyed by the name of the attribute and * the value is the string value of the attribute. * * the map returned by this method is live, and you can add new attribute * by updating the map directly. Because of this design, there's no setter. * * * @return * always non-null */ public Map<QName, String> getOtherAttributes() { return otherAttributes; } /** * Generates a String representation of the contents of this type. * This is an extension method, produced by the 'ts' xjc plugin * */ @Override public String toString() { return ToStringBuilder.reflectionToString(this, JAXBToStringStyle.DEFAULT_STYLE); } }
/* * 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. * * Other licenses: * ----------------------------------------------------------------------------- * Commercial licenses for this work are available. These replace the above * ASL 2.0 and offer limited warranties, support, maintenance, and commercial * database integrations. * * For more information, please visit: http://www.jooq.org/licenses * * * * * * * * * * * * * * * * */ package org.jooq.impl; import org.jooq.Binding; import org.jooq.Check; import org.jooq.Converter; import org.jooq.DataType; import org.jooq.ForeignKey; import org.jooq.Identity; import org.jooq.Index; import org.jooq.Name; import org.jooq.OrderField; import org.jooq.Parameter; import org.jooq.Record; import org.jooq.Schema; import org.jooq.Sequence; import org.jooq.Table; import org.jooq.TableField; import org.jooq.UniqueKey; /** * A utility class that grants access to internal API, to be used only by * generated code. * <p> * This type is for JOOQ INTERNAL USE only. Do not reference directly. * * @author Lukas Eder */ @org.jooq.Internal public final class Internal { /** * Factory method for embeddable types. */ public static final <R extends Record, T extends Record> TableField<R, T> createEmbeddable(Name name, Class<T> recordType, Table<R> table, TableField<R, ?>... fields) { return new EmbeddableTableField<>(name, recordType, table, fields); } /** * Factory method for indexes. */ public static final Index createIndex(String name, Table<?> table, OrderField<?>[] sortFields, boolean unique) { return createIndex(DSL.name(name), table, sortFields, unique); } /** * Factory method for indexes. */ public static final Index createIndex(Name name, Table<?> table, OrderField<?>[] sortFields, boolean unique) { return new IndexImpl(name, table, sortFields, null, unique); } /** * Factory method for identities. */ public static final <R extends Record, T> Identity<R, T> createIdentity(Table<R> table, TableField<R, T> field) { return new IdentityImpl<>(table, field); } /** * Factory method for unique keys. */ @SafeVarargs public static final <R extends Record> UniqueKey<R> createUniqueKey(Table<R> table, TableField<R, ?>... fields) { return new UniqueKeyImpl<>(table, fields, true); } /** * Factory method for unique keys. */ @SafeVarargs public static final <R extends Record> UniqueKey<R> createUniqueKey(Table<R> table, String name, TableField<R, ?>... fields) { return new UniqueKeyImpl<>(table, name, fields, true); } /** * Factory method for foreign keys. */ @SafeVarargs public static final <R extends Record, U extends Record> ForeignKey<R, U> createForeignKey(UniqueKey<U> key, Table<R> table, TableField<R, ?>... fields) { return createForeignKey(key, table, null, fields); } /** * Factory method for foreign keys. */ @SafeVarargs public static final <R extends Record, U extends Record> ForeignKey<R, U> createForeignKey(UniqueKey<U> key, Table<R> table, String name, TableField<R, ?>... fields) { ForeignKey<R, U> result = new ReferenceImpl<>(key, table, name, fields, true); if (key instanceof UniqueKeyImpl) ((UniqueKeyImpl<U>) key).references.add(result); return result; } /** * Factory method for sequences. */ public static final <T extends Number> Sequence<T> createSequence(String name, Schema schema, DataType<T> type) { return new SequenceImpl<>(name, schema, type, false); } /** * Factory method for sequences. */ public static final <T extends Number> Sequence<T> createSequence(String name, Schema schema, DataType<T> type, Number startWith, Number incrementBy, Number minvalue, Number maxvalue, boolean cycle, Number cache) { return new SequenceImpl<>( DSL.name(name), schema, type, false, startWith != null ? Tools.field(startWith, type) : null, incrementBy != null ? Tools.field(incrementBy, type) : null, minvalue != null ? Tools.field(minvalue, type) : null, maxvalue != null ? Tools.field(maxvalue, type) : null, cycle, cache != null ? Tools.field(cache, type) : null ); } /** * Factory method for check constraints. */ public static final <R extends Record> Check<R> createCheck(Table<R> table, Name name, String condition) { return new CheckImpl<>(table, name, DSL.condition(condition), true); } /** * Factory method for path aliases. */ public static final Name createPathAlias(Table<?> child, ForeignKey<?, ?> path) { Name name = DSL.name(path.getName()); if (child instanceof TableImpl) { Table<?> ancestor = ((TableImpl<?>) child).child; if (ancestor != null) name = createPathAlias(ancestor, ((TableImpl<?>) child).childPath).append(name); else name = child.getQualifiedName().append(name); } return DSL.name("alias_" + Tools.hash(name)); } /** * Factory method for parameters. */ public static final <T> Parameter<T> createParameter(String name, DataType<T> type, boolean isDefaulted, boolean isUnnamed) { return createParameter(name, type, isDefaulted, isUnnamed, null, null); } /** * Factory method for parameters. */ public static final <T, U> Parameter<U> createParameter(String name, DataType<T> type, boolean isDefaulted, boolean isUnnamed, Converter<T, U> converter) { return createParameter(name, type, isDefaulted, isUnnamed, converter, null); } /** * Factory method for parameters. */ public static final <T, U> Parameter<U> createParameter(String name, DataType<T> type, boolean isDefaulted, boolean isUnnamed, Binding<T, U> binding) { return createParameter(name, type, isDefaulted, isUnnamed, null, binding); } /** * Factory method for parameters. */ @SuppressWarnings("unchecked") public static final <T, X, U> Parameter<U> createParameter(String name, DataType<T> type, boolean isDefaulted, boolean isUnnamed, Converter<X, U> converter, Binding<T, X> binding) { final Binding<T, U> actualBinding = DefaultBinding.newBinding(converter, type, binding); final DataType<U> actualType = converter == null && binding == null ? (DataType<U>) type : type.asConvertedDataType(actualBinding); return new ParameterImpl<>(name, actualType, actualBinding, isDefaulted, isUnnamed); } private Internal() {} }
/* * 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. */ /* * Changes for TIBCO Project SnappyData data platform. * * Portions Copyright (c) 2017-2020 TIBCO Software Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ package org.apache.spark.unsafe.types; import javax.annotation.Nonnull; import java.io.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Map; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.KryoSerializable; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.google.common.primitives.Ints; import org.apache.spark.unsafe.Native; import org.apache.spark.unsafe.Platform; import org.apache.spark.unsafe.array.ByteArrayMethods; import org.apache.spark.unsafe.hash.Murmur3_x86_32; import static org.apache.spark.unsafe.Platform.*; /** * A UTF-8 String for internal Spark use. * <p> * A String encoded in UTF-8 as an Array[Byte], which can be used for comparison, * search, see http://en.wikipedia.org/wiki/UTF-8 for details. * <p> * Note: This is not designed for general use cases, should not be used outside SQL. */ public final class UTF8String implements Comparable<UTF8String>, Externalizable, KryoSerializable, Cloneable { // These are only updated by readExternal() or read() @Nonnull private Object base; private long offset; private int numBytes; private transient int hash; private transient boolean isAscii; public Object getBaseObject() { return base; } public long getBaseOffset() { return offset; } /** * A char in UTF-8 encoding can take 1-4 bytes depending on the first byte which * indicates the size of the char. See Unicode standard in page 126, Table 3-6: * http://www.unicode.org/versions/Unicode10.0.0/UnicodeStandard-10.0.pdf * * Binary Hex Comments * 0xxxxxxx 0x00..0x7F Only byte of a 1-byte character encoding * 10xxxxxx 0x80..0xBF Continuation bytes (1-3 continuation bytes) * 110xxxxx 0xC0..0xDF First byte of a 2-byte character encoding * 1110xxxx 0xE0..0xEF First byte of a 3-byte character encoding * 11110xxx 0xF0..0xF7 First byte of a 4-byte character encoding * * As a consequence of the well-formedness conditions specified in * Table 3-7 (page 126), the following byte values are disallowed in UTF-8: * C0–C1, F5–FF. */ private static byte[] bytesOfCodePointInUTF8 = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x00..0x0F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x10..0x1F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x20..0x2F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x30..0x3F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x40..0x4F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x50..0x5F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x60..0x6F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 0x70..0x7F // Continuation bytes cannot appear as the first byte 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x80..0x8F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x90..0x9F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xA0..0xAF 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0xB0..0xBF 0, 0, // 0xC0..0xC1 - disallowed in UTF-8 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xC2..0xCF 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // 0xD0..0xDF 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // 0xE0..0xEF 4, 4, 4, 4, 4, // 0xF0..0xF4 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // 0xF5..0xFF - disallowed in UTF-8 }; private static final boolean IS_LITTLE_ENDIAN = ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN; private static final UTF8String COMMA_UTF8 = UTF8String.fromString(","); public static final UTF8String EMPTY_UTF8 = UTF8String.fromString(""); /** * Creates an UTF8String from byte array, which should be encoded in UTF-8. * * Note: `bytes` will be hold by returned UTF8String. */ public static UTF8String fromBytes(byte[] bytes) { if (bytes != null) { return new UTF8String(bytes, BYTE_ARRAY_OFFSET, bytes.length); } else { return null; } } /** * Creates an UTF8String from byte array, which should be encoded in UTF-8. * * Note: `bytes` will be hold by returned UTF8String. */ public static UTF8String fromBytes(byte[] bytes, int offset, int numBytes) { if (bytes != null) { return new UTF8String(bytes, BYTE_ARRAY_OFFSET + offset, numBytes); } else { return null; } } /** * Creates an UTF8String from given address (base and offset) and length. */ public static UTF8String fromAddress(Object base, long offset, int numBytes) { return new UTF8String(base, offset, numBytes); } /** * Creates an UTF8String from String. */ public static UTF8String fromString(String str) { return str == null ? null : fromBytes(str.getBytes(StandardCharsets.UTF_8)); } /** * Creates an UTF8String that contains `length` spaces. */ public static UTF8String blankString(int length) { byte[] spaces = new byte[length]; Arrays.fill(spaces, (byte) ' '); return fromBytes(spaces); } protected UTF8String(Object base, long offset, int numBytes) { this.base = base; this.offset = offset; this.numBytes = numBytes; } // for serialization public UTF8String() { this(null, 0, 0); } /** * Writes the content of this string into a memory address, identified by an object and an offset. * The target memory address must already been allocated, and have enough space to hold all the * bytes in this string. */ public void writeToMemory(Object target, long targetOffset) { Platform.copyMemory(base, offset, target, targetOffset, numBytes); } public void writeTo(ByteBuffer buffer) { assert(buffer.hasArray()); byte[] target = buffer.array(); int offset = buffer.arrayOffset(); int pos = buffer.position(); writeToMemory(target, Platform.BYTE_ARRAY_OFFSET + offset + pos); buffer.position(pos + numBytes); } /** * Returns a {@link ByteBuffer} wrapping the base object if it is a byte array * or a copy of the data if the base object is not a byte array. * * Unlike getBytes this will not create a copy the array if this is a slice. */ @Nonnull public ByteBuffer getByteBuffer() { if (base instanceof byte[] && offset >= BYTE_ARRAY_OFFSET) { final byte[] bytes = (byte[]) base; // the offset includes an object header... this is only needed for unsafe copies final long arrayOffset = offset - BYTE_ARRAY_OFFSET; // verify that the offset and length points somewhere inside the byte array // and that the offset can safely be truncated to a 32-bit integer if ((long) bytes.length < arrayOffset + numBytes) { throw new ArrayIndexOutOfBoundsException(); } return ByteBuffer.wrap(bytes, (int) arrayOffset, numBytes); } else { return ByteBuffer.wrap(getBytes()); } } public void writeTo(OutputStream out) throws IOException { final ByteBuffer bb = this.getByteBuffer(); assert(bb.hasArray()); // similar to Utils.writeByteBuffer but without the spark-core dependency out.write(bb.array(), bb.arrayOffset() + bb.position(), bb.remaining()); } /** * Returns the number of bytes for a code point with the first byte as `b` * @param b The first byte of a code point */ private static int numBytesForFirstByte(final byte b) { if (b >= 0) return 1; final int offset = b & 0xFF; byte numBytes = bytesOfCodePointInUTF8[offset]; return (numBytes == 0) ? 1: numBytes; // Skip the first byte disallowed in UTF-8 } /** * Returns the number of bytes */ public int numBytes() { return numBytes; } /** * Returns the number of code points in it. */ public int numChars() { if (isAscii) return numBytes; final long endOffset = offset + numBytes; int len = 0; for (long offset = this.offset; offset < endOffset; offset += numBytesForFirstByte(Platform.getByte(base, offset))) { len++; } if (len == numBytes) isAscii = true; return len; } /** * Returns a 64-bit integer that can be used as the prefix used in sorting. */ public long getPrefix() { // Since JVMs are either 4-byte aligned or 8-byte aligned, we check the size of the string. // If size is 0, just return 0. // If size is between 0 and 4 (inclusive), assume data is 4-byte aligned under the hood and // use a getInt to fetch the prefix. // If size is greater than 4, assume we have at least 8 bytes of data to fetch. // After getting the data, we use a mask to mask out data that is not part of the string. long p; long mask = 0; if (IS_LITTLE_ENDIAN) { if (numBytes >= 8) { p = Platform.getLong(base, offset); } else if (numBytes > 4) { p = Platform.getLong(base, offset); mask = (1L << (8 - numBytes) * 8) - 1; } else if (numBytes > 0) { p = (long) Platform.getInt(base, offset); mask = (1L << (8 - numBytes) * 8) - 1; } else { p = 0; } p = java.lang.Long.reverseBytes(p); } else { // byteOrder == ByteOrder.BIG_ENDIAN if (numBytes >= 8) { p = Platform.getLong(base, offset); } else if (numBytes > 4) { p = Platform.getLong(base, offset); mask = (1L << (8 - numBytes) * 8) - 1; } else if (numBytes > 0) { p = ((long) Platform.getInt(base, offset)) << 32; mask = (1L << (8 - numBytes) * 8) - 1; } else { p = 0; } } p &= ~mask; return p; } /** * Returns the underline bytes, will be a copy of it if it's part of another array. */ public byte[] getBytes() { // avoid copy if `base` is `byte[]` if (offset == BYTE_ARRAY_OFFSET && base instanceof byte[] && ((byte[]) base).length == numBytes) { return (byte[]) base; } else { byte[] bytes = new byte[numBytes]; copyMemory(base, offset, bytes, BYTE_ARRAY_OFFSET, numBytes); return bytes; } } /** * Returns a substring of this. * @param start the position of first code point * @param until the position after last code point, exclusive. */ public UTF8String substring(final int start, final int until) { if (until <= start || start >= numBytes) { return EMPTY_UTF8; } int i = 0; int c = 0; while (i < numBytes && c < start) { i += numBytesForFirstByte(getByte(i)); c += 1; } int j = i; while (i < numBytes && c < until) { i += numBytesForFirstByte(getByte(i)); c += 1; } if (i > j) { byte[] bytes = new byte[i - j]; copyMemory(base, offset + j, bytes, BYTE_ARRAY_OFFSET, i - j); return fromBytes(bytes); } else { return EMPTY_UTF8; } } public UTF8String substringSQL(int pos, int length) { // Information regarding the pos calculation: // Hive and SQL use one-based indexing for SUBSTR arguments but also accept zero and // negative indices for start positions. If a start index i is greater than 0, it // refers to element i-1 in the sequence. If a start index i is less than 0, it refers // to the -ith element before the end of the sequence. If a start index i is 0, it // refers to the first element. int len = numChars(); // `len + pos` does not overflow as `len >= 0`. int start = (pos > 0) ? pos -1 : ((pos < 0) ? len + pos : 0); int end; if ((long) start + length > Integer.MAX_VALUE) { end = Integer.MAX_VALUE; } else if ((long) start + length < Integer.MIN_VALUE) { end = Integer.MIN_VALUE; } else { end = start + length; } return substring(start, end); } /** * Returns whether this contains `substring` or not. */ public boolean contains(final UTF8String substring) { final int slen = substring.numBytes; if (slen == 0) { return true; } final Object base = this.base; final int len = this.numBytes; // noinspection ConstantConditions if (base == null && len >= Native.MIN_JNI_SIZE && substring.base == null && Native.isLoaded()) { return Native.containsString(offset, len, substring.offset, slen); } final byte first = substring.getByte(0); long offset = this.offset; final long end = offset + len - slen; for (; offset <= end; offset++) { if (Platform.getByte(base, offset) == first && ByteArrayMethods.arrayEquals( base, offset, substring.base, substring.offset, slen)) return true; } return false; } /** * Returns the byte at position `i`. */ public byte getByte(int i) { return Platform.getByte(base, offset + i); } private boolean matchAt(final UTF8String s, int pos) { if (s.numBytes + pos > numBytes || pos < 0) { return false; } return ByteArrayMethods.arrayEquals(base, offset + pos, s.base, s.offset, s.numBytes); } public boolean startsWith(final UTF8String prefix) { return matchAt(prefix, 0); } public boolean endsWith(final UTF8String suffix) { return matchAt(suffix, numBytes - suffix.numBytes); } /** * Returns the upper case of this string */ public UTF8String toUpperCase() { if (numBytes == 0) { return EMPTY_UTF8; } byte[] bytes = new byte[numBytes]; bytes[0] = (byte) Character.toTitleCase(getByte(0)); for (int i = 0; i < numBytes; i++) { byte b = getByte(i); if (numBytesForFirstByte(b) != 1) { // fallback return toUpperCaseSlow(); } int upper = Character.toUpperCase((int) b); if (upper > 127) { // fallback return toUpperCaseSlow(); } bytes[i] = (byte) upper; } return fromBytes(bytes); } private UTF8String toUpperCaseSlow() { return fromString(toString().toUpperCase()); } /** * Returns the lower case of this string */ public UTF8String toLowerCase() { if (numBytes == 0) { return EMPTY_UTF8; } byte[] bytes = new byte[numBytes]; bytes[0] = (byte) Character.toTitleCase(getByte(0)); for (int i = 0; i < numBytes; i++) { byte b = getByte(i); if (numBytesForFirstByte(b) != 1) { // fallback return toLowerCaseSlow(); } int lower = Character.toLowerCase((int) b); if (lower > 127) { // fallback return toLowerCaseSlow(); } bytes[i] = (byte) lower; } return fromBytes(bytes); } private UTF8String toLowerCaseSlow() { return fromString(toString().toLowerCase()); } /** * Returns the title case of this string, that could be used as title. */ public UTF8String toTitleCase() { if (numBytes == 0) { return EMPTY_UTF8; } byte[] bytes = new byte[numBytes]; for (int i = 0; i < numBytes; i++) { byte b = getByte(i); if (i == 0 || getByte(i - 1) == ' ') { if (numBytesForFirstByte(b) != 1) { // fallback return toTitleCaseSlow(); } int upper = Character.toTitleCase(b); if (upper > 127) { // fallback return toTitleCaseSlow(); } bytes[i] = (byte) upper; } else { bytes[i] = b; } } return fromBytes(bytes); } private UTF8String toTitleCaseSlow() { StringBuffer sb = new StringBuffer(); String s = toString(); sb.append(s); sb.setCharAt(0, Character.toTitleCase(sb.charAt(0))); for (int i = 1; i < s.length(); i++) { if (sb.charAt(i - 1) == ' ') { sb.setCharAt(i, Character.toTitleCase(sb.charAt(i))); } } return fromString(sb.toString()); } /* * Returns the index of the string `match` in this String. This string has to be a comma separated * list. If `match` contains a comma 0 will be returned. If the `match` isn't part of this String, * 0 will be returned, else the index of match (1-based index) */ public int findInSet(UTF8String match) { if (match.contains(COMMA_UTF8)) { return 0; } int n = 1, lastComma = -1; for (int i = 0; i < numBytes; i++) { if (getByte(i) == (byte) ',') { if (i - (lastComma + 1) == match.numBytes && ByteArrayMethods.arrayEquals(base, offset + (lastComma + 1), match.base, match.offset, match.numBytes)) { return n; } lastComma = i; n++; } } if (numBytes - (lastComma + 1) == match.numBytes && ByteArrayMethods.arrayEquals(base, offset + (lastComma + 1), match.base, match.offset, match.numBytes)) { return n; } return 0; } /** * Copy the bytes from the current UTF8String, and make a new UTF8String. * @param start the start position of the current UTF8String in bytes. * @param end the end position of the current UTF8String in bytes. * @return a new UTF8String in the position of [start, end] of current UTF8String bytes. */ private UTF8String copyUTF8String(int start, int end) { int len = end - start + 1; byte[] newBytes = new byte[len]; copyMemory(base, offset + start, newBytes, BYTE_ARRAY_OFFSET, len); return UTF8String.fromBytes(newBytes); } public UTF8String trim() { int s = 0; // skip all of the space (0x20) in the left side while (s < this.numBytes && getByte(s) == 0x20) s++; if (s == this.numBytes) { // empty string return EMPTY_UTF8; } // skip all of the space (0x20) in the right side int e = this.numBytes - 1; while (e > s && getByte(e) == 0x20) e--; return copyUTF8String(s, e); } /** * Based on the given trim string, trim this string starting from both ends * This method searches for each character in the source string, removes the character if it is * found in the trim string, stops at the first not found. It calls the trimLeft first, then * trimRight. It returns a new string in which both ends trim characters have been removed. * @param trimString the trim character string */ public UTF8String trim(UTF8String trimString) { if (trimString != null) { return trimLeft(trimString).trimRight(trimString); } else { return null; } } public UTF8String trimLeft() { int s = 0; // skip all of the space (0x20) in the left side while (s < this.numBytes && getByte(s) == 0x20) s++; if (s == this.numBytes) { // empty string return EMPTY_UTF8; } else { return copyUTF8String(s, this.numBytes - 1); } } /** * Based on the given trim string, trim this string starting from left end * This method searches each character in the source string starting from the left end, removes * the character if it is in the trim string, stops at the first character which is not in the * trim string, returns the new string. * @param trimString the trim character string */ public UTF8String trimLeft(UTF8String trimString) { if (trimString == null) return null; // the searching byte position in the source string int srchIdx = 0; // the first beginning byte position of a non-matching character int trimIdx = 0; while (srchIdx < numBytes) { UTF8String searchChar = copyUTF8String( srchIdx, srchIdx + numBytesForFirstByte(this.getByte(srchIdx)) - 1); int searchCharBytes = searchChar.numBytes; // try to find the matching for the searchChar in the trimString set if (trimString.find(searchChar, 0) >= 0) { trimIdx += searchCharBytes; } else { // no matching, exit the search break; } srchIdx += searchCharBytes; } if (trimIdx >= numBytes) { // empty string return EMPTY_UTF8; } else { return copyUTF8String(trimIdx, numBytes - 1); } } public UTF8String trimRight() { int e = numBytes - 1; // skip all of the space (0x20) in the right side while (e >= 0 && getByte(e) == 0x20) e--; if (e < 0) { // empty string return EMPTY_UTF8; } else { return copyUTF8String(0, e); } } /** * Based on the given trim string, trim this string starting from right end * This method searches each character in the source string starting from the right end, * removes the character if it is in the trim string, stops at the first character which is not * in the trim string, returns the new string. * @param trimString the trim character string */ public UTF8String trimRight(UTF8String trimString) { if (trimString == null) return null; int charIdx = 0; // number of characters from the source string int numChars = 0; // array of character length for the source string int[] stringCharLen = new int[numBytes]; // array of the first byte position for each character in the source string int[] stringCharPos = new int[numBytes]; // build the position and length array while (charIdx < numBytes) { stringCharPos[numChars] = charIdx; stringCharLen[numChars] = numBytesForFirstByte(getByte(charIdx)); charIdx += stringCharLen[numChars]; numChars ++; } // index trimEnd points to the first no matching byte position from the right side of // the source string. int trimEnd = numBytes - 1; while (numChars > 0) { UTF8String searchChar = copyUTF8String( stringCharPos[numChars - 1], stringCharPos[numChars - 1] + stringCharLen[numChars - 1] - 1); if (trimString.find(searchChar, 0) >= 0) { trimEnd -= stringCharLen[numChars - 1]; } else { break; } numChars --; } if (trimEnd < 0) { // empty string return EMPTY_UTF8; } else { return copyUTF8String(0, trimEnd); } } public UTF8String reverse() { byte[] result = new byte[this.numBytes]; int i = 0; // position in byte while (i < numBytes) { int len = numBytesForFirstByte(getByte(i)); copyMemory(this.base, this.offset + i, result, BYTE_ARRAY_OFFSET + result.length - i - len, len); i += len; } return UTF8String.fromBytes(result); } public UTF8String repeat(int times) { if (times <= 0) { return EMPTY_UTF8; } byte[] newBytes = new byte[numBytes * times]; copyMemory(this.base, this.offset, newBytes, BYTE_ARRAY_OFFSET, numBytes); int copied = 1; while (copied < times) { int toCopy = Math.min(copied, times - copied); System.arraycopy(newBytes, 0, newBytes, copied * numBytes, numBytes * toCopy); copied += toCopy; } return UTF8String.fromBytes(newBytes); } /** * Returns the position of the first occurrence of substr in * current string from the specified position (0-based index). * * @param v the string to be searched * @param start the start position of the current string for searching * @return the position of the first occurrence of substr, if not found, -1 returned. */ public int indexOf(UTF8String v, int start) { if (v.numBytes() == 0) { return 0; } // locate to the start position. int i = 0; // position in byte int c = 0; // position in character while (i < numBytes && c < start) { i += numBytesForFirstByte(getByte(i)); c += 1; } do { if (i + v.numBytes > numBytes) { return -1; } if (ByteArrayMethods.arrayEquals(base, offset + i, v.base, v.offset, v.numBytes)) { return c; } i += numBytesForFirstByte(getByte(i)); c += 1; } while (i < numBytes); return -1; } /** * Find the `str` from left to right. */ private int find(UTF8String str, int start) { assert (str.numBytes > 0); while (start <= numBytes - str.numBytes) { if (ByteArrayMethods.arrayEquals(base, offset + start, str.base, str.offset, str.numBytes)) { return start; } start += 1; } return -1; } /** * Find the `str` from right to left. */ private int rfind(UTF8String str, int start) { assert (str.numBytes > 0); while (start >= 0) { if (ByteArrayMethods.arrayEquals(base, offset + start, str.base, str.offset, str.numBytes)) { return start; } start -= 1; } return -1; } /** * Returns the substring from string str before count occurrences of the delimiter delim. * If count is positive, everything the left of the final delimiter (counting from left) is * returned. If count is negative, every to the right of the final delimiter (counting from the * right) is returned. subStringIndex performs a case-sensitive match when searching for delim. */ public UTF8String subStringIndex(UTF8String delim, int count) { if (delim.numBytes == 0 || count == 0) { return EMPTY_UTF8; } if (count > 0) { int idx = -1; while (count > 0) { idx = find(delim, idx + 1); if (idx >= 0) { count --; } else { // can not find enough delim return this; } } if (idx == 0) { return EMPTY_UTF8; } byte[] bytes = new byte[idx]; copyMemory(base, offset, bytes, BYTE_ARRAY_OFFSET, idx); return fromBytes(bytes); } else { int idx = numBytes - delim.numBytes + 1; count = -count; while (count > 0) { idx = rfind(delim, idx - 1); if (idx >= 0) { count --; } else { // can not find enough delim return this; } } if (idx + delim.numBytes == numBytes) { return EMPTY_UTF8; } int size = numBytes - delim.numBytes - idx; byte[] bytes = new byte[size]; copyMemory(base, offset + idx + delim.numBytes, bytes, BYTE_ARRAY_OFFSET, size); return fromBytes(bytes); } } /** * Returns str, right-padded with pad to a length of len * For example: * ('hi', 5, '??') =&gt; 'hi???' * ('hi', 1, '??') =&gt; 'h' */ public UTF8String rpad(int len, UTF8String pad) { int spaces = len - this.numChars(); // number of char need to pad if (spaces <= 0 || pad.numBytes() == 0) { // no padding at all, return the substring of the current string return substring(0, len); } else { int padChars = pad.numChars(); int count = spaces / padChars; // how many padding string needed // the partial string of the padding UTF8String remain = pad.substring(0, spaces - padChars * count); byte[] data = new byte[this.numBytes + pad.numBytes * count + remain.numBytes]; copyMemory(this.base, this.offset, data, BYTE_ARRAY_OFFSET, this.numBytes); int offset = this.numBytes; int idx = 0; while (idx < count) { copyMemory(pad.base, pad.offset, data, BYTE_ARRAY_OFFSET + offset, pad.numBytes); ++ idx; offset += pad.numBytes; } copyMemory(remain.base, remain.offset, data, BYTE_ARRAY_OFFSET + offset, remain.numBytes); return UTF8String.fromBytes(data); } } /** * Returns str, left-padded with pad to a length of len. * For example: * ('hi', 5, '??') =&gt; '???hi' * ('hi', 1, '??') =&gt; 'h' */ public UTF8String lpad(int len, UTF8String pad) { int spaces = len - this.numChars(); // number of char need to pad if (spaces <= 0 || pad.numBytes() == 0) { // no padding at all, return the substring of the current string return substring(0, len); } else { int padChars = pad.numChars(); int count = spaces / padChars; // how many padding string needed // the partial string of the padding UTF8String remain = pad.substring(0, spaces - padChars * count); byte[] data = new byte[this.numBytes + pad.numBytes * count + remain.numBytes]; int offset = 0; int idx = 0; while (idx < count) { copyMemory(pad.base, pad.offset, data, BYTE_ARRAY_OFFSET + offset, pad.numBytes); ++ idx; offset += pad.numBytes; } copyMemory(remain.base, remain.offset, data, BYTE_ARRAY_OFFSET + offset, remain.numBytes); offset += remain.numBytes; copyMemory(this.base, this.offset, data, BYTE_ARRAY_OFFSET + offset, numBytes()); return UTF8String.fromBytes(data); } } /** * Concatenates input strings together into a single string. Returns null if any input is null. */ public static UTF8String concat(UTF8String... inputs) { // Compute the total length of the result. long totalLength = 0; for (int i = 0; i < inputs.length; i++) { if (inputs[i] != null) { totalLength += (long)inputs[i].numBytes; } else { return null; } } // Allocate a new byte array, and copy the inputs one by one into it. final byte[] result = new byte[Ints.checkedCast(totalLength)]; int offset = 0; for (int i = 0; i < inputs.length; i++) { int len = inputs[i].numBytes; copyMemory( inputs[i].base, inputs[i].offset, result, BYTE_ARRAY_OFFSET + offset, len); offset += len; } return fromBytes(result); } /** * Concatenates input strings together into a single string using the separator. * A null input is skipped. For example, concat(",", "a", null, "c") would yield "a,c". */ public static UTF8String concatWs(UTF8String separator, UTF8String... inputs) { if (separator == null) { return null; } int numInputBytes = 0; // total number of bytes from the inputs int numInputs = 0; // number of non-null inputs for (int i = 0; i < inputs.length; i++) { if (inputs[i] != null) { numInputBytes += inputs[i].numBytes; numInputs++; } } if (numInputs == 0) { // Return an empty string if there is no input, or all the inputs are null. return EMPTY_UTF8; } // Allocate a new byte array, and copy the inputs one by one into it. // The size of the new array is the size of all inputs, plus the separators. final byte[] result = new byte[numInputBytes + (numInputs - 1) * separator.numBytes]; int offset = 0; for (int i = 0, j = 0; i < inputs.length; i++) { if (inputs[i] != null) { int len = inputs[i].numBytes; copyMemory( inputs[i].base, inputs[i].offset, result, BYTE_ARRAY_OFFSET + offset, len); offset += len; j++; // Add separator if this is not the last input. if (j < numInputs) { copyMemory( separator.base, separator.offset, result, BYTE_ARRAY_OFFSET + offset, separator.numBytes); offset += separator.numBytes; } } } return fromBytes(result); } public UTF8String[] split(UTF8String pattern, int limit) { String[] splits = toString().split(pattern.toString(), limit); UTF8String[] res = new UTF8String[splits.length]; for (int i = 0; i < res.length; i++) { res[i] = fromString(splits[i]); } return res; } public UTF8String replace(UTF8String search, UTF8String replace) { if (EMPTY_UTF8.equals(search)) { return this; } String replaced = toString().replace( search.toString(), replace.toString()); return fromString(replaced); } // TODO: Need to use `Code Point` here instead of Char in case the character longer than 2 bytes public UTF8String translate(Map<Character, Character> dict) { String srcStr = this.toString(); StringBuilder sb = new StringBuilder(); for(int k = 0; k< srcStr.length(); k++) { if (null == dict.get(srcStr.charAt(k))) { sb.append(srcStr.charAt(k)); } else if ('\0' != dict.get(srcStr.charAt(k))){ sb.append(dict.get(srcStr.charAt(k))); } } return fromString(sb.toString()); } /** * Wrapper over `long` to allow result of parsing long from string to be accessed via reference. * This is done solely for better performance and is not expected to be used by end users. */ public static class LongWrapper implements Serializable { public transient long value = 0; } /** * Wrapper over `int` to allow result of parsing integer from string to be accessed via reference. * This is done solely for better performance and is not expected to be used by end users. * * {@link LongWrapper} could have been used here but using `int` directly save the extra cost of * conversion from `long` to `int` */ public static class IntWrapper implements Serializable { public transient int value = 0; } /** * Parses this UTF8String to long. * * Note that, in this method we accumulate the result in negative format, and convert it to * positive format at the end, if this string is not started with '-'. This is because min value * is bigger than max value in digits, e.g. Long.MAX_VALUE is '9223372036854775807' and * Long.MIN_VALUE is '-9223372036854775808'. * * This code is mostly copied from LazyLong.parseLong in Hive. * * @param toLongResult If a valid `long` was parsed from this UTF8String, then its value would * be set in `toLongResult` * @return true if the parsing was successful else false */ public boolean toLong(LongWrapper toLongResult) { if (numBytes == 0) { return false; } byte b = getByte(0); final boolean negative = b == '-'; int offset = 0; if (negative || b == '+') { offset++; if (numBytes == 1) { return false; } } final byte separator = '.'; final int radix = 10; final long stopValue = Long.MIN_VALUE / radix; long result = 0; while (offset < numBytes) { b = getByte(offset); offset++; if (b == separator) { // We allow decimals and will return a truncated integral in that case. // Therefore we won't throw an exception here (checking the fractional // part happens below.) break; } int digit; if (b >= '0' && b <= '9') { digit = b - '0'; } else { return false; } // We are going to process the new digit and accumulate the result. However, before doing // this, if the result is already smaller than the stopValue(Long.MIN_VALUE / radix), then // result * 10 will definitely be smaller than minValue, and we can stop. if (result < stopValue) { return false; } result = result * radix - digit; // Since the previous result is less than or equal to stopValue(Long.MIN_VALUE / radix), we // can just use `result > 0` to check overflow. If result overflows, we should stop. if (result > 0) { return false; } } // This is the case when we've encountered a decimal separator. The fractional // part will not change the number, but we will verify that the fractional part // is well formed. while (offset < numBytes) { byte currentByte = getByte(offset); if (currentByte < '0' || currentByte > '9') { return false; } offset++; } if (!negative) { result = -result; if (result < 0) { return false; } } toLongResult.value = result; return true; } /** * Parses this UTF8String to int. * * Note that, in this method we accumulate the result in negative format, and convert it to * positive format at the end, if this string is not started with '-'. This is because min value * is bigger than max value in digits, e.g. Integer.MAX_VALUE is '2147483647' and * Integer.MIN_VALUE is '-2147483648'. * * This code is mostly copied from LazyInt.parseInt in Hive. * * Note that, this method is almost same as `toLong`, but we leave it duplicated for performance * reasons, like Hive does. * * @param intWrapper If a valid `int` was parsed from this UTF8String, then its value would * be set in `intWrapper` * @return true if the parsing was successful else false */ public boolean toInt(IntWrapper intWrapper) { if (numBytes == 0) { return false; } byte b = getByte(0); final boolean negative = b == '-'; int offset = 0; if (negative || b == '+') { offset++; if (numBytes == 1) { return false; } } final byte separator = '.'; final int radix = 10; final int stopValue = Integer.MIN_VALUE / radix; int result = 0; while (offset < numBytes) { b = getByte(offset); offset++; if (b == separator) { // We allow decimals and will return a truncated integral in that case. // Therefore we won't throw an exception here (checking the fractional // part happens below.) break; } int digit; if (b >= '0' && b <= '9') { digit = b - '0'; } else { return false; } // We are going to process the new digit and accumulate the result. However, before doing // this, if the result is already smaller than the stopValue(Integer.MIN_VALUE / radix), then // result * 10 will definitely be smaller than minValue, and we can stop if (result < stopValue) { return false; } result = result * radix - digit; // Since the previous result is less than or equal to stopValue(Integer.MIN_VALUE / radix), // we can just use `result > 0` to check overflow. If result overflows, we should stop if (result > 0) { return false; } } // This is the case when we've encountered a decimal separator. The fractional // part will not change the number, but we will verify that the fractional part // is well formed. while (offset < numBytes) { byte currentByte = getByte(offset); if (currentByte < '0' || currentByte > '9') { return false; } offset++; } if (!negative) { result = -result; if (result < 0) { return false; } } intWrapper.value = result; return true; } public boolean toShort(IntWrapper intWrapper) { if (toInt(intWrapper)) { int intValue = intWrapper.value; short result = (short) intValue; if (result == intValue) { return true; } } return false; } public boolean toByte(IntWrapper intWrapper) { if (toInt(intWrapper)) { int intValue = intWrapper.value; byte result = (byte) intValue; if (result == intValue) { return true; } } return false; } @Override public String toString() { return new String(getBytes(), StandardCharsets.UTF_8); } @Override public UTF8String clone() { UTF8String newString = fromBytes(getBytes()); if (isAscii) { newString.isAscii = true; } return newString; } public UTF8String cloneIfRequired() { if (offset == BYTE_ARRAY_OFFSET && ((byte[])base).length == numBytes) { return this; } else { final int numBytes = this.numBytes; final byte[] bytes = new byte[numBytes]; copyMemory(base, offset, bytes, BYTE_ARRAY_OFFSET, numBytes); UTF8String newString = fromAddress(bytes, BYTE_ARRAY_OFFSET, numBytes); if (isAscii) { newString.isAscii = true; } return newString; } } public UTF8String copy() { byte[] bytes = new byte[numBytes]; copyMemory(base, offset, bytes, BYTE_ARRAY_OFFSET, numBytes); return fromBytes(bytes); } @Override public int compareTo(@Nonnull final UTF8String other) { return compare(other); } public int compare(final UTF8String other) { int len = Math.min(numBytes, other.numBytes); // for the case that compare will fail in first few bytes itself, the overhead // of JNI call is too high /* // noinspection ConstantConditions if (leftBase == null && rightBase == null && len >= Native.MIN_JNI_SIZE && Native.isLoaded()) { final int result = Native.compareString(leftOffset, rightOffset, len); return result != 0 ? result : (numBytes - other.numBytes); } */ int wordMax = (len / 8) * 8; long roffset = other.offset; Object rbase = other.base; for (int i = 0; i < wordMax; i += 8) { long left = getLong(base, offset + i); long right = getLong(rbase, roffset + i); if (left != right) { if (IS_LITTLE_ENDIAN) { return Long.compareUnsigned(Long.reverseBytes(left), Long.reverseBytes(right)); } else { return Long.compareUnsigned(left, right); } } } for (int i = wordMax; i < len; i++) { // In UTF-8, the byte should be unsigned, so we should compare them as unsigned int. int res = (getByte(i) & 0xFF) - (Platform.getByte(rbase, roffset + i) & 0xFF); if (res != 0) { return res; } } return numBytes - other.numBytes; } @Override public boolean equals(final Object other) { if (other instanceof UTF8String) { UTF8String o = (UTF8String) other; if (numBytes != o.numBytes) { return false; } return ByteArrayMethods.arrayEquals(base, offset, o.base, o.offset, numBytes); } else { return false; } } public boolean equals(final UTF8String o) { final int numBytes = this.numBytes; return o != null && numBytes == o.numBytes && ByteArrayMethods.arrayEquals( base, offset, o.base, o.offset, numBytes); } /** * Levenshtein distance is a metric for measuring the distance of two strings. The distance is * defined by the minimum number of single-character edits (i.e. insertions, deletions or * substitutions) that are required to change one of the strings into the other. */ public int levenshteinDistance(UTF8String other) { // Implementation adopted from org.apache.common.lang3.StringUtils.getLevenshteinDistance int n = numChars(); int m = other.numChars(); if (n == 0) { return m; } else if (m == 0) { return n; } UTF8String s, t; if (n <= m) { s = this; t = other; } else { s = other; t = this; int swap; swap = n; n = m; m = swap; } int[] p = new int[n + 1]; int[] d = new int[n + 1]; int[] swap; int i, i_bytes, j, j_bytes, num_bytes_j, cost; for (i = 0; i <= n; i++) { p[i] = i; } for (j = 0, j_bytes = 0; j < m; j_bytes += num_bytes_j, j++) { num_bytes_j = numBytesForFirstByte(t.getByte(j_bytes)); d[0] = j + 1; for (i = 0, i_bytes = 0; i < n; i_bytes += numBytesForFirstByte(s.getByte(i_bytes)), i++) { if (s.getByte(i_bytes) != t.getByte(j_bytes) || num_bytes_j != numBytesForFirstByte(s.getByte(i_bytes))) { cost = 1; } else { cost = (ByteArrayMethods.arrayEquals(t.base, t.offset + j_bytes, s.base, s.offset + i_bytes, num_bytes_j)) ? 0 : 1; } d[i + 1] = Math.min(Math.min(d[i] + 1, p[i + 1] + 1), p[i] + cost); } swap = p; p = d; d = swap; } return p[n]; } @Override public int hashCode() { final int h = this.hash; if (h != 0) return h; return (this.hash = Murmur3_x86_32.hashUnsafeBytes( base, offset, numBytes, 42)); } /** * Soundex mapping table */ private static final byte[] US_ENGLISH_MAPPING = {'0', '1', '2', '3', '0', '1', '2', '7', '0', '2', '2', '4', '5', '5', '0', '1', '2', '6', '2', '3', '0', '1', '7', '2', '0', '2'}; /** * Encodes a string into a Soundex value. Soundex is an encoding used to relate similar names, * but can also be used as a general purpose scheme to find word with similar phonemes. * https://en.wikipedia.org/wiki/Soundex */ public UTF8String soundex() { if (numBytes == 0) { return EMPTY_UTF8; } byte b = getByte(0); if ('a' <= b && b <= 'z') { b -= 32; } else if (b < 'A' || 'Z' < b) { // first character must be a letter return this; } byte[] sx = {'0', '0', '0', '0'}; sx[0] = b; int sxi = 1; int idx = b - 'A'; byte lastCode = US_ENGLISH_MAPPING[idx]; for (int i = 1; i < numBytes; i++) { b = getByte(i); if ('a' <= b && b <= 'z') { b -= 32; } else if (b < 'A' || 'Z' < b) { // not a letter, skip it lastCode = '0'; continue; } idx = b - 'A'; byte code = US_ENGLISH_MAPPING[idx]; if (code == '7') { // ignore it } else { if (code != '0' && code != lastCode) { sx[sxi++] = code; if (sxi > 3) break; } lastCode = code; } } return UTF8String.fromBytes(sx); } public void writeExternal(ObjectOutput out) throws IOException { byte[] bytes = getBytes(); out.writeInt(bytes.length); out.write(bytes); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { offset = BYTE_ARRAY_OFFSET; numBytes = in.readInt(); base = new byte[numBytes]; in.readFully((byte[]) base); } @Override public void write(Kryo kryo, Output out) { byte[] bytes = getBytes(); out.writeInt(bytes.length); out.write(bytes); } @Override public void read(Kryo kryo, Input in) { this.offset = BYTE_ARRAY_OFFSET; this.numBytes = in.readInt(); this.base = new byte[numBytes]; in.read((byte[]) base); } }
// ----------------------------------------------------------------------- // <copyright file="Contact.java" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ----------------------------------------------------------------------- package com.microsoft.store.partnercenter.models; /** * The contact. */ public class Contact { /** * Gets or sets the first name. */ private String __FirstName; public String getFirstName() { return __FirstName; } public void setFirstName( String value ) { __FirstName = value; } /** * Gets or sets the last name. */ private String __LastName; public String getLastName() { return __LastName; } public void setLastName( String value ) { __LastName = value; } /** * Gets or sets the email. */ private String __Email; public String getEmail() { return __Email; } public void setEmail( String value ) { __Email = value; } /** * Gets or sets the phone number. */ private String __PhoneNumber; public String getPhoneNumber() { return __PhoneNumber; } public void setPhoneNumber( String value ) { __PhoneNumber = value; } }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE129_Improper_Validation_of_Array_Index__PropertiesFile_array_write_no_check_13.java Label Definition File: CWE129_Improper_Validation_of_Array_Index.label.xml Template File: sources-sinks-13.tmpl.java */ /* * @description * CWE: 129 Improper Validation of Array Index * BadSource: PropertiesFile Read data from a .properties file (in property named data) * GoodSource: A hardcoded non-zero, non-min, non-max, even number * Sinks: array_write_no_check * GoodSink: Write to array after verifying index * BadSink : Write to array without any verification of index * Flow Variant: 13 Control flow: if(IO.STATIC_FINAL_FIVE==5) and if(IO.STATIC_FINAL_FIVE!=5) * * */ import java.util.Properties; import java.io.FileInputStream; import java.io.IOException; import java.util.logging.Level; public class CWE129_Improper_Validation_of_Array_Index__PropertiesFile_array_write_no_check_13 extends AbstractTestCase { public void bad() throws Throwable { int data; if (IO.STATIC_FINAL_FIVE==5) { data = Integer.MIN_VALUE; /* Initialize data */ /* retrieve the property */ { Properties properties = new Properties(); FileInputStream streamFileInput = null; try { streamFileInput = new FileInputStream("../common/config.properties"); properties.load(streamFileInput); /* POTENTIAL FLAW: Read data from a .properties file */ String stringNumber = properties.getProperty("data"); if (stringNumber != null) // avoid NPD incidental warnings { try { data = Integer.parseInt(stringNumber.trim()); } catch(NumberFormatException exceptNumberFormat) { IO.logger.log(Level.WARNING, "Number format exception parsing data from string", exceptNumberFormat); } } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO); } finally { /* Close stream reading object */ try { if (streamFileInput != null) { streamFileInput.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO); } } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = 0; } if (IO.STATIC_FINAL_FIVE==5) { /* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */ int array[] = { 0, 1, 2, 3, 4 }; /* POTENTIAL FLAW: Attempt to write to array at location data, which may be outside the array bounds */ array[data] = 42; /* Skip reading back data from array since that may be another out of bounds operation */ } } /* goodG2B1() - use goodsource and badsink by changing first IO.STATIC_FINAL_FIVE==5 to IO.STATIC_FINAL_FIVE!=5 */ private void goodG2B1() throws Throwable { int data; if (IO.STATIC_FINAL_FIVE!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = 0; } else { /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } if (IO.STATIC_FINAL_FIVE==5) { /* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */ int array[] = { 0, 1, 2, 3, 4 }; /* POTENTIAL FLAW: Attempt to write to array at location data, which may be outside the array bounds */ array[data] = 42; /* Skip reading back data from array since that may be another out of bounds operation */ } } /* goodG2B2() - use goodsource and badsink by reversing statements in first if */ private void goodG2B2() throws Throwable { int data; if (IO.STATIC_FINAL_FIVE==5) { /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */ data = 2; } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = 0; } if (IO.STATIC_FINAL_FIVE==5) { /* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */ int array[] = { 0, 1, 2, 3, 4 }; /* POTENTIAL FLAW: Attempt to write to array at location data, which may be outside the array bounds */ array[data] = 42; /* Skip reading back data from array since that may be another out of bounds operation */ } } /* goodB2G1() - use badsource and goodsink by changing second IO.STATIC_FINAL_FIVE==5 to IO.STATIC_FINAL_FIVE!=5 */ private void goodB2G1() throws Throwable { int data; if (IO.STATIC_FINAL_FIVE==5) { data = Integer.MIN_VALUE; /* Initialize data */ /* retrieve the property */ { Properties properties = new Properties(); FileInputStream streamFileInput = null; try { streamFileInput = new FileInputStream("../common/config.properties"); properties.load(streamFileInput); /* POTENTIAL FLAW: Read data from a .properties file */ String stringNumber = properties.getProperty("data"); if (stringNumber != null) // avoid NPD incidental warnings { try { data = Integer.parseInt(stringNumber.trim()); } catch(NumberFormatException exceptNumberFormat) { IO.logger.log(Level.WARNING, "Number format exception parsing data from string", exceptNumberFormat); } } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO); } finally { /* Close stream reading object */ try { if (streamFileInput != null) { streamFileInput.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO); } } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = 0; } if (IO.STATIC_FINAL_FIVE!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.writeLine("Benign, fixed string"); } else { /* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */ int array[] = { 0, 1, 2, 3, 4 }; /* FIX: Verify index before writing to array at location data */ if (data >= 0 && data < array.length) { array[data] = 42; } else { IO.writeLine("Array index out of bounds"); } } } /* goodB2G2() - use badsource and goodsink by reversing statements in second if */ private void goodB2G2() throws Throwable { int data; if (IO.STATIC_FINAL_FIVE==5) { data = Integer.MIN_VALUE; /* Initialize data */ /* retrieve the property */ { Properties properties = new Properties(); FileInputStream streamFileInput = null; try { streamFileInput = new FileInputStream("../common/config.properties"); properties.load(streamFileInput); /* POTENTIAL FLAW: Read data from a .properties file */ String stringNumber = properties.getProperty("data"); if (stringNumber != null) // avoid NPD incidental warnings { try { data = Integer.parseInt(stringNumber.trim()); } catch(NumberFormatException exceptNumberFormat) { IO.logger.log(Level.WARNING, "Number format exception parsing data from string", exceptNumberFormat); } } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO); } finally { /* Close stream reading object */ try { if (streamFileInput != null) { streamFileInput.close(); } } catch (IOException exceptIO) { IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO); } } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = 0; } if (IO.STATIC_FINAL_FIVE==5) { /* Need to ensure that the array is of size > 3 and < 101 due to the GoodSource and the large_fixed BadSource */ int array[] = { 0, 1, 2, 3, 4 }; /* FIX: Verify index before writing to array at location data */ if (data >= 0 && data < array.length) { array[data] = 42; } else { IO.writeLine("Array index out of bounds"); } } } public void good() throws Throwable { goodG2B1(); goodG2B2(); goodB2G1(); goodB2G2(); } /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { mainFromParent(args); } }
package carpet.script; import carpet.script.bundled.BundledModule; import carpet.CarpetSettings; import carpet.CarpetServer; import carpet.script.bundled.FileModule; import carpet.script.bundled.Module; import carpet.script.exception.InvalidCallbackException; import carpet.script.value.FunctionValue; import carpet.script.value.MapValue; import carpet.script.value.StringValue; import carpet.script.value.ThreadValue; import carpet.script.value.Value; import carpet.utils.Messenger; import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.tree.CommandNode; import net.minecraft.server.MinecraftServer; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.util.WorldSavePath; import net.minecraft.util.math.BlockPos; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import static net.minecraft.server.command.CommandManager.argument; import static net.minecraft.server.command.CommandManager.literal; public class CarpetScriptServer { //make static for now, but will change that later: public final MinecraftServer server; public CarpetScriptHost globalHost; public Map<String, CarpetScriptHost> modules; public long tickStart; public boolean stopAll; private Set<String> holyMoly; public CarpetEventServer events; private static final List<Module> bundledModuleData = new ArrayList<>(); public static void registerBuiltInScript(BundledModule app) { bundledModuleData.add(app); } static { registerBuiltInScript(BundledModule.carpetNative("camera", false)); registerBuiltInScript(BundledModule.carpetNative("overlay", false)); registerBuiltInScript(BundledModule.carpetNative("event_test", false)); registerBuiltInScript(BundledModule.carpetNative("stats_test", false)); registerBuiltInScript(BundledModule.carpetNative("math", true)); registerBuiltInScript(BundledModule.carpetNative("chunk_display", false)); registerBuiltInScript(BundledModule.carpetNative("ai_tracker", false)); } public CarpetScriptServer(MinecraftServer server) { this.server = server; init(); } private void init() { ScriptHost.systemGlobals.clear(); events = new CarpetEventServer(server); modules = new HashMap<>(); tickStart = 0L; stopAll = false; holyMoly = server.getCommandManager().getDispatcher().getRoot().getChildren().stream().map(CommandNode::getName).collect(Collectors.toSet()); globalHost = CarpetScriptHost.create(this, null, false, null); } public void loadAllWorldScripts() { if (CarpetSettings.scriptsAutoload) { Messenger.m(server.getCommandSource(), "Auto-loading world scarpet apps"); for (String moduleName: listAvailableModules(false)) { addScriptHost(server.getCommandSource(), moduleName, true, true); } } } public Module getModule(String name, boolean allowLibraries) { File folder = server.getSavePath(WorldSavePath.ROOT).resolve("scripts").toFile(); File[] listOfFiles = folder.listFiles(); if (listOfFiles != null) for (File script : listOfFiles) { if (script.getName().equalsIgnoreCase(name+".sc")) { return new FileModule(script); } if (allowLibraries && script.getName().equalsIgnoreCase(name+".scl")) { return new FileModule(script); } } for (Module moduleData : bundledModuleData) { if (moduleData.getName().equalsIgnoreCase(name) && (allowLibraries || !moduleData.isLibrary())) { return moduleData; } } return null; } public List<String> listAvailableModules(boolean includeBuiltIns) { List<String> moduleNames = new ArrayList<>(); if (includeBuiltIns) { for (Module mi : bundledModuleData) { if (!mi.isLibrary()) moduleNames.add(mi.getName()); } } File folder = server.getSavePath(WorldSavePath.ROOT).resolve("scripts").toFile(); File[] listOfFiles = folder.listFiles(); if (listOfFiles == null) return moduleNames; for (File script : listOfFiles) { if (script.getName().endsWith(".sc")) { String name = script.getName().replaceFirst("\\.sc","").toLowerCase(Locale.ROOT); moduleNames.add(name); } } return moduleNames; } public ScriptHost getHostByName(String name) { if (name == null) return globalHost; return modules.get(name); } public boolean addScriptHost(ServerCommandSource source, String name, boolean perPlayer, boolean autoload) { //TODO add per player modules to support player actions better on a server name = name.toLowerCase(Locale.ROOT); boolean reload = false; if (modules.containsKey(name)) { removeScriptHost(source, name, false); reload = true; } Module module = getModule(name, false); if (module == null) { Messenger.m(source, "r Failed to add "+name+" app"); return false; } CarpetScriptHost newHost = CarpetScriptHost.create(this, module, perPlayer, source); if (newHost == null) { Messenger.m(source, "r Failed to add "+name+" app"); return false; } if (module == null) { Messenger.m(source, "r Unable to locate the app, but created empty "+name+" app instead"); modules.put(name, newHost); return true; } String code = module.getCode(); if (module.getCode() == null) { Messenger.m(source, "r Unable to load "+name+" app - not found"); return false; } modules.put(name, newHost); if (autoload && !newHost.persistenceRequired) { removeScriptHost(source, name, false); return false; } //addEvents(source, name); addCommand(source, name, reload); return true; } private void addCommand(ServerCommandSource source, String hostName, boolean isReload) { ScriptHost host = modules.get(hostName); String loaded = isReload?"reloaded":"loaded"; if (host == null) { return; } if (host.getFunction("__command") == null) { Messenger.m(source, "gi "+hostName+" app "+loaded+"."); return; } if (holyMoly.contains(hostName)) { Messenger.m(source, "gi "+hostName+" app "+loaded+" with no command."); Messenger.m(source, "gi Tried to mask vanilla command."); return; } LiteralArgumentBuilder<ServerCommandSource> command = literal(hostName). requires((player) -> modules.containsKey(hostName)). executes( (c) -> { Value response = modules.get(hostName).retrieveForExecution(c.getSource()). handleCommand(c.getSource(),"__command", null, ""); if (!response.isNull()) Messenger.m(c.getSource(), "gi "+response.getString()); return (int)response.readInteger(); }); for (String function : host.globaFunctionNames(host.main, s -> !s.startsWith("_")).sorted().collect(Collectors.toList())) { command = command. then(literal(function). requires((player) -> modules.containsKey(hostName) && modules.get(hostName).getFunction(function) != null). executes( (c) -> { Value response = modules.get(hostName).retrieveForExecution(c.getSource()). handleCommand(c.getSource(), function,null,""); if (!response.isNull()) Messenger.m(c.getSource(),"gi "+response.getString()); return (int)response.readInteger(); }). then(argument("args...", StringArgumentType.greedyString()). executes( (c) -> { Value response = modules.get(hostName).retrieveForExecution(c.getSource()). handleCommand(c.getSource(), function,null, StringArgumentType.getString(c, "args...")); if (!response.isNull()) Messenger.m(c.getSource(), "gi "+response.getString()); return (int)response.readInteger(); }))); } Messenger.m(source, "gi "+hostName+" app "+loaded+" with /"+hostName+" command"); server.getCommandManager().getDispatcher().register(command); CarpetServer.settingsManager.notifyPlayersCommandsChanged(); } public boolean removeScriptHost(ServerCommandSource source, String name, boolean notifySource) { name = name.toLowerCase(Locale.ROOT); if (!modules.containsKey(name)) { if (notifySource) Messenger.m(source, "r No such app found: ", "wb " + name); return false; } // stop all events associated with name events.removeAllHostEvents(name); modules.get(name).onClose(); modules.remove(name); CarpetServer.settingsManager.notifyPlayersCommandsChanged(); if (notifySource) Messenger.m(source, "gi Removed "+name+" app"); return true; } public boolean runas(ServerCommandSource source, String hostname, FunctionValue udf, List<LazyValue> argv) { return runas(BlockPos.ORIGIN, source, hostname, udf, argv); } public boolean runas(BlockPos origin, ServerCommandSource source, String hostname, FunctionValue udf, List<LazyValue> argv) { CarpetScriptHost host = globalHost; try { if (hostname != null) host = modules.get(hostname).retrieveForExecution(source); host.callUDF(origin, source, udf, argv); } catch (NullPointerException | InvalidCallbackException npe) { return false; } return true; } public void tick() { events.tick(); for (CarpetScriptHost host : modules.values()) { host.tick(); } } public void onClose() { for (ScriptHost host : modules.values()) { host.onClose(); } ThreadValue.shutdown(); } public void reload(MinecraftServer server) { Map<String, Boolean> apps = new HashMap<>(); modules.forEach((s, h) -> apps.put(s, h.perUser)); apps.keySet().forEach(s -> removeScriptHost(server.getCommandSource(), s, false)); events.clearAll(); init(); apps.forEach((s, pp) -> addScriptHost(server.getCommandSource(), s, pp, false)); } }