text
stringlengths 7
1.01M
|
|---|
/*
* Copyright (c) 1995, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.applet;
import java.awt.Image;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.Iterator;
/**
* This interface corresponds to an applet's environment: the document
* containing the applet and the other applets in the same document.
* <p>
* The methods in this interface can be used by an applet to obtain information
* about its environment.
*
* @author Arthur van Hoff
* @since 1.0
* @deprecated The Applet API is deprecated, no replacement.
*/
@Deprecated(since = "9", forRemoval = true)
@SuppressWarnings("removal")
public interface AppletContext {
/**
* Creates an audio clip.
*
* @param url an absolute {@code URL} giving the location of the audio clip
* @return the audio clip at the specified {@code URL}
*/
AudioClip getAudioClip(URL url);
/**
* Returns an {@code Image} object that can then be painted on the screen.
* The {@code url} argument that is passed as an argument must specify an
* absolute {@code URL}.
* <p>
* This method always returns immediately, whether or not the image exists.
* When the applet attempts to draw the image on the screen, the data will
* be loaded. The graphics primitives that draw the image will incrementally
* paint on the screen.
*
* @param url an absolute {@code URL} giving the location of the image
* @return the image at the specified {@code URL}
* @see java.awt.Image
*/
Image getImage(URL url);
/**
* Finds and returns the applet in the document represented by this applet
* context with the given name. The name can be set in the HTML tag by
* setting the {@code name} attribute.
*
* @param name an applet name
* @return the applet with the given name, or {@code null} if not found
*/
Applet getApplet(String name);
/**
* Finds all the applets in the document represented by this applet context.
*
* @return an enumeration of all applets in the document represented by this
* applet context
*/
Enumeration<Applet> getApplets();
/**
* Requests that the browser or applet viewer show the Web page indicated by
* the {@code url} argument. The browser or applet viewer determines which
* window or frame to display the Web page. This method may be ignored by
* applet contexts that are not browsers.
*
* @param url an absolute {@code URL} giving the location of the document
*/
void showDocument(URL url);
/**
* Requests that the browser or applet viewer show the Web page indicated by
* the {@code url} argument. The {@code target} argument indicates in which
* HTML frame the document is to be displayed. The target argument is
* interpreted as follows:
*
* <table class="striped">
* <caption>Target arguments and their descriptions</caption>
* <thead>
* <tr>
* <th scope="col">Target Argument
* <th scope="col">Description
* </thead>
* <tbody>
* <tr>
* <th scope="row">{@code "_self"}
* <td>Show in the window and frame that contain the applet.
* <tr>
* <th scope="row">{@code "_parent"}
* <td>Show in the applet's parent frame. If the applet's frame has no
* parent frame, acts the same as "_self".
* <tr>
* <th scope="row">{@code "_top"}
* <td>Show in the top-level frame of the applet's window. If the
* applet's frame is the top-level frame, acts the same as "_self".
* <tr>
* <th scope="row">{@code "_blank"}
* <td>Show in a new, unnamed top-level window.
* <tr>
* <th scope="row"><i>name</i>
* <td>Show in the frame or window named <i>name</i>. If a target named
* <i>name</i> does not already exist, a new top-level window with the
* specified name is created, and the document is shown there.
* </tbody>
* </table>
* <p>
* An applet viewer or browser is free to ignore {@code showDocument}.
*
* @param url an absolute {@code URL} giving the location of the document
* @param target a {@code String} indicating where to display the page
*/
public void showDocument(URL url, String target);
/**
* Requests that the argument string be displayed in the "status window".
* Many browsers and applet viewers provide such a window, where the
* application can inform users of its current state.
*
* @param status a string to display in the status window
*/
void showStatus(String status);
/**
* Associates the specified stream with the specified key in this applet
* context. If the applet context previously contained a mapping for this
* key, the old value is replaced.
* <p>
* For security reasons, mapping of streams and keys exists for each
* codebase. In other words, applet from one codebase cannot access the
* streams created by an applet from a different codebase
*
* @param key key with which the specified value is to be associated
* @param stream stream to be associated with the specified key. If this
* parameter is {@code null}, the specified key is removed in this
* applet context.
* @throws IOException if the stream size exceeds a certain size limit. Size
* limit is decided by the implementor of this interface.
* @since 1.4
*/
public void setStream(String key, InputStream stream) throws IOException;
/**
* Returns the stream to which specified key is associated within this
* applet context. Returns {@code null} if the applet context contains no
* stream for this key.
* <p>
* For security reasons, mapping of streams and keys exists for each
* codebase. In other words, applet from one codebase cannot access the
* streams created by an applet from a different codebase.
*
* @param key key whose associated stream is to be returned
* @return the stream to which this applet context maps the key
* @since 1.4
*/
public InputStream getStream(String key);
/**
* Finds all the keys of the streams in this applet context.
* <p>
* For security reasons, mapping of streams and keys exists for each
* codebase. In other words, applet from one codebase cannot access the
* streams created by an applet from a different codebase.
*
* @return an {@code Iterator} of all the names of the streams in this
* applet context
* @since 1.4
*/
public Iterator<String> getStreamKeys();
}
|
package com.codepath.project.cinetrailer;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.ErrorReason;
import com.google.android.youtube.player.YouTubePlayer.PlaybackEventListener;
import com.google.android.youtube.player.YouTubePlayer.PlayerStateChangeListener;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class YoutubeActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener{
String youtubeTrailerID;
private static final int PORTRAIT_ORIENTATION = Build.VERSION.SDK_INT < 9
? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
: ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_youtube);
Intent intent = getIntent();
String id = intent.getStringExtra("id");
String url = "https://api.themoviedb.org/3/movie/" + id + "/videos?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed";
fetchMovieDataOKHttp(url);
}
@Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
player.setFullscreen(true);
player.setPlayerStateChangeListener(playerStateChangeListener);
player.setPlaybackEventListener(playbackEventListener);
/** Start buffering **/
if (!wasRestored) {
player.loadVideo(youtubeTrailerID);
player.play();
}
}
@Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult result) {
Toast.makeText(this, "Failured to Initialize!", Toast.LENGTH_LONG).show();
}
private PlaybackEventListener playbackEventListener = new PlaybackEventListener() {
@Override
public void onBuffering(boolean arg0) {
}
@Override
public void onPaused() {
}
@Override
public void onPlaying() {
}
@Override
public void onSeekTo(int arg0) {
}
@Override
public void onStopped() {
}
};
private PlayerStateChangeListener playerStateChangeListener = new PlayerStateChangeListener() {
@Override
public void onAdStarted() {
}
@Override
public void onError(ErrorReason arg0) {
}
@Override
public void onLoaded(String arg0) {
}
@Override
public void onLoading() {
}
@Override
public void onVideoEnded() {
}
@Override
public void onVideoStarted() {
}
};
public void fetchMovieDataOKHttp(String url) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
call.cancel();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String myResponse = response.body().string();
YoutubeActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
JSONObject json = new JSONObject(myResponse);
Log.d("debug", "received success");
JSONArray movieJsonResults = null;
try {
movieJsonResults = json.getJSONArray("results");
JSONObject jsonObject = movieJsonResults.getJSONObject(0);
youtubeTrailerID = jsonObject.getString("key");
YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.ivYoutube);
youTubePlayerView.initialize("a07e22bc18f5cb106bfe4cc1f83ad8ed", YoutubeActivity.this);
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
}
|
package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 智慧餐厅规则模型
*
* @author auto create
* @since 1.0, 2018-04-03 21:31:27
*/
public class ConditionItemPattern extends AlipayObject {
private static final long serialVersionUID = 2165386835627756767L;
/**
* 智慧餐厅用户规则操作符,EQ表示相等,GT表示大于,GTEQ表示大于等于,LT表示小于,LTEQ表示小于等于
*/
@ApiField("logical_operator")
private String logicalOperator;
/**
* 操作对应的值; 值>0
*/
@ApiField("operation_value")
private String operationValue;
/**
* 人群规则项:目前共支持九种标记规则,分别是:用户在商家下的交易金额(30,60,90,180,365)TRADE_AMT(单位:YUAN) 、用户在商家下的交易笔数(30,60,90,180,365)TRADE_CNT(单位:COUNT), 用户在商家下的笔单价(30,60,90,180,365)PCT_AMT(单位:YUAN), 用户在商家下的领券量(30,60,90,180,365)APPLY_VOUCHER_CNT((单位:TICKET), 用户在商家下的核券量(30,60,90,180,365) VERIFY_VOUCHER_CNT(单位:TICKET) 、用户在商家下的最后一次消费距离当前天数 LAST_PAY_DATE(单位:DAY)、用户在商家下最后一次交易金额 LAST_PAY_AMT(单位:YUAN)、用户家庭位置距离该PID下最近门店的距离HOME_SHOP_DIS((单位:KM)、用户工作位置距离该PID下最近门店的距离WORK_SHOP_DIS(单位:KM)
*/
@ApiField("operator_rule")
private String operatorRule;
/**
* 描述周期字段;30,60,90,180,365;周期字段创建规则:消费金额,消费笔数,笔单价,领券数,核销券数时必填
*/
@ApiField("period")
private String period;
/**
* 单位描述,DAY("DAY", "天"), KM("KM", "千米"), COUNT("COUNT","笔数") TICKET("TICKET","券") YUAN("YUAN","元")
*/
@ApiField("rule_unit")
private String ruleUnit;
public String getLogicalOperator() {
return this.logicalOperator;
}
public void setLogicalOperator(String logicalOperator) {
this.logicalOperator = logicalOperator;
}
public String getOperationValue() {
return this.operationValue;
}
public void setOperationValue(String operationValue) {
this.operationValue = operationValue;
}
public String getOperatorRule() {
return this.operatorRule;
}
public void setOperatorRule(String operatorRule) {
this.operatorRule = operatorRule;
}
public String getPeriod() {
return this.period;
}
public void setPeriod(String period) {
this.period = period;
}
public String getRuleUnit() {
return this.ruleUnit;
}
public void setRuleUnit(String ruleUnit) {
this.ruleUnit = ruleUnit;
}
}
|
package com.battlelancer.seriesguide.ui.dialogs;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v4.os.AsyncTaskCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import com.battlelancer.seriesguide.R;
import com.battlelancer.seriesguide.settings.TraktCredentials;
import com.battlelancer.seriesguide.util.TraktTools;
import com.battlelancer.seriesguide.util.tasks.BaseRateItemTask;
import com.battlelancer.seriesguide.util.tasks.RateEpisodeTask;
import com.battlelancer.seriesguide.util.tasks.RateMovieTask;
import com.battlelancer.seriesguide.util.tasks.RateShowTask;
import com.uwetrottmann.trakt5.enums.Rating;
import java.util.List;
/**
* Displays a 10 value rating scale. If a rating is clicked it will be stored to the database and
* sent to trakt (if the user is connected).
*/
public class RateDialogFragment extends AppCompatDialogFragment {
/**
* Display a {@link RateDialogFragment} to rate an episode.
*/
public static void displayRateDialog(Context context, FragmentManager fragmentManager,
int episodeTvdbId) {
if (!TraktCredentials.ensureCredentials(context)) {
return;
}
RateDialogFragment newFragment = newInstanceEpisode(episodeTvdbId);
newFragment.show(fragmentManager, "ratedialog");
}
private interface InitBundle {
String ITEM_TYPE = "item-type";
String ITEM_ID = "item-id";
}
private static final String ITEM_SHOW = "show";
private static final String ITEM_EPISODE = "episode";
private static final String ITEM_MOVIE = "movie";
/**
* Create {@link RateDialogFragment} to rate a show.
*/
public static RateDialogFragment newInstanceShow(int showTvdbId) {
RateDialogFragment f = new RateDialogFragment();
Bundle args = new Bundle();
args.putString(InitBundle.ITEM_TYPE, ITEM_SHOW);
args.putInt(InitBundle.ITEM_ID, showTvdbId);
f.setArguments(args);
return f;
}
/**
* Create {@link RateDialogFragment} to rate an episode.
*/
public static RateDialogFragment newInstanceEpisode(int episodeTvdbId) {
RateDialogFragment f = new RateDialogFragment();
Bundle args = new Bundle();
args.putString(InitBundle.ITEM_TYPE, ITEM_EPISODE);
args.putInt(InitBundle.ITEM_ID, episodeTvdbId);
f.setArguments(args);
return f;
}
/**
* Create {@link RateDialogFragment} to rate a movie.
*/
public static RateDialogFragment newInstanceMovie(int movieTmdbId) {
RateDialogFragment f = new RateDialogFragment();
Bundle args = new Bundle();
args.putString(InitBundle.ITEM_TYPE, ITEM_MOVIE);
args.putInt(InitBundle.ITEM_ID, movieTmdbId);
f.setArguments(args);
return f;
}
@BindViews({
R.id.rating1,
R.id.rating2,
R.id.rating3,
R.id.rating4,
R.id.rating5,
R.id.rating6,
R.id.rating7,
R.id.rating8,
R.id.rating9,
R.id.rating10
}) List<Button> ratingButtons;
private Unbinder unbinder;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder;
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
@SuppressLint("InflateParams") View layout = inflater.inflate(R.layout.dialog_trakt_rate,
null);
unbinder = ButterKnife.bind(this, layout);
for (int i = 0; i < ratingButtons.size(); i++) {
Button ratingButton = ratingButtons.get(i);
ratingButton.setText(TraktTools.buildUserRatingString(getContext(), i + 1));
}
// rating buttons from 1 (worst) to 10 (best)
ratingButtons.get(0).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
rate(Rating.WEAKSAUCE);
}
});
ratingButtons.get(1).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
rate(Rating.TERRIBLE);
}
});
ratingButtons.get(2).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
rate(Rating.BAD);
}
});
ratingButtons.get(3).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
rate(Rating.POOR);
}
});
ratingButtons.get(4).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
rate(Rating.MEH);
}
});
ratingButtons.get(5).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
rate(Rating.FAIR);
}
});
ratingButtons.get(6).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
rate(Rating.GOOD);
}
});
ratingButtons.get(7).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
rate(Rating.GREAT);
}
});
ratingButtons.get(8).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
rate(Rating.SUPERB);
}
});
ratingButtons.get(9).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
rate(Rating.TOTALLYNINJA);
}
});
builder = new AlertDialog.Builder(getActivity());
builder.setView(layout);
return builder.create();
}
private void rate(Rating rating) {
Bundle args = getArguments();
String itemType = args.getString(InitBundle.ITEM_TYPE);
if (itemType == null) {
return;
}
int itemId = args.getInt(InitBundle.ITEM_ID);
BaseRateItemTask task = null;
switch (itemType) {
case ITEM_MOVIE: {
task = new RateMovieTask(getContext(), rating, itemId);
break;
}
case ITEM_SHOW: {
task = new RateShowTask(getContext(), rating, itemId);
break;
}
case ITEM_EPISODE: {
task = new RateEpisodeTask(getContext(), rating, itemId);
break;
}
}
if (task != null) {
AsyncTaskCompat.executeParallel(task);
}
// guard against onClick being called after onSaveInstanceState by allowing state loss
dismissAllowingStateLoss();
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (unbinder != null) {
unbinder.unbind();
}
}
}
|
/**
* Generated with Acceleo
*/
package org.wso2.developerstudio.eclipse.gmf.esb.parts;
// Start of user code for imports
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.eef.runtime.ui.widgets.referencestable.ReferencesTableSettings;
import org.eclipse.jface.viewers.ViewerFilter;
// End of user code
/**
*
*
*/
public interface EventMediatorOutputConnectorPropertiesEditionPart {
/**
* Init the commentMediators
* @param current the current value
* @param containgFeature the feature where to navigate if necessary
* @param feature the feature to manage
*/
public void initCommentMediators(ReferencesTableSettings settings);
/**
* Update the commentMediators
* @param newValue the commentMediators to update
*
*/
public void updateCommentMediators();
/**
* Adds the given filter to the commentMediators edition editor.
*
* @param filter
* a viewer filter
* @see org.eclipse.jface.viewers.StructuredViewer#addFilter(ViewerFilter)
*
*/
public void addFilterToCommentMediators(ViewerFilter filter);
/**
* Adds the given filter to the commentMediators edition editor.
*
* @param filter
* a viewer filter
* @see org.eclipse.jface.viewers.StructuredViewer#addFilter(ViewerFilter)
*
*/
public void addBusinessFilterToCommentMediators(ViewerFilter filter);
/**
* @return true if the given element is contained inside the commentMediators table
*
*/
public boolean isContainedInCommentMediatorsTable(EObject element);
/**
* Returns the internationalized title text.
*
* @return the internationalized title text.
*
*/
public String getTitle();
// Start of user code for additional methods
// End of user code
}
|
/*
* Copyright 2017 Apereo
*
* 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.tle.core.usermanagement.standard.wrapper;
import com.tle.beans.ump.UserManagementSettings;
import com.tle.beans.usermanagement.standard.wrapper.AbstractSystemUserWrapperSettings;
import com.tle.common.Pair;
import com.tle.common.institution.CurrentInstitution;
import com.tle.common.usermanagement.user.ModifiableUserState;
import com.tle.common.usermanagement.user.SystemUserState;
import com.tle.common.usermanagement.user.valuebean.DefaultUserBean;
import com.tle.common.usermanagement.user.valuebean.GroupBean;
import com.tle.common.usermanagement.user.valuebean.RoleBean;
import com.tle.common.usermanagement.user.valuebean.UserBean;
import com.tle.exceptions.BadCredentialsException;
import com.tle.plugins.ump.AbstractUserDirectory;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
@SuppressWarnings("nls")
public abstract class AbstractSystemUserWrapper extends AbstractUserDirectory {
private String systemUsername;
private UserBean systemUserBean;
protected abstract boolean authenticatePassword(String suppliedPassword);
protected abstract String getEmailAddress();
@Override
protected boolean initialise(UserManagementSettings settings) {
this.systemUsername = ((AbstractSystemUserWrapperSettings) settings).getUsername();
this.systemUserBean =
new DefaultUserBean(
systemUsername, systemUsername, systemUsername, systemUsername, getEmailAddress());
return false;
}
@Override
public ModifiableUserState authenticateUser(String username, String password) {
if (!username.startsWith(systemUsername)) {
return null;
}
if (authenticatePassword(password)) {
return createAuthenticatedState(username);
}
throw newBadCredentialsException();
}
@Override
public ModifiableUserState authenticateUserFromUsername(String username, String privateData) {
if (!username.startsWith(systemUsername)) {
return null;
}
return createAuthenticatedState(username);
}
private ModifiableUserState createAuthenticatedState(String username) {
final int sysUserLen = systemUsername.length();
if (username.length() == sysUserLen) {
return new SystemUserState(CurrentInstitution.get(), systemUserBean);
} else if (username.charAt(sysUserLen) == '\\') {
// Impersonate username after supportUsername + '\'
return getChain().authenticateUserFromUsername(username.substring(sysUserLen + 1), null);
}
throw newBadCredentialsException();
}
private BadCredentialsException newBadCredentialsException() {
return new BadCredentialsException("Username or password incorrect");
}
@Override
public UserBean getInformationForUser(String userID) {
if (isSystemUser(userID)) {
return systemUserBean;
}
return null;
}
@Override
public Map<String, UserBean> getInformationForUsers(Collection<String> userIDs) {
for (String userID : userIDs) {
if (isSystemUser(userID)) {
return Collections.singletonMap(systemUsername, systemUserBean);
}
}
return null;
}
@Override
public Pair<ChainResult, Collection<GroupBean>> getGroupsContainingUser(String userID) {
return isSystemUser(userID)
? new Pair<ChainResult, Collection<GroupBean>>(ChainResult.STOP, null)
: null;
}
@Override
public Pair<ChainResult, Collection<RoleBean>> getRolesForUser(String userID) {
return isSystemUser(userID)
? new Pair<ChainResult, Collection<RoleBean>>(ChainResult.STOP, null)
: null;
}
private boolean isSystemUser(String userId) {
return Objects.equals(userId, systemUsername);
}
}
|
package com.alipay.api.domain;
import java.util.List;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;
/**
* 档口model
*
* @author auto create
* @since 1.0, 2018-12-21 17:36:41
*/
public class StallModel extends AlipayObject {
private static final long serialVersionUID = 3853779279592324158L;
/**
* 档口下菜品集合
*/
@ApiListField("dish_ids")
@ApiField("string")
private List<String> dishIds;
/**
* 档口id
*/
@ApiField("id")
private String id;
/**
* kds详情信息
*/
@ApiListField("kds_list")
@ApiField("stall_kds_entity")
private List<StallKdsEntity> kdsList;
/**
* 打印机id
*/
@ApiField("printer_id")
private String printerId;
/**
* 打印机名称
*/
@ApiField("printer_name")
private String printerName;
/**
* 是否分单打印(parted:菜品分开打印;together:菜品统一打印)
*/
@ApiField("receipt_type")
private String receiptType;
/**
* 门店id
*/
@ApiField("shop_id")
private String shopId;
/**
* 档口名称
*/
@ApiField("stall_name")
private String stallName;
/**
* 启用情况(false:停用;true:启用)
*/
@ApiField("use")
private Boolean use;
public List<String> getDishIds() {
return this.dishIds;
}
public void setDishIds(List<String> dishIds) {
this.dishIds = dishIds;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public List<StallKdsEntity> getKdsList() {
return this.kdsList;
}
public void setKdsList(List<StallKdsEntity> kdsList) {
this.kdsList = kdsList;
}
public String getPrinterId() {
return this.printerId;
}
public void setPrinterId(String printerId) {
this.printerId = printerId;
}
public String getPrinterName() {
return this.printerName;
}
public void setPrinterName(String printerName) {
this.printerName = printerName;
}
public String getReceiptType() {
return this.receiptType;
}
public void setReceiptType(String receiptType) {
this.receiptType = receiptType;
}
public String getShopId() {
return this.shopId;
}
public void setShopId(String shopId) {
this.shopId = shopId;
}
public String getStallName() {
return this.stallName;
}
public void setStallName(String stallName) {
this.stallName = stallName;
}
public Boolean getUse() {
return this.use;
}
public void setUse(Boolean use) {
this.use = use;
}
}
|
package io.quarkus.resteasy.mutiny.common.runtime;
import java.util.concurrent.ExecutorService;
import javax.ws.rs.client.RxInvokerProvider;
import javax.ws.rs.client.SyncInvoker;
import javax.ws.rs.client.WebTarget;
public class MultiInvokerProvider implements RxInvokerProvider<MultiRxInvoker> {
WebTarget target;
@Override
public boolean isProviderFor(Class<?> clazz) {
return MultiRxInvoker.class.equals(clazz);
}
@Override
public MultiRxInvoker getRxInvoker(SyncInvoker syncInvoker, ExecutorService executorService) {
return new MultiRxInvokerImpl(syncInvoker, executorService);
}
public WebTarget getTarget() {
return target;
}
public void setTarget(WebTarget target) {
this.target = target;
}
}
|
package jcf.sua.ux.flex.mvc.interceptor;
import jcf.sua.MessageHeaders;
import jcf.sua.dataset.DataSetReader;
import jcf.sua.mvc.MciDataSetAccessor;
import jcf.sua.mvc.MciRequestContextHolder;
import jcf.sua.ux.flex.FlexMessage;
import jcf.sua.ux.flex.FlexMessagePayload;
import jcf.sua.ux.flex.dataset.FlexAmfDataSetConverter;
import jcf.sua.ux.flex.dataset.FlexAmfDataSetReader;
import jcf.sua.ux.flex.mvc.FlexAmfArgumentResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.flex.core.MessageInterceptor;
import org.springframework.flex.core.MessageProcessingContext;
import flex.messaging.FlexContext;
import flex.messaging.messages.Message;
import flex.messaging.messages.RemotingMessage;
/**
*
* @author nolang
*
*/
public final class FlexAmfMessageBrokerInterceptor implements MessageInterceptor {
private static final Logger logger = LoggerFactory.getLogger(FlexAmfMessageBrokerInterceptor.class);
private FlexAmfDataSetConverter converter = new FlexAmfDataSetConverter();
private FlexAmfArgumentResolver argumentResolver;
public void setArgumentResolver(FlexAmfArgumentResolver argumentResolver) {
this.argumentResolver = argumentResolver;
}
public Message preProcess(MessageProcessingContext context,
Message inputMessage) {
if( logger.isDebugEnabled() ){
logger.debug("FlexAmfMessageBrokerInterceptor - preProcess");
}
MciRequestContextHolder.get().setMciRequest(checkMciRequest(inputMessage));
MciRequestContextHolder.get().setHttpServletRequest(FlexContext.getHttpRequest());
MciRequestContextHolder.get().setHttpServletResponse(FlexContext.getHttpResponse());
if(MciRequestContextHolder.get().isMciRequest()){
MciRequestContextHolder.get().setDataSetReader(getDataSetReader((RemotingMessage) inputMessage));
/*
* Arguments Resolving...
*/
argumentResolver.resolveArgument((RemotingMessage) inputMessage);
}
return inputMessage;
}
public Message postProcess(MessageProcessingContext context,
Message inputMessage, Message outputMessage) {
if( logger.isDebugEnabled() ){
logger.debug("FlexAmfMessageBrokerInterceptor - postProcess");
}
if(MciRequestContextHolder.get().isMciRequest()){
/*
* Builds output message
*/
outputMessage.setBody(buildFlexMessage(MciRequestContextHolder.get().getDataSetAccessor()));
}
MciRequestContextHolder.clear();
return outputMessage;
}
private FlexMessage<FlexMessagePayload> buildFlexMessage(MciDataSetAccessor dataSetAccessor) {
FlexMessage<FlexMessagePayload> flexMessage = new FlexMessage<FlexMessagePayload>();
FlexMessagePayload flexMessagePayload = new FlexMessagePayload();
flexMessagePayload.setDataSetMap(converter.toFlexAmfDataSet(dataSetAccessor.getDataSetMap()));
MessageHeaders headers = new MessageHeaders();
headers.setSuccesMessages(dataSetAccessor.getSuccessMessags());
flexMessage.setMessageHeaders(headers);
flexMessage.setPayload(flexMessagePayload);
return flexMessage;
}
/**
*
* @return
*/
private DataSetReader getDataSetReader(RemotingMessage message){
return new FlexAmfDataSetReader(message);
}
/**
*
* @param request
* @return
*/
private boolean checkMciRequest(Message message) {
return (message != null && message instanceof RemotingMessage);
}
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE89_SQL_Injection__connect_tcp_executeUpdate_03.java
Label Definition File: CWE89_SQL_Injection.label.xml
Template File: sources-sinks-03.tmpl.java
*/
/*
* @description
* CWE: 89 SQL Injection
* BadSource: connect_tcp Read data using an outbound tcp connection
* GoodSource: A hardcoded string
* Sinks: executeUpdate
* GoodSink: Use prepared statement and executeUpdate (properly)
* BadSink : data concatenated into SQL statement used in executeUpdate(), which could result in SQL Injection
* Flow Variant: 03 Control flow: if(5==5) and if(5!=5)
*
* */
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.Socket;
import java.util.logging.Level;
import java.sql.*;
public class CWE89_SQL_Injection__connect_tcp_executeUpdate_03 extends AbstractTestCase
{
public void bad() throws Throwable
{
String data;
if (5==5)
{
data = ""; /* Initialize data */
/* Read data using an outbound tcp connection */
{
Socket socket = null;
BufferedReader readerBuffered = null;
InputStreamReader readerInputStream = null;
try
{
/* Read data using an outbound tcp connection */
socket = new Socket("host.example.org", 39544);
/* read input from socket */
readerInputStream = new InputStreamReader(socket.getInputStream(), "UTF-8");
readerBuffered = new BufferedReader(readerInputStream);
/* POTENTIAL FLAW: Read data using an outbound tcp connection */
data = readerBuffered.readLine();
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
}
finally
{
/* clean up stream reading objects */
try
{
if (readerBuffered != null)
{
readerBuffered.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
}
try
{
if (readerInputStream != null)
{
readerInputStream.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
}
/* clean up socket objects */
try
{
if (socket != null)
{
socket.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing Socket", 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 = null;
}
if (5==5)
{
Connection dbConnection = null;
Statement sqlStatement = null;
try
{
dbConnection = IO.getDBConnection();
sqlStatement = dbConnection.createStatement();
/* POTENTIAL FLAW: data concatenated into SQL statement used in executeUpdate(), which could result in SQL Injection */
int rowCount = sqlStatement.executeUpdate("insert into users (status) values ('updated') where name='"+data+"'");
IO.writeLine("Updated " + rowCount + " rows successfully.");
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
}
finally
{
try
{
if (sqlStatement != null)
{
sqlStatement.close();
}
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql);
}
try
{
if (dbConnection != null)
{
dbConnection.close();
}
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
}
}
}
}
/* goodG2B1() - use goodsource and badsink by changing first 5==5 to 5!=5 */
private void goodG2B1() throws Throwable
{
String data;
if (5!=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 = null;
}
else
{
/* FIX: Use a hardcoded string */
data = "foo";
}
if (5==5)
{
Connection dbConnection = null;
Statement sqlStatement = null;
try
{
dbConnection = IO.getDBConnection();
sqlStatement = dbConnection.createStatement();
/* POTENTIAL FLAW: data concatenated into SQL statement used in executeUpdate(), which could result in SQL Injection */
int rowCount = sqlStatement.executeUpdate("insert into users (status) values ('updated') where name='"+data+"'");
IO.writeLine("Updated " + rowCount + " rows successfully.");
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
}
finally
{
try
{
if (sqlStatement != null)
{
sqlStatement.close();
}
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql);
}
try
{
if (dbConnection != null)
{
dbConnection.close();
}
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
}
}
}
}
/* goodG2B2() - use goodsource and badsink by reversing statements in first if */
private void goodG2B2() throws Throwable
{
String data;
if (5==5)
{
/* FIX: Use a hardcoded string */
data = "foo";
}
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 = null;
}
if (5==5)
{
Connection dbConnection = null;
Statement sqlStatement = null;
try
{
dbConnection = IO.getDBConnection();
sqlStatement = dbConnection.createStatement();
/* POTENTIAL FLAW: data concatenated into SQL statement used in executeUpdate(), which could result in SQL Injection */
int rowCount = sqlStatement.executeUpdate("insert into users (status) values ('updated') where name='"+data+"'");
IO.writeLine("Updated " + rowCount + " rows successfully.");
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
}
finally
{
try
{
if (sqlStatement != null)
{
sqlStatement.close();
}
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error closing Statement", exceptSql);
}
try
{
if (dbConnection != null)
{
dbConnection.close();
}
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
}
}
}
}
/* goodB2G1() - use badsource and goodsink by changing second 5==5 to 5!=5 */
private void goodB2G1() throws Throwable
{
String data;
if (5==5)
{
data = ""; /* Initialize data */
/* Read data using an outbound tcp connection */
{
Socket socket = null;
BufferedReader readerBuffered = null;
InputStreamReader readerInputStream = null;
try
{
/* Read data using an outbound tcp connection */
socket = new Socket("host.example.org", 39544);
/* read input from socket */
readerInputStream = new InputStreamReader(socket.getInputStream(), "UTF-8");
readerBuffered = new BufferedReader(readerInputStream);
/* POTENTIAL FLAW: Read data using an outbound tcp connection */
data = readerBuffered.readLine();
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
}
finally
{
/* clean up stream reading objects */
try
{
if (readerBuffered != null)
{
readerBuffered.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
}
try
{
if (readerInputStream != null)
{
readerInputStream.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
}
/* clean up socket objects */
try
{
if (socket != null)
{
socket.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing Socket", 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 = null;
}
if (5!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
IO.writeLine("Benign, fixed string");
}
else
{
Connection dbConnection = null;
PreparedStatement sqlStatement = null;
try
{
/* FIX: Use prepared statement and executeUpdate (properly) */
dbConnection = IO.getDBConnection();
sqlStatement = dbConnection.prepareStatement("insert into users (status) values ('updated') where name=?");
sqlStatement.setString(1, data);
int rowCount = sqlStatement.executeUpdate();
IO.writeLine("Updated " + rowCount + " rows successfully.");
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
}
finally
{
try
{
if (sqlStatement != null)
{
sqlStatement.close();
}
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
}
try
{
if (dbConnection != null)
{
dbConnection.close();
}
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
}
}
}
}
/* goodB2G2() - use badsource and goodsink by reversing statements in second if */
private void goodB2G2() throws Throwable
{
String data;
if (5==5)
{
data = ""; /* Initialize data */
/* Read data using an outbound tcp connection */
{
Socket socket = null;
BufferedReader readerBuffered = null;
InputStreamReader readerInputStream = null;
try
{
/* Read data using an outbound tcp connection */
socket = new Socket("host.example.org", 39544);
/* read input from socket */
readerInputStream = new InputStreamReader(socket.getInputStream(), "UTF-8");
readerBuffered = new BufferedReader(readerInputStream);
/* POTENTIAL FLAW: Read data using an outbound tcp connection */
data = readerBuffered.readLine();
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
}
finally
{
/* clean up stream reading objects */
try
{
if (readerBuffered != null)
{
readerBuffered.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
}
try
{
if (readerInputStream != null)
{
readerInputStream.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
}
/* clean up socket objects */
try
{
if (socket != null)
{
socket.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing Socket", 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 = null;
}
if (5==5)
{
Connection dbConnection = null;
PreparedStatement sqlStatement = null;
try
{
/* FIX: Use prepared statement and executeUpdate (properly) */
dbConnection = IO.getDBConnection();
sqlStatement = dbConnection.prepareStatement("insert into users (status) values ('updated') where name=?");
sqlStatement.setString(1, data);
int rowCount = sqlStatement.executeUpdate();
IO.writeLine("Updated " + rowCount + " rows successfully.");
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error getting database connection", exceptSql);
}
finally
{
try
{
if (sqlStatement != null)
{
sqlStatement.close();
}
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error closing PreparedStatement", exceptSql);
}
try
{
if (dbConnection != null)
{
dbConnection.close();
}
}
catch (SQLException exceptSql)
{
IO.logger.log(Level.WARNING, "Error closing Connection", exceptSql);
}
}
}
}
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);
}
}
|
/**
* 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.hedwig.server.persistence;
import com.google.protobuf.ByteString;
import org.apache.hedwig.protocol.PubSubProtocol.Message;
/**
* Encapsulates a request for reading a single message. The message on the given
* topic <b>at</b> the given seqId is scanned. A call-back {@link ScanCallback}
* is provided. When the message is scanned, the
* {@link ScanCallback#messageScanned(Object, Message)} method is called. Since
* there is only 1 record to be scanned the
* {@link ScanCallback#operationFinished(Object)} method may not be called since
* its redundant.
* {@link ScanCallback#scanFailed(Object, org.apache.hedwig.exceptions.PubSubException)}
* method is called in case of error.
*
*/
public class ScanRequest {
ByteString topic;
long startSeqId;
ScanCallback callback;
Object ctx;
public ScanRequest(ByteString topic, long startSeqId, ScanCallback callback, Object ctx) {
this.topic = topic;
this.startSeqId = startSeqId;
this.callback = callback;
this.ctx = ctx;
}
public ByteString getTopic() {
return topic;
}
public long getStartSeqId() {
return startSeqId;
}
public ScanCallback getCallback() {
return callback;
}
public Object getCtx() {
return ctx;
}
}
|
/*
* Copyright (c) 2017 xamoom GmbH <apps@xamoom.com>
*
* Licensed under the MIT License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at the root of this project.
*/
package com.xamoom.android.xamoomcontentblocks.Adapters;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.collection.LruCache;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.xamoom.android.xamoomcontentblocks.ListManager;
import com.xamoom.android.xamoomcontentblocks.ViewHolders.ContentBlock15ViewHolder;
import com.xamoom.android.xamoomcontentblocks.ViewHolders.ContentBlock3ViewHolder;
import com.xamoom.android.xamoomcontentblocks.XamoomContentFragment;
import com.xamoom.android.xamoomsdk.EnduserApi;
import com.xamoom.android.xamoomsdk.R;
import com.xamoom.android.xamoomsdk.Resource.Content;
import com.xamoom.android.xamoomsdk.Resource.ContentBlock;
import com.xamoom.android.xamoomsdk.Resource.Style;
import java.util.ArrayList;
import java.util.List;
public class ContentBlock3Adapter implements AdapterDelegate<List<ContentBlock>> {
private static final int BLOCK_TYPE = 3;
@Override
public boolean isForViewType(@NonNull List<ContentBlock> items, int position) {
ContentBlock cb = items.get(position);
return cb.getBlockType() == BLOCK_TYPE;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(
ViewGroup parent, Fragment fragment, EnduserApi enduserApi, String youtubeApiKey,
LruCache bitmapCache, LruCache contentCache, boolean showContentLinks, ListManager listManager, AdapterDelegatesManager adapterDelegatesManager,
ContentBlock3ViewHolder.OnContentBlock3ViewHolderInteractionListener onContentBlock3ViewHolderInteractionListener,
ContentBlock15ViewHolder.OnContentBlock15ViewHolderInteractionListener
onContentBlock15ViewHolderInteractionListener,
XamoomContentFragment.OnXamoomContentFragmentInteractionListener onXamoomContentFragmentInteractionListener, @Nullable ArrayList<String> urls, @Nullable String mapboxStyleString,
@Nullable String navigationButtonTintColorString, @Nullable String contentButtonTextColorString, @Nullable String navigationMode, Content content) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.content_block_3_layout, parent, false);
return new ContentBlock3ViewHolder(view, fragment.getContext(), onContentBlock3ViewHolderInteractionListener, urls, fragment, onXamoomContentFragmentInteractionListener);
}
@Override
public void onBindViewHolder(@NonNull List<ContentBlock> items, int position,
@NonNull RecyclerView.ViewHolder holder, Style style, boolean offline) {
ContentBlock cb = items.get(position);
ContentBlock3ViewHolder newHolder = (ContentBlock3ViewHolder) holder;
newHolder.setStyle(style);
newHolder.setupContentBlock(cb, offline);
}
}
|
/**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.internal;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.webkit.WebView;
import com.facebook.FacebookException;
import com.facebook.widget.FacebookDialog;
import com.facebook.widget.WebDialog;
import org.json.JSONException;
import org.json.JSONObject;
/**
* com.facebook.internal is solely for the use of other packages within the Facebook SDK for Android. Use of
* any of the classes in this package is unsupported, and they may be modified or removed without warning at
* any time.
*
* This dialog is used as a fallback when a native FacebookDialog could not be displayed. The primary reason for
* this separation is to keep this approach for internal use only until we stabilize the API.
*/
public class FacebookWebFallbackDialog extends WebDialog {
private static final String TAG = FacebookWebFallbackDialog.class.getName();
private static final int OS_BACK_BUTTON_RESPONSE_TIMEOUT_MILLISECONDS = 1500;
private boolean waitingForDialogToClose;
public static boolean presentWebFallback(final Context context,
String dialogUrl,
String applicationId,
final FacebookDialog.PendingCall appCall,
final FacebookDialog.Callback callback) {
if (Utility.isNullOrEmpty(dialogUrl)) {
return false;
}
String redirectUrl = String.format("fb%s://bridge/", applicationId);
// Show the webdialog.
FacebookWebFallbackDialog fallbackWebDialog = new FacebookWebFallbackDialog(
context, dialogUrl, redirectUrl);
fallbackWebDialog.setOnCompleteListener(new WebDialog.OnCompleteListener() {
@Override
public void onComplete(Bundle values, FacebookException error) {
Intent dummyIntent = new Intent();
dummyIntent.putExtras(values == null ? new Bundle() : values);
FacebookDialog.handleActivityResult(
context,
appCall,
appCall.getRequestCode(),
dummyIntent,
callback);
}
});
fallbackWebDialog.show();
return true;
}
private FacebookWebFallbackDialog(Context context, String url, String expectedRedirectUrl) {
super(context, url);
setExpectedRedirectUrl(expectedRedirectUrl);
}
@Override
protected Bundle parseResponseUri(String url) {
Uri responseUri = Uri.parse(url);
Bundle queryParams = Utility.parseUrlQueryString(responseUri.getQuery());
// Convert Bridge args to the format that the Native dialog code understands.
String bridgeArgsJSONString = queryParams.getString(ServerProtocol.FALLBACK_DIALOG_PARAM_BRIDGE_ARGS);
queryParams.remove(ServerProtocol.FALLBACK_DIALOG_PARAM_BRIDGE_ARGS);
if (!Utility.isNullOrEmpty(bridgeArgsJSONString)) {
Bundle bridgeArgs;
try {
JSONObject bridgeArgsJSON = new JSONObject(bridgeArgsJSONString);
bridgeArgs = BundleJSONConverter.convertToBundle(bridgeArgsJSON);
queryParams.putBundle(NativeProtocol.EXTRA_PROTOCOL_BRIDGE_ARGS, bridgeArgs);
} catch (JSONException je) {
Utility.logd(TAG, "Unable to parse bridge_args JSON", je);
}
}
// Convert Method results to the format that the Native dialog code understands.
String methodResultsJSONString = queryParams.getString(ServerProtocol.FALLBACK_DIALOG_PARAM_METHOD_RESULTS);
queryParams.remove(ServerProtocol.FALLBACK_DIALOG_PARAM_METHOD_RESULTS);
if (!Utility.isNullOrEmpty(methodResultsJSONString)) {
methodResultsJSONString = Utility.isNullOrEmpty(methodResultsJSONString) ? "{}" : methodResultsJSONString;
Bundle methodResults;
try {
JSONObject methodArgsJSON = new JSONObject(methodResultsJSONString);
methodResults = BundleJSONConverter.convertToBundle(methodArgsJSON);
queryParams.putBundle(NativeProtocol.EXTRA_PROTOCOL_METHOD_RESULTS, methodResults);
} catch (JSONException je) {
Utility.logd(TAG, "Unable to parse bridge_args JSON", je);
}
}
// The web host does not send a numeric version back. Put the latest known version in there so NativeProtocol
// can continue parsing the response.
queryParams.remove(ServerProtocol.FALLBACK_DIALOG_PARAM_VERSION);
queryParams.putInt(NativeProtocol.EXTRA_PROTOCOL_VERSION, NativeProtocol.getLatestKnownVersion());
return queryParams;
}
@Override
public void dismiss() {
WebView webView = getWebView();
if (isListenerCalled() || webView == null || !webView.isShown()) {
// If the listener has been called, or if the WebView isn't visible, we cannot give the dialog a chance
// to respond. So defer to the parent implementation.
super.dismiss();
return;
}
// If we have already notified the dialog to close, then ignore this request to dismiss. The timer will
// honor the request.
if (waitingForDialogToClose) {
return;
}
waitingForDialogToClose = true;
// Now fire off the event that will tell the dialog to wind down.
String eventJS =
"(function() {" +
" var event = document.createEvent('Event');" +
" event.initEvent('fbPlatformDialogMustClose',true,true);" +
" document.dispatchEvent(event);" +
"})();";
webView.loadUrl("javascript:" + eventJS);
// Set up a timeout for the dialog to respond. If the timer expires, we need to honor the user's desire to
// dismiss the dialog.
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(
new Runnable() {
@Override
public void run() {
if (!isListenerCalled()) {
// If we get here, then the dialog did not close quickly enough. So we need to honor the user's
// wish to cancel.
sendCancelToListener();
}
}
},
OS_BACK_BUTTON_RESPONSE_TIMEOUT_MILLISECONDS);
}
}
|
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8011738
* @author sogoel
* @summary Code translation test for Lambda expressions, method references
* @run main ByteCodeTest
*/
import com.sun.tools.classfile.Attribute;
import com.sun.tools.classfile.BootstrapMethods_attribute;
import com.sun.tools.classfile.ClassFile;
import com.sun.tools.classfile.ConstantPool;
import com.sun.tools.classfile.ConstantPoolException;
import com.sun.tools.classfile.ConstantPool.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class ByteCodeTest {
static boolean IS_DEBUG = false;
public static void main(String[] args) {
File classFile = null;
int err = 0;
boolean verifyResult = false;
for(TestCases tc : TestCases.values()) {
classFile = getCompiledFile(tc.name(), tc.srcCode);
if(classFile == null) { // either testFile or classFile was not created
err++;
} else {
verifyResult = verifyClassFileAttributes(classFile, tc);
if(!verifyResult)
System.out.println("Bootstrap class file attributes did not match for " + tc.name());
}
}
if(err > 0)
throw new RuntimeException("Found " + err + " found");
else
System.out.println("Test passed");
}
private static boolean verifyClassFileAttributes(File classFile, TestCases tc) {
ClassFile c = null;
try {
c = ClassFile.read(classFile);
} catch (IOException | ConstantPoolException e) {
e.printStackTrace();
}
ConstantPoolVisitor cpv = new ConstantPoolVisitor(c, c.constant_pool.size());
Map<Integer, String> hm = cpv.getBSMMap();
List<String> expectedValList = tc.getExpectedArgValues();
expectedValList.add(tc.bsmSpecifier.specifier);
if(!(hm.values().containsAll(new HashSet<String>(expectedValList)))) {
System.out.println("Values do not match");
return false;
}
return true;
}
private static File getCompiledFile(String fname, String srcString) {
File testFile = null, classFile = null;
boolean isTestFileCreated = true;
try {
testFile = writeTestFile(fname+".java", srcString);
} catch(IOException ioe) {
isTestFileCreated = false;
System.err.println("fail to write" + ioe);
}
if(isTestFileCreated) {
try {
classFile = compile(testFile);
} catch (Error err) {
System.err.println("fail compile. Source:\n" + srcString);
throw err;
}
}
return classFile;
}
static File writeTestFile(String fname, String source) throws IOException {
File f = new File(fname);
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(f)));
out.println(source);
out.close();
return f;
}
static File compile(File f) {
int rc = com.sun.tools.javac.Main.compile(new String[] {
"-source", "1.8", "-g", f.getPath() });
if (rc != 0)
throw new Error("compilation failed. rc=" + rc);
String path = f.getPath();
return new File(path.substring(0, path.length() - 5) + ".class");
}
static void debugln(String str) {
if(IS_DEBUG)
System.out.println(str);
}
enum BSMSpecifier {
SPECIFIER1("REF_invokeStatic java/lang/invoke/LambdaMetafactory metaFactory " +
"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;" +
"Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)" +
"Ljava/lang/invoke/CallSite;"),
SPECIFIER2("REF_invokeStatic java/lang/invoke/LambdaMetafactory altMetaFactory " +
"(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;" +
"[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;");
String specifier;
private BSMSpecifier(String specifier) {
this.specifier = specifier;
}
}
enum TestCases {
// Single line lambda expression
TC1("class TC1 {\n" +
" public static void main(String[] args) {\n" +
" Object o = (Runnable) () -> { System.out.println(\"hi\");};\n" +
" }\n"+
"}", BSMSpecifier.SPECIFIER1) {
@Override
List<String> getExpectedArgValues() {
List<String> valList = new ArrayList<>();
valList.add("REF_invokeInterface java/lang/Runnable run ()V");
valList.add("REF_invokeStatic TC1 lambda$0 ()V");
valList.add("()V");
return valList;
}
},
// Lambda expression in a for loop
TC2("import java.util.*;\n" +
"public class TC2 {\n" +
" void TC2_test() {\n" +
" List<String> list = new ArrayList<>();\n" +
" list.add(\"A\");\n" +
" list.add(\"B\");\n" +
" list.stream().forEach( s -> { System.out.println(s); } );\n" +
" }\n" +
" public static void main(String[] args) {\n" +
" new TC2().TC2_test();\n" +
" }\n" +
"}", BSMSpecifier.SPECIFIER1) {
@Override
List<String> getExpectedArgValues() {
List<String> valList = new ArrayList<>();
valList.add("REF_invokeInterface java/util/function/Consumer accept (Ljava/lang/Object;)V");
valList.add("REF_invokeStatic TC2 lambda$0 (Ljava/lang/String;)V");
valList.add("(Ljava/lang/String;)V");
return valList;
}
},
// Lambda initializer
TC3("class TC3 {\n" +
" interface SAM {\n" +
" void m(int i);\n" +
" }\n" +
" SAM lambda_03 = (int pos) -> { };\n" +
"}", BSMSpecifier.SPECIFIER1) {
@Override
List<String> getExpectedArgValues() {
List<String> valList = new ArrayList<>();
valList.add("REF_invokeInterface TC3$SAM m (I)V");
valList.add("REF_invokeStatic TC3 lambda$0 (I)V");
valList.add("(I)V");
return valList;
}
},
// Array initializer
TC4("class TC4 {\n" +
" interface Block<T> {\n" +
" void m(T t);\n" +
" }\n" +
" void test1() {\n" +
" Block<?>[] arr1 = { t -> { }, t -> { } };\n" +
" }\n" +
"}", BSMSpecifier.SPECIFIER1) {
@Override
List<String> getExpectedArgValues() {
List<String> valList = new ArrayList<>();
valList.add("REF_invokeInterface TC4$Block m (Ljava/lang/Object;)V");
valList.add("REF_invokeStatic TC4 lambda$0 (Ljava/lang/Object;)V");
valList.add("(Ljava/lang/Object;)V");
valList.add("REF_invokeStatic TC4 lambda$1 (Ljava/lang/Object;)V");
return valList;
}
},
//Lambda expression as a method arg
TC5("class TC5 {\n"+
" interface MapFun<T,R> { R m( T n); }\n" +
" void meth( MapFun<String,Integer> mf ) {\n" +
" assert( mf.m(\"four\") == 4);\n" +
" }\n"+
" void test(Integer i) {\n" +
" meth(s -> { Integer len = s.length(); return len; } );\n" +
" }\n"+
"}", BSMSpecifier.SPECIFIER1) {
@Override
List<String> getExpectedArgValues() {
List<String> valList = new ArrayList<>();
valList.add("REF_invokeInterface TC5$MapFun m (Ljava/lang/Object;)Ljava/lang/Object;");
valList.add("REF_invokeStatic TC5 lambda$0 (Ljava/lang/String;)Ljava/lang/Integer;");
valList.add("(Ljava/lang/String;)Ljava/lang/Integer;");
return valList;
}
},
//Inner class of Lambda expression
TC6("class TC6 {\n" +
" interface MapFun<T, R> { R m( T n); }\n" +
" MapFun<Class<?>,String> cs;\n" +
" void test() {\n" +
" cs = c -> {\n" +
" class innerClass {\n" +
" Class<?> icc;\n" +
" innerClass(Class<?> _c) { icc = _c; }\n" +
" String getString() { return icc.toString(); }\n" +
" }\n" +
" return new innerClass(c).getString();\n"+
" };\n" +
" }\n" +
"}\n", BSMSpecifier.SPECIFIER1) {
@Override
List<String> getExpectedArgValues() {
List<String> valList = new ArrayList<>();
valList.add("REF_invokeInterface TC6$MapFun m (Ljava/lang/Object;)Ljava/lang/Object;");
valList.add("REF_invokeSpecial TC6 lambda$0 (Ljava/lang/Class;)Ljava/lang/String;");
valList.add("(Ljava/lang/Class;)Ljava/lang/String;");
return valList;
}
},
// Method reference
TC7("class TC7 {\n" +
" static interface SAM {\n" +
" void m(Integer i);\n" +
" }\n" +
" void m(Integer i) {}\n" +
" SAM s = this::m;\n" +
"}\n", BSMSpecifier.SPECIFIER1) {
@Override
List<String> getExpectedArgValues() {
List<String> valList = new ArrayList<>();
valList.add("REF_invokeInterface TC7$SAM m (Ljava/lang/Integer;)V");
valList.add("REF_invokeVirtual TC7 m (Ljava/lang/Integer;)V");
valList.add("(Ljava/lang/Integer;)V");
return valList;
}
},
// Constructor reference
TC8("public class TC8 {\n" +
" static interface A {Fee<String> m();}\n" +
" static class Fee<T> {\n" +
" private T t;\n" +
" public Fee() {}\n" +
" }\n" +
" public static void main(String[] args) {\n" +
" A a = Fee<String>::new; \n" +
" }\n" +
"}\n", BSMSpecifier.SPECIFIER1) {
@Override
List<String> getExpectedArgValues() {
List<String> valList = new ArrayList<>();
valList.add("REF_invokeInterface TC8$A m ()LTC8$Fee;");
valList.add("REF_newInvokeSpecial TC8$Fee <init> ()V");
valList.add("()LTC8$Fee;");
return valList;
}
},
// Recursive lambda expression
TC9("class TC9 {\n" +
" interface Recursive<T, R> { T apply(R n); };\n" +
" Recursive<Integer,Integer> factorial;\n" +
" void test(Integer j) {\n" +
" factorial = i -> { return i == 0 ? 1 : i * factorial.apply( i - 1 ); };\n" +
" }\n" +
"}\n", BSMSpecifier.SPECIFIER1) {
@Override
List<String> getExpectedArgValues() {
List<String> valList = new ArrayList<>();
valList.add("REF_invokeInterface TC9$Recursive apply (Ljava/lang/Object;)Ljava/lang/Object;");
valList.add("REF_invokeSpecial TC9 lambda$0 (Ljava/lang/Integer;)Ljava/lang/Integer;");
valList.add("(Ljava/lang/Integer;)Ljava/lang/Integer;");
return valList;
}
},
//Serializable Lambda
TC10("import java.io.Serializable;\n" +
"class TC10 {\n" +
" interface Foo { int m(); }\n" +
" public static void main(String[] args) {\n" +
" Foo f1 = (Foo & Serializable)() -> 3;\n" +
" }\n" +
"}\n", BSMSpecifier.SPECIFIER2) {
@Override
List<String> getExpectedArgValues() {
List<String> valList = new ArrayList<>();
valList.add("REF_invokeStatic java/lang/invoke/LambdaMetafactory altMetaFactory (Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;");
valList.add("REF_invokeInterface TC10$Foo m ()I");
valList.add("REF_invokeStatic TC10 lambda$main$3231c38a$0 ()I");
valList.add("()I");
valList.add("1");
return valList;
}
};
String srcCode;
BSMSpecifier bsmSpecifier;
TestCases(String src, BSMSpecifier bsmSpecifier) {
this.srcCode = src;
// By default, all test cases will have bootstrap method specifier as Lambda.MetaFactory
// For serializable lambda test cases, bootstrap method specifier changed to altMetaFactory
this.bsmSpecifier = bsmSpecifier;
}
List<String> getExpectedArgValues() {
return null;
}
void setSrcCode(String src) {
srcCode = src;
}
}
static class ConstantPoolVisitor implements ConstantPool.Visitor<String, Integer> {
final List<String> slist;
final ClassFile cf;
final ConstantPool cfpool;
final Map<Integer, String> bsmMap;
public ConstantPoolVisitor(ClassFile cf, int size) {
slist = new ArrayList<>(size);
for (int i = 0 ; i < size; i++) {
slist.add(null);
}
this.cf = cf;
this.cfpool = cf.constant_pool;
bsmMap = readBSM();
}
public Map<Integer, String> getBSMMap() {
return Collections.unmodifiableMap(bsmMap);
}
public String visit(CPInfo c, int index) {
return c.accept(this, index);
}
private Map<Integer, String> readBSM() {
BootstrapMethods_attribute bsmAttr =
(BootstrapMethods_attribute) cf.getAttribute(Attribute.BootstrapMethods);
if (bsmAttr != null) {
Map<Integer, String> out =
new HashMap<>(bsmAttr.bootstrap_method_specifiers.length);
for (BootstrapMethods_attribute.BootstrapMethodSpecifier bsms :
bsmAttr.bootstrap_method_specifiers) {
int index = bsms.bootstrap_method_ref;
try {
String value = slist.get(index);
if (value == null) {
value = visit(cfpool.get(index), index);
debugln("[SG]: index " + index);
debugln("[SG]: value " + value);
slist.set(index, value);
out.put(index, value);
}
for (int idx : bsms.bootstrap_arguments) {
value = slist.get(idx);
if (value == null) {
value = visit(cfpool.get(idx), idx);
debugln("[SG]: idx " + idx);
debugln("[SG]: value " + value);
slist.set(idx, value);
out.put(idx, value);
}
}
} catch (InvalidIndex ex) {
ex.printStackTrace();
}
}
return out;
}
return new HashMap<>(0);
}
@Override
public String visitClass(CONSTANT_Class_info c, Integer p) {
String value = slist.get(p);
if (value == null) {
try {
value = visit(cfpool.get(c.name_index), c.name_index);
slist.set(p, value);
} catch (ConstantPoolException ex) {
ex.printStackTrace();
}
}
return value;
}
@Override
public String visitDouble(CONSTANT_Double_info c, Integer p) {
String value = slist.get(p);
if (value == null) {
value = Double.toString(c.value);
slist.set(p, value);
}
return value;
}
@Override
public String visitFieldref(CONSTANT_Fieldref_info c, Integer p) {
String value = slist.get(p);
if (value == null) {
try {
value = visit(cfpool.get(c.class_index), c.class_index);
value = value.concat(" " + visit(cfpool.get(c.name_and_type_index),
c.name_and_type_index));
slist.set(p, value);
} catch (ConstantPoolException ex) {
ex.printStackTrace();
}
}
return value;
}
@Override
public String visitFloat(CONSTANT_Float_info c, Integer p) {
String value = slist.get(p);
if (value == null) {
value = Float.toString(c.value);
slist.set(p, value);
}
return value;
}
@Override
public String visitInteger(CONSTANT_Integer_info cnstnt, Integer p) {
String value = slist.get(p);
if (value == null) {
value = Integer.toString(cnstnt.value);
slist.set(p, value);
}
return value;
}
@Override
public String visitInterfaceMethodref(CONSTANT_InterfaceMethodref_info c,
Integer p) {
String value = slist.get(p);
if (value == null) {
try {
value = visit(cfpool.get(c.class_index), c.class_index);
value = value.concat(" " +
visit(cfpool.get(c.name_and_type_index),
c.name_and_type_index));
slist.set(p, value);
} catch (ConstantPoolException ex) {
ex.printStackTrace();
}
}
return value;
}
@Override
public String visitInvokeDynamic(CONSTANT_InvokeDynamic_info c, Integer p) {
String value = slist.get(p);
if (value == null) {
try {
value = bsmMap.get(c.bootstrap_method_attr_index) + " "
+ visit(cfpool.get(c.name_and_type_index), c.name_and_type_index);
slist.set(p, value);
} catch (ConstantPoolException ex) {
ex.printStackTrace();
}
}
return value;
}
@Override
public String visitLong(CONSTANT_Long_info c, Integer p) {
String value = slist.get(p);
if (value == null) {
value = Long.toString(c.value);
slist.set(p, value);
}
return value;
}
@Override
public String visitNameAndType(CONSTANT_NameAndType_info c, Integer p) {
String value = slist.get(p);
if (value == null) {
try {
value = visit(cfpool.get(c.name_index), c.name_index);
value = value.concat(" " +
visit(cfpool.get(c.type_index), c.type_index));
slist.set(p, value);
} catch (InvalidIndex ex) {
ex.printStackTrace();
}
}
return value;
}
@Override
public String visitMethodref(CONSTANT_Methodref_info c, Integer p) {
String value = slist.get(p);
if (value == null) {
try {
value = visit(cfpool.get(c.class_index), c.class_index);
value = value.concat(" " +
visit(cfpool.get(c.name_and_type_index),
c.name_and_type_index));
slist.set(p, value);
} catch (ConstantPoolException ex) {
ex.printStackTrace();
}
}
return value;
}
@Override
public String visitMethodHandle(CONSTANT_MethodHandle_info c, Integer p) {
String value = slist.get(p);
if (value == null) {
try {
value = c.reference_kind.name();
value = value.concat(" "
+ visit(cfpool.get(c.reference_index), c.reference_index));
slist.set(p, value);
} catch (ConstantPoolException ex) {
ex.printStackTrace();
}
}
return value;
}
@Override
public String visitMethodType(CONSTANT_MethodType_info c, Integer p) {
String value = slist.get(p);
if (value == null) {
try {
value = visit(cfpool.get(c.descriptor_index), c.descriptor_index);
slist.set(p, value);
} catch (ConstantPoolException ex) {
ex.printStackTrace();
}
}
return value;
}
@Override
public String visitString(CONSTANT_String_info c, Integer p) {
try {
String value = slist.get(p);
if (value == null) {
value = c.getString();
slist.set(p, value);
}
return value;
} catch (ConstantPoolException ex) {
throw new RuntimeException("Fatal error", ex);
}
}
@Override
public String visitUtf8(CONSTANT_Utf8_info cnstnt, Integer p) {
String value = slist.get(p);
if (value == null) {
value = cnstnt.value;
slist.set(p, value);
}
return value;
}
}
}
|
/*
*
* Copyright IBM Corp. 2018
*
* 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 j2serulesession;
import static j2serulesession.MessageCode.ODM_CONSOLE_INFORMATION_ERROR_JSON_MAPPING;
import static j2serulesession.MessageCode.ODM_CONSOLE_INFORMATION_ERROR_JSON_SYNTAX;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
class JSONFileContentException extends Exception {
private static final long serialVersionUID = 1L;
JSONFileContentException(String message, IOException exception) {
super(message, exception);
}
}
class InvalidJSONSyntax extends JSONFileContentException {
private static final long serialVersionUID = 1L;
InvalidJSONSyntax(String resourceName, JsonParseException exception) {
super(new MessageFormatter().getMessage(ODM_CONSOLE_INFORMATION_ERROR_JSON_SYNTAX, resourceName,
exception.getMessage()), exception);
}
}
class InvalidJSONContent extends JSONFileContentException {
private static final long serialVersionUID = 1L;
InvalidJSONContent(String resourceName, JsonMappingException exception) {
super(new MessageFormatter().getMessage(ODM_CONSOLE_INFORMATION_ERROR_JSON_MAPPING, resourceName,
exception.getMessage()), exception);
}
}
|
/**
* Copyright 2016 Nikita Koksharov
*
* 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.redisson.connection;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.redisson.api.NodeType;
import org.redisson.api.RFuture;
import org.redisson.client.RedisClient;
import org.redisson.client.RedisConnection;
import org.redisson.client.RedisConnectionException;
import org.redisson.client.RedisException;
import org.redisson.client.protocol.RedisCommands;
import org.redisson.config.BaseMasterSlaveServersConfig;
import org.redisson.config.Config;
import org.redisson.config.MasterSlaveServersConfig;
import org.redisson.config.ReplicatedServersConfig;
import org.redisson.misc.RPromise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;
import io.netty.util.concurrent.GlobalEventExecutor;
import io.netty.util.concurrent.ScheduledFuture;
/**
* {@link ConnectionManager} for AWS ElastiCache Replication Groups or Azure Redis Cache. By providing all nodes
* of the replication group to this manager, the role of each node can be polled to determine
* if a failover has occurred resulting in a new master.
*
* @author Nikita Koksharov
* @author Steve Ungerer
*/
public class ReplicatedConnectionManager extends MasterSlaveConnectionManager {
private static final String ROLE_KEY = "role";
private final Logger log = LoggerFactory.getLogger(getClass());
private AtomicReference<URI> currentMaster = new AtomicReference<URI>();
private final Map<URI, RedisConnection> nodeConnections = new HashMap<URI, RedisConnection>();
private ScheduledFuture<?> monitorFuture;
private enum Role {
master,
slave
}
public ReplicatedConnectionManager(ReplicatedServersConfig cfg, Config config) {
super(config);
this.config = create(cfg);
initTimer(this.config);
for (URI addr : cfg.getNodeAddresses()) {
RFuture<RedisConnection> connectionFuture = connect(cfg, addr);
connectionFuture.awaitUninterruptibly();
RedisConnection connection = connectionFuture.getNow();
if (connection == null) {
continue;
}
Role role = Role.valueOf(connection.sync(RedisCommands.INFO_REPLICATION).get(ROLE_KEY));
if (Role.master.equals(role)) {
if (currentMaster.get() != null) {
throw new RedisException("Multiple masters detected");
}
currentMaster.set(addr);
log.info("{} is the master", addr);
this.config.setMasterAddress(addr);
} else {
log.info("{} is a slave", addr);
this.config.addSlaveAddress(addr);
}
}
if (currentMaster.get() == null) {
throw new RedisConnectionException("Can't connect to servers!");
}
init(this.config);
scheduleMasterChangeCheck(cfg);
}
@Override
protected MasterSlaveServersConfig create(BaseMasterSlaveServersConfig<?> cfg) {
MasterSlaveServersConfig res = super.create(cfg);
res.setDatabase(((ReplicatedServersConfig)cfg).getDatabase());
return res;
}
private RFuture<RedisConnection> connect(BaseMasterSlaveServersConfig<?> cfg, final URI addr) {
RedisConnection connection = nodeConnections.get(addr);
if (connection != null) {
return newSucceededFuture(connection);
}
RedisClient client = createClient(NodeType.MASTER, addr, cfg.getConnectTimeout(), cfg.getRetryInterval() * cfg.getRetryAttempts());
final RPromise<RedisConnection> result = newPromise();
RFuture<RedisConnection> future = client.connectAsync();
future.addListener(new FutureListener<RedisConnection>() {
@Override
public void operationComplete(Future<RedisConnection> future) throws Exception {
if (!future.isSuccess()) {
result.tryFailure(future.cause());
return;
}
RedisConnection connection = future.getNow();
if (connection.isActive()) {
nodeConnections.put(addr, connection);
result.trySuccess(connection);
} else {
connection.closeAsync();
result.tryFailure(new RedisException("Connection to " + connection.getRedisClient().getAddr() + " is not active!"));
}
}
});
return result;
}
private void scheduleMasterChangeCheck(final ReplicatedServersConfig cfg) {
monitorFuture = GlobalEventExecutor.INSTANCE.schedule(new Runnable() {
@Override
public void run() {
final URI master = currentMaster.get();
log.debug("Current master: {}", master);
final AtomicInteger count = new AtomicInteger(cfg.getNodeAddresses().size());
for (final URI addr : cfg.getNodeAddresses()) {
if (isShuttingDown()) {
return;
}
RFuture<RedisConnection> connectionFuture = connect(cfg, addr);
connectionFuture.addListener(new FutureListener<RedisConnection>() {
@Override
public void operationComplete(Future<RedisConnection> future) throws Exception {
if (!future.isSuccess()) {
log.error(future.cause().getMessage(), future.cause());
if (count.decrementAndGet() == 0) {
scheduleMasterChangeCheck(cfg);
}
return;
}
if (isShuttingDown()) {
return;
}
RedisConnection connection = future.getNow();
RFuture<Map<String, String>> result = connection.async(RedisCommands.INFO_REPLICATION);
result.addListener(new FutureListener<Map<String, String>>() {
@Override
public void operationComplete(Future<Map<String, String>> future)
throws Exception {
if (!future.isSuccess()) {
log.error(future.cause().getMessage(), future.cause());
if (count.decrementAndGet() == 0) {
scheduleMasterChangeCheck(cfg);
}
return;
}
Role role = Role.valueOf(future.getNow().get(ROLE_KEY));
if (Role.master.equals(role)) {
if (master.equals(addr)) {
log.debug("Current master {} unchanged", master);
} else if (currentMaster.compareAndSet(master, addr)) {
log.info("Master has changed from {} to {}", master, addr);
changeMaster(singleSlotRange.getStartSlot(), addr);
}
}
if (count.decrementAndGet() == 0) {
scheduleMasterChangeCheck(cfg);
}
}
});
}
});
}
}
}, cfg.getScanInterval(), TimeUnit.MILLISECONDS);
}
@Override
public void shutdown() {
monitorFuture.cancel(true);
super.shutdown();
for (RedisConnection connection : nodeConnections.values()) {
connection.getRedisClient().shutdown();
}
}
}
|
package com.github.javafaker;
import com.github.javafaker.service.FakeValuesService;
import com.github.javafaker.service.RandomService;
import java.util.Locale;
import java.util.Random;
/**
* Provides utility methods for generating fake strings, such as names, phone
* numbers, addresses. generate random strings with given patterns
*
* @author ren
*/
public class Faker {
private final RandomService randomService;
private final FakeValuesService fakeValuesService;
private final Ancient ancient;
private final App app;
private final Artist artist;
private final Avatar avatar;
private final Lorem lorem;
private final Music music;
private final Name name;
private final Number number;
private final Internet internet;
private final PhoneNumber phoneNumber;
private final Pokemon pokemon;
private final Address address;
private final Business business;
private final Book book;
private final ChuckNorris chuckNorris;
private final Color color;
private final Commerce commerce;
private final Currency currency;
private final Company company;
private final Crypto crypto;
private final IdNumber idNumber;
private final Hacker hacker;
private final Options options;
private final Code code;
private final Finance finance;
private final Food food;
private final GameOfThrones gameOfThrones;
private final DateAndTime dateAndTime;
private final Demographic demographic;
private final Educator educator;
private final Shakespeare shakespeare;
private final SlackEmoji slackEmoji;
private final Space space;
private final Superhero superhero;
private final Bool bool;
private final Team team;
private final Beer beer;
private final University university;
private final Cat cat;
private final File file;
private final Stock stock;
private final LordOfTheRings lordOfTheRings;
private final Zelda zelda;
private final HarryPotter harryPotter;
private final RockBand rockBand;
private final Esports esports;
private final Friends friends;
private final Hipster hipster;
private final Job job;
private final TwinPeaks twinPeaks;
private final RickAndMorty rickAndMorty;
private final Yoda yoda;
private final Matz matz;
private final Witcher witcher;
private final Weather weather;
private final Lebowski lebowski;
public Faker() {
this(Locale.ENGLISH);
}
public Faker(Locale locale) {
this(locale, null);
}
public Faker(Random random) {
this(Locale.ENGLISH, random);
}
public Faker(Locale locale, Random random) {
this.randomService = new RandomService(random);
this.fakeValuesService = new FakeValuesService(locale, randomService);
this.ancient = new Ancient(this);
this.app = new App(this);
this.artist = new Artist(this);
this.avatar = new Avatar(this);
this.lorem = new Lorem(this);
this.music = new Music(this);
this.name = new Name(this);
this.number = new Number(this);
this.internet = new Internet(this);
this.phoneNumber = new PhoneNumber(this);
this.pokemon = new Pokemon(this);
this.address = new Address(this);
this.book = new Book(this);
this.business = new Business(this);
this.chuckNorris = new ChuckNorris(this);
this.color = new Color(this);
this.idNumber = new IdNumber(this);
this.hacker = new Hacker(this);
this.company = new Company(this);
this.crypto = new Crypto(this);
this.commerce = new Commerce(this);
this.currency = new Currency(this);
this.options = new Options(this);
this.code = new Code(this);
this.file = new File(this);
this.finance = new Finance(this);
this.food = new Food(this);
this.gameOfThrones = new GameOfThrones(this);
this.dateAndTime = new DateAndTime(this);
this.demographic = new Demographic(this);
this.educator = new Educator(this);
this.shakespeare = new Shakespeare(this);
this.slackEmoji = new SlackEmoji(this);
this.space = new Space(this);
this.superhero = new Superhero(this);
this.team = new Team(this);
this.bool = new Bool(this);
this.beer = new Beer(this);
this.university = new University(this);
this.cat = new Cat(this);
this.stock = new Stock(this);
this.lordOfTheRings = new LordOfTheRings(this);
this.zelda = new Zelda(this);
this.harryPotter = new HarryPotter(this);
this.rockBand = new RockBand(this);
this.esports = new Esports(this);
this.friends = new Friends(this);
this.hipster = new Hipster(this);
this.job = new Job(this);
this.twinPeaks = new TwinPeaks(this);
this.rickAndMorty = new RickAndMorty(this);
this.yoda = new Yoda(this);
this.matz = new Matz(this);
this.witcher = new Witcher(this);
this.weather = new Weather(this);
this.lebowski = new Lebowski(this);
}
/**
* Constructs Faker instance with default argument.
*
* @return {@link Faker#Faker()}
*/
public static Faker instance() {
return new Faker();
}
/**
* Constructs Faker instance with provided {@link Locale}.
*
* @param locale - {@link Locale}
* @return {@link Faker#Faker(Locale)}
*/
public static Faker instance(Locale locale) {
return new Faker(locale);
}
/**
* Constructs Faker instance with provided {@link Random}.
*
* @param random - {@link Random}
* @return {@link Faker#Faker(Random)}
*/
public static Faker instance(Random random) {
return new Faker(random);
}
/**
* Constructs Faker instance with provided {@link Locale} and {@link Random}.
*
* @param locale - {@link Locale}
* @param random - {@link Random}
* @return {@link Faker#Faker(Locale, Random)}
*/
public static Faker instance(Locale locale, Random random) {
return new Faker(locale, random);
}
/**
* Returns a string with the '#' characters in the parameter replaced with random digits between 0-9 inclusive.
* <p>
* For example, the string "ABC##EFG" could be replaced with a string like "ABC99EFG".
*
* @param numberString
* @return
*/
public String numerify(String numberString) {
return fakeValuesService.numerify(numberString);
}
/**
* Returns a string with the '?' characters in the parameter replaced with random alphabetic
* characters.
* <p>
* For example, the string "12??34" could be replaced with a string like "12AB34".
*
* @param letterString
* @return
*/
public String letterify(String letterString) {
return fakeValuesService.letterify(letterString);
}
/**
* Returns a string with the '?' characters in the parameter replaced with random alphabetic
* characters.
* <p>
* For example, the string "12??34" could be replaced with a string like "12AB34".
*
* @param letterString
* @param isUpper
* @return
*/
public String letterify(String letterString, boolean isUpper) {
return fakeValuesService.letterify(letterString, isUpper);
}
/**
* Applies both a {@link #numerify(String)} and a {@link #letterify(String)}
* over the incoming string.
*
* @param string
* @return
*/
public String bothify(String string) {
return fakeValuesService.bothify(string);
}
/**
* Applies both a {@link #numerify(String)} and a {@link #letterify(String)}
* over the incoming string.
*
* @param string
* @param isUpper
* @return
*/
public String bothify(String string, boolean isUpper) {
return fakeValuesService.bothify(string, isUpper);
}
/**
* Generates a String that matches the given regular expression.
*/
public String regexify(String regex) {
return fakeValuesService.regexify(regex);
}
public RandomService random() {
return this.randomService;
}
public Currency currency() {
return currency;
}
FakeValuesService fakeValuesService() {
return this.fakeValuesService;
}
public Ancient ancient() {
return ancient;
}
public App app() {
return app;
}
public Artist artist() {
return artist;
}
public Avatar avatar() {
return avatar;
}
public Music music() {
return music;
}
public Name name() {
return name;
}
public Number number() {
return number;
}
public Internet internet() {
return internet;
}
public PhoneNumber phoneNumber() {
return phoneNumber;
}
public Pokemon pokemon() {
return pokemon;
}
public Lorem lorem() {
return lorem;
}
public Address address() {
return address;
}
public Book book() {
return book;
}
public Business business() {
return business;
}
public ChuckNorris chuckNorris() {
return chuckNorris;
}
public Color color() {
return color;
}
public Commerce commerce() {
return commerce;
}
public Company company() {
return company;
}
public Crypto crypto() {
return crypto;
}
public Hacker hacker() {
return hacker;
}
public IdNumber idNumber() {
return idNumber;
}
public Options options() {
return options;
}
public Code code() {
return code;
}
public File file() {
return file;
}
public Finance finance() {
return finance;
}
public Food food() {
return food;
}
public GameOfThrones gameOfThrones() {
return gameOfThrones;
}
public DateAndTime date() {
return dateAndTime;
}
public Demographic demographic() {
return demographic;
}
public Educator educator() {
return educator;
}
public SlackEmoji slackEmoji() {
return slackEmoji;
}
public Shakespeare shakespeare() {
return shakespeare;
}
public Space space() {
return space;
}
public Superhero superhero() {
return superhero;
}
public Bool bool() {
return bool;
}
public Team team() {
return team;
}
public Beer beer() {
return beer;
}
public University university() {
return university;
}
public Cat cat() {
return cat;
}
public Stock stock() {
return stock;
}
public LordOfTheRings lordOfTheRings() {
return lordOfTheRings;
}
public Zelda zelda() {
return zelda;
}
public HarryPotter harryPotter() {
return harryPotter;
}
public RockBand rockBand() {
return rockBand;
}
public Esports esports() {
return esports;
}
public Friends friends() {
return friends;
}
public Hipster hipster() {
return hipster;
}
public Job job() {
return job;
}
public TwinPeaks twinPeaks() {
return twinPeaks;
}
public RickAndMorty rickAndMorty() {
return rickAndMorty;
}
public Yoda yoda() {
return yoda;
}
public Matz matz() {
return matz;
}
public Witcher witcher() {
return witcher;
}
public Weather weather() {
return weather;
}
public Lebowski lebowski() {
return lebowski;
}
public String resolve(String key) {
return this.fakeValuesService.resolve(key, this, this);
}
/**
* Allows the evaluation of native YML expressions to allow you to build your own.
*
* The following are valid expressions:
* <ul>
* <li>#{regexify '(a|b){2,3}'}</li>
* <li>#{regexify '\\.\\*\\?\\+'}</li>
* <li>#{bothify '????','false'}</li>
* <li>#{Name.first_name} #{Name.first_name} #{Name.last_name}</li>
* <li>#{number.number_between '1','10'}</li>
* </ul>
* @param expression (see examples above)
* @return the evaluated string expression
* @throws RuntimeException if unable to evaluate the expression
*/
public String expression(String expression) {
return this.fakeValuesService.expression(expression, this);
}
}
|
/*
* Copyright (c) 2011-2018, Meituan Dianping. All Rights Reserved.
*
* 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.dianping.cat.report.page.state.task;
import java.util.Stack;
import com.dianping.cat.consumer.state.StateReportMerger;
import com.dianping.cat.consumer.state.model.entity.Machine;
import com.dianping.cat.consumer.state.model.entity.ProcessDomain;
import com.dianping.cat.consumer.state.model.entity.StateReport;
public class HistoryStateReportMerger extends StateReportMerger {
public HistoryStateReportMerger(StateReport stateReport) {
super(stateReport);
}
protected void visitMachineChildren(Machine to, Machine from) {
Stack<Object> objs = getObjects();
for (ProcessDomain source : from.getProcessDomains().values()) {
ProcessDomain target = to.findProcessDomain(source.getName());
if (target == null) {
target = new ProcessDomain(source.getName());
to.addProcessDomain(target);
}
objs.push(target);
source.accept(this);
objs.pop();
}
}
}
|
package com.affirm.android;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.res.ResourcesCompat;
import static com.affirm.android.AffirmColor.AFFIRM_COLOR_TYPE_BLUE;
import static com.affirm.android.AffirmLogoType.AFFIRM_DISPLAY_TYPE_LOGO;
public class AffirmPromotionButton extends FrameLayout {
private boolean htmlStyling;
private String message;
private PromotionButton promotionButton;
private PromotionWebView promotionWebView;
private AffirmLogoType affirmLogoType;
private AffirmColor affirmColor;
private String remoteCssUrl;
private String typefaceDeclaration;
private float affirmTextSize;
private int affirmTextColor;
private int affirmTextFont;
public AffirmPromotionButton(@NonNull Context context) {
this(context, null);
}
public AffirmPromotionButton(@NonNull Context context,
@Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public AffirmPromotionButton(@NonNull Context context,
@Nullable AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(@NonNull Context context, @Nullable AttributeSet attrs) {
TypedArray typedArray =
context.obtainStyledAttributes(attrs, R.styleable.AffirmPromotionButton);
int affirmLogoTypeOrdinal =
typedArray.getInt(R.styleable.AffirmPromotionButton_affirmLogoType,
AFFIRM_DISPLAY_TYPE_LOGO.getOrdinal());
int affirmColorOrdinal =
typedArray.getInt(R.styleable.AffirmPromotionButton_affirmColor,
AFFIRM_COLOR_TYPE_BLUE.getOrdinal());
affirmTextSize =
typedArray.getDimensionPixelSize(R.styleable.AffirmPromotionButton_affirmTextSize,
getResources().getDimensionPixelSize(R.dimen.affirm_promotion_size));
affirmTextColor =
typedArray.getResourceId(R.styleable.AffirmPromotionButton_affirmTextColor,
android.R.color.black);
affirmTextFont =
typedArray.getResourceId(R.styleable.AffirmPromotionButton_affirmTextFont,
0);
htmlStyling = typedArray.getBoolean(R.styleable.AffirmPromotionButton_htmlStyling,
false);
affirmLogoType = AffirmLogoType.getAffirmLogoType(affirmLogoTypeOrdinal);
affirmColor = AffirmColor.getAffirmColor(affirmColorOrdinal);
typedArray.recycle();
}
protected void setLabel(@NonNull String text) {
this.message = text;
removeAllViews();
if (htmlStyling) {
addView(promotionWebView);
promotionWebView.loadWebData(text, remoteCssUrl, typefaceDeclaration);
} else {
buildPromotionButtonIfNeeded();
addView(promotionButton);
promotionButton.setText(promotionButton.updateSpan(text));
}
}
private void buildPromotionButtonIfNeeded() {
if (promotionButton == null) {
promotionButton = new PromotionButton(getContext());
promotionButton.setAffirmTextSize(affirmTextSize);
promotionButton.setAffirmTextColor(affirmTextColor);
promotionButton.setTypeface(affirmTextFont > 0
? ResourcesCompat.getFont(getContext(), affirmTextFont) : Typeface.SERIF);
promotionButton.setAffirmColor(affirmColor);
promotionButton.setAffirmLogoType(affirmLogoType);
}
}
public boolean isHtmlStyle() {
return htmlStyling;
}
@Deprecated
public void setAffirmLogoType(@NonNull AffirmLogoType affirmLogoType) {
this.affirmLogoType = affirmLogoType;
buildPromotionButtonIfNeeded();
promotionButton.setAffirmLogoType(affirmLogoType);
}
@Deprecated
public void setAffirmColor(@NonNull AffirmColor affirmColor) {
this.affirmColor = affirmColor;
buildPromotionButtonIfNeeded();
promotionButton.setAffirmColor(affirmColor);
}
public void configWithHtmlStyling() {
this.configWithHtmlStyling(null);
}
public void configWithHtmlStyling(@Nullable String remoteCssUrl) {
this.configWithHtmlStyling(remoteCssUrl, null);
}
/**
* When you want to display the promo message in html style, if you want to custom the style
* of promo message, should pass the local or remote url and the file of typeface declaration
*
* @param remoteCssUrl Set if you want to use custom css. If not, just pass null
* @param typefaceDeclaration To embed your selected fonts into a webpage, you should pass
* the typeface declaration.
*/
public void configWithHtmlStyling(@Nullable String remoteCssUrl,
@Nullable String typefaceDeclaration) {
this.htmlStyling = true;
this.remoteCssUrl = remoteCssUrl;
this.typefaceDeclaration = typefaceDeclaration;
promotionWebView = new PromotionWebView(getContext());
}
public void configWithLocalStyling(@NonNull AffirmColor affirmColor,
@NonNull AffirmLogoType affirmLogoType) {
this.configWithLocalStyling(affirmColor, affirmLogoType, null);
}
public void configWithLocalStyling(@NonNull AffirmColor affirmColor,
@NonNull AffirmLogoType affirmLogoType,
@Nullable Typeface typeface) {
this.configWithLocalStyling(affirmColor, affirmLogoType, typeface,
android.R.color.black, R.dimen.affirm_progressbar_dimen);
}
public void configWithLocalStyling(@NonNull AffirmColor affirmColor,
@NonNull AffirmLogoType affirmLogoType,
@Nullable Typeface typeface,
int affirmTextColor) {
this.configWithLocalStyling(affirmColor, affirmLogoType, typeface,
affirmTextColor, R.dimen.affirm_progressbar_dimen);
}
/**
* When you want to display the promo message with a button, you can custom with the
* AffirmColor, AffirmLogoType & Typeface
*
* @param affirmColor Should be a kind of AffirmColor
* @param affirmLogoType Should be a kind of AffirmLogoType
* @param typeface The typeface you want to use
* @param affirmTextColor The textColor of promo message
* @param affirmTextSize The textSize of promo message
*/
public void configWithLocalStyling(@NonNull AffirmColor affirmColor,
@NonNull AffirmLogoType affirmLogoType,
@Nullable Typeface typeface,
int affirmTextColor,
int affirmTextSize) {
this.htmlStyling = false;
this.affirmColor = affirmColor;
this.affirmLogoType = affirmLogoType;
promotionButton = new PromotionButton(getContext());
promotionButton.setAffirmColor(affirmColor);
promotionButton.setAffirmLogoType(affirmLogoType);
promotionButton.setTypeface(typeface);
promotionButton.setAffirmTextColor(affirmTextColor);
promotionButton.setAffirmTextSize(getResources().getDimensionPixelSize(affirmTextSize));
}
protected AffirmColor getAffirmColor() {
return affirmColor;
}
protected AffirmLogoType getAffirmLogoType() {
return affirmLogoType;
}
boolean isEmpty() {
return TextUtils.isEmpty(message);
}
@Override
public void setOnClickListener(@Nullable OnClickListener l) {
super.setOnClickListener(l);
if (promotionWebView != null) {
promotionWebView.setWebViewClickListener(l);
}
}
public void destroy() {
if (promotionWebView != null) {
promotionWebView.destroyWebView();
promotionWebView = null;
}
}
}
|
package org.jooby.apitool;
import org.jooby.Jooby;
import org.junit.Test;
import java.nio.file.Path;
import java.nio.file.Paths;
public class KtResourceTest {
@Test
public void shouldWorkWithKotlinResource() throws Exception {
new RouteMethodAssert(new ApiParser(dir()).parseFully(kt("kt.ResourceApp")))
.next(r -> {
r.returnType("java.util.List<kt.KR1>");
r.pattern("/kr");
r.description("List KR.");
r.summary("KR API.");
r.param(p -> {
p.name("name")
.type(String.class)
.description("KR name.")
.kind(RouteParameter.Kind.QUERY);
});
}).done();
}
private Jooby kt(final String classname) throws Exception {
return (Jooby) getClass().getClassLoader().loadClass(classname).newInstance();
}
private Path dir() {
Path userdir = Paths.get(System.getProperty("user.dir"));
if (!userdir.toString().endsWith("jooby-apitool")) {
userdir = userdir.resolve("modules").resolve("jooby-apitool");
}
return userdir;
}
}
|
package projetopessoas;
/**
*
* @author Gabriel Ferreira Prodi
* Curso POO Java #011b
* 15/07/2020
*
*/
public abstract class Pessoa {
//Atributos
protected String nome;
private int idade;
private String sexo;
//Métodos
public final void fazerAniver(){
this.setIdade(getIdade() + 1);
}
/*
public Pessoa(String nome, int idade, String sexo) {
this.nome = nome;
this.idade = idade;
this.sexo = sexo;
}
*/
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getIdade() {
return idade;
}
public void setIdade(int idade) {
this.idade = idade;
}
public String getSexo() {
return sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
@Override
public String toString() {
return "Pessoa{" + "nome=" + nome + ", idade=" + idade + ", sexo=" + sexo + '}';
}
}
|
package com.itheima.demo04.MyException;
/*
自定义异常类:
java提供的异常类,不够我们使用,需要自己定义一些异常类
格式:
public class XXXExcepiton extends Exception | RuntimeException{
添加一个空参数的构造方法
添加一个带异常信息的构造方法
}
注意:
1.自定义异常类一般都是以Exception结尾,说明该类是一个异常类
2.自定义异常类,必须的继承Exception或者RuntimeException
继承Exception:那么自定义的异常类就是一个编译期异常,如果方法内部抛出了编译期异常,就必须处理这个异常,要么throws,要么try...catch
继承RuntimeException:那么自定义的异常类就是一个运行期异常,无需处理,交给虚拟机处理(中断处理)
*/
class RegisterException extends /*Exception*/ RuntimeException{
//添加一个空参数的构造方法
public RegisterException(){
super();
}
/*
添加一个带异常信息的构造方法
查看源码发现,所有的异常类都会有一个带异常信息的构造方法,
方法内部会调用父类带异常信息的构造方法,
让父类来处理这个异常信息
*/
public RegisterException(String message){
super(message);
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Created by MJesser on 13.10.2017.
//
// Copyright (c) 2006 - 2017 FORCAM GmbH. All rights reserved.
////////////////////////////////////////////////////////////////////////////////
package com.forcam.na.ffwebservices.client.api.shifttype;
import com.forcam.na.ffwebservices.client.api.AbstractLinkModelBuilder;
import com.forcam.na.ffwebservices.model.shifttype.ShiftTypePropertiesWSModel;
import javax.inject.Inject;
/**
* Creates a shift type link model.
*/
public class ShiftTypeLinkModelBuilder extends AbstractLinkModelBuilder<ShiftTypePropertiesWSModel> {
// ----------------------------------------------------------------------
// constructors
// ----------------------------------------------------------------------
@Inject
public ShiftTypeLinkModelBuilder() {
super(ShiftTypePropertiesWSModel.class);
}
}
|
package com.qx.gulimall.member.service.impl;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qx.common.utils.PageUtils;
import com.qx.common.utils.Query;
import com.qx.gulimall.member.dao.MemberCollectSubjectDao;
import com.qx.gulimall.member.entity.MemberCollectSubjectEntity;
import com.qx.gulimall.member.service.MemberCollectSubjectService;
@Service("memberCollectSubjectService")
public class MemberCollectSubjectServiceImpl extends ServiceImpl<MemberCollectSubjectDao, MemberCollectSubjectEntity> implements MemberCollectSubjectService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<MemberCollectSubjectEntity> page = this.page(
new Query<MemberCollectSubjectEntity>().getPage(params),
new QueryWrapper<MemberCollectSubjectEntity>()
);
return new PageUtils(page);
}
}
|
package org.vitrivr.cineast.core.config;
import java.io.File;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public final class ExtractionPipelineConfig {
/** Default value for size of thread-pool. */
public static final int DEFAULT_THREADPOOL_SIZE = 4;
/** Default value for size of task-queue. */
public static final int DEFAULT_TASKQUEUE_SIZE = 10;
/** Default value for size of segment-queue. */
public static final int DEFAULT_SEGMENTQUEUE_SIZE = 10;
/** */
private Integer shotQueueSize = DEFAULT_THREADPOOL_SIZE;
/** */
private Integer threadPoolSize = DEFAULT_TASKQUEUE_SIZE;
/** */
private Integer taskQueueSize = DEFAULT_SEGMENTQUEUE_SIZE;
private File outputLocation = new File(".");
@JsonCreator
public ExtractionPipelineConfig() {
}
@JsonProperty
public Integer getShotQueueSize(){
return this.shotQueueSize;
}
public void setShotQueueSize(Integer shotQueueSize) {
this.shotQueueSize = shotQueueSize;
}
@JsonProperty
public Integer getThreadPoolSize(){
return this.threadPoolSize;
}
public void setThreadPoolSize(int threadPoolSize) {
this.threadPoolSize = threadPoolSize;
}
@JsonProperty
public Integer getTaskQueueSize() {
return this.taskQueueSize;
}
public void setTaskQueueSize(int taskQueueSize) {
this.taskQueueSize = taskQueueSize;
}
@JsonProperty
public File getOutputLocation(){
return this.outputLocation;
}
public void setOutputLocation(String outputLocation) {
this.outputLocation = new File(outputLocation);
}
}
|
/*
* Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4095165 4321151
* @key intermittent
* @summary synopsis: activator should restart daemon services
* @author Ann Wollrath
*
* @library ../../../testlibrary
* @modules java.rmi/sun.rmi.registry
* java.rmi/sun.rmi.server
* java.rmi/sun.rmi.transport
* java.rmi/sun.rmi.transport.tcp
* java.base/sun.nio.ch
* @build TestLibrary RMID RMIDSelectorProvider ActivationLibrary ActivateMe RestartService_Stub
* @run main/othervm/policy=security.policy/timeout=240 RestartService
*/
import java.io.*;
import java.rmi.*;
import java.rmi.activation.*;
import java.rmi.server.*;
import java.rmi.registry.*;
import java.util.Vector;
import java.util.Properties;
public class RestartService
implements ActivateMe, Runnable
{
private ActivationID id;
private static Object lock = new Object();
private Vector responders = new Vector();
private static final String RESTARTABLE = "restartable";
private static final String ACTIVATABLE = "activatable";
public RestartService(ActivationID id, MarshalledObject mobj)
throws ActivationException, RemoteException
{
this.id = id;
Activatable.exportObject(this, id, 0);
ActivateMe obj;
String responder;
try {
Object[] stuff = (Object[]) mobj.get();
responder = (String) stuff[0];
System.err.println(responder + " service started");
obj = (ActivateMe) stuff[1];
} catch (Exception e) {
System.err.println("unable to obtain stub from marshalled object");
return;
}
obj.ping(responder);
}
public RestartService() throws RemoteException {
UnicastRemoteObject.exportObject(this, 0);
}
public void ping(String responder) {
System.err.println("RestartService: received ping from " + responder);
synchronized (lock) {
responders.add(responder);
lock.notify();
}
}
public boolean receivedPing(String responder) {
return responders.contains(responder);
}
public ActivateMe getUnicastVersion() throws RemoteException {
return new RestartService();
}
public ActivationID getID() {
return id;
}
/**
* Spawns a thread to deactivate the object.
*/
public void shutdown() throws Exception
{
(new Thread(this,"RestartService")).start();
}
/**
* Thread to deactivate object. First attempts to make object
* inactive (via the inactive method). If that fails (the
* object may still have pending/executing calls), then
* unexport the object forcibly.
*/
public void run() {
}
public static void main(String[] args) {
System.out.println("\nRegression test for bug 4095165\n");
TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager");
RMID rmid = null;
RestartService unicastObj = null;
try {
RMID.removeLog();
rmid = RMID.createRMIDOnEphemeralPort();
rmid.start();
/* Cause activation groups to have a security policy that will
* allow security managers to be downloaded and installed
*/
Properties p = new Properties();
// this test must always set policies/managers in its
// activation groups
p.put("java.security.policy",
TestParams.defaultGroupPolicy);
p.put("java.security.manager", "");
/*
* Create unicast object to be contacted when service is activated.
*/
unicastObj = new RestartService();
/*
* Create and register descriptors for a restartable and
* non-restartable service (respectively) in a group other than
* this VM's group.
*/
System.err.println("Creating descriptors");
Object[] stuff = new Object[] { RESTARTABLE, unicastObj };
MarshalledObject restartMobj = new MarshalledObject(stuff);
ActivationGroupDesc groupDesc =
new ActivationGroupDesc(p, null);
stuff[0] = ACTIVATABLE;
MarshalledObject activateMobj = new MarshalledObject(stuff);
ActivationGroupID groupID =
ActivationGroup.getSystem().registerGroup(groupDesc);
ActivationDesc restartableDesc =
new ActivationDesc(groupID, "RestartService", null,
restartMobj, true);
ActivationDesc activatableDesc =
new ActivationDesc(groupID, "RestartService", null,
activateMobj, false);
System.err.println("Registering descriptors");
ActivateMe restartableObj =
(ActivateMe) Activatable.register(restartableDesc);
ActivateMe activatableObj =
(ActivateMe) Activatable.register(activatableDesc);
/*
* Restart rmid; it should start up the restartable service
*/
rmid.restart();
/*
* Wait for service to be automatically restarted.
*/
boolean gotPing = false;
for (int i = 0; i < 15; i++) {
synchronized (lock) {
if (unicastObj.receivedPing(RESTARTABLE) != true) {
lock.wait(5000);
if (unicastObj.receivedPing(RESTARTABLE) == true) {
System.err.println("Test1 passed: rmid restarted" +
" service");
gotPing = true;
break;
}
} else {
gotPing = true;
break;
}
}
}
if (gotPing == false)
TestLibrary.bomb("Test1 failed: service not restarted by timeout", null);
/*
* Make sure activatable services wasn't automatically restarted.
*/
synchronized (lock) {
if (unicastObj.receivedPing(ACTIVATABLE) != true) {
lock.wait(5000);
if (unicastObj.receivedPing(ACTIVATABLE) != true) {
System.err.println("Test2 passed: rmid did not " +
"restart activatable service");
return;
}
}
TestLibrary.bomb("Test2 failed: activatable service restarted!", null);
}
} catch (Exception e) {
TestLibrary.bomb("test failed", e);
} finally {
rmid.cleanup();
TestLibrary.unexport(unicastObj);
}
}
}
|
package com.cloud.api.command.user.template;
import com.cloud.acl.SecurityChecker;
import com.cloud.api.APICommand;
import com.cloud.api.APICommandGroup;
import com.cloud.api.ApiCommandJobType;
import com.cloud.api.ApiConstants;
import com.cloud.api.ApiErrorCode;
import com.cloud.api.BaseAsyncCreateCmd;
import com.cloud.api.Parameter;
import com.cloud.api.ResponseObject.ResponseView;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.GuestOSResponse;
import com.cloud.api.response.ProjectResponse;
import com.cloud.api.response.SnapshotResponse;
import com.cloud.api.response.TemplateResponse;
import com.cloud.api.response.UserVmResponse;
import com.cloud.api.response.VolumeResponse;
import com.cloud.context.CallContext;
import com.cloud.event.EventTypes;
import com.cloud.legacymodel.exceptions.InvalidParameterValueException;
import com.cloud.legacymodel.exceptions.PermissionDeniedException;
import com.cloud.legacymodel.exceptions.ResourceAllocationException;
import com.cloud.legacymodel.storage.VirtualMachineTemplate;
import com.cloud.legacymodel.storage.Volume;
import com.cloud.legacymodel.user.Account;
import com.cloud.model.enumeration.MaintenancePolicy;
import com.cloud.model.enumeration.OptimiseFor;
import com.cloud.projects.Project;
import com.cloud.storage.Snapshot;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@APICommand(name = "createTemplate", group = APICommandGroup.TemplateService, responseObject = TemplateResponse.class, description = "Creates a template of a virtual machine. " + "The virtual " +
"machine must be in a " +
"STOPPED state. "
+ "A template created from this command is automatically designated as a private template visible to the account that created it.", responseView = ResponseView.Restricted,
requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class CreateTemplateCmd extends BaseAsyncCreateCmd {
public static final Logger s_logger = LoggerFactory.getLogger(CreateTemplateCmd.class.getName());
private static final String s_name = "createtemplateresponse";
// ///////////////////////////////////////////////////
// ////////////// API parameters /////////////////////
// ///////////////////////////////////////////////////
@Parameter(name = ApiConstants.SNAPSHOT_ID,
type = CommandType.UUID,
entityType = SnapshotResponse.class,
description = "the ID of the snapshot the template is being created from. Either this parameter, or volumeId has to be passed in")
protected Long snapshotId;
@Parameter(name = ApiConstants.VOLUME_ID,
type = CommandType.UUID,
entityType = VolumeResponse.class,
description = "the ID of the disk volume the template is being created from. Either this parameter, or snapshotId has to be passed in")
protected Long volumeId;
@Deprecated
@Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.UUID, entityType = UserVmResponse.class,
description = "DEPRECATED SINCE 5.1.0: Optional, VM ID. If this presents, it is going to create a baremetal template for VM this ID refers to. This is only for VM " +
"whose hypervisor type is BareMetal")
protected Long vmId;
@Parameter(name = ApiConstants.DETAILS, type = CommandType.MAP, description = "Template details in key/value pairs using format details[i].keyname=keyvalue. Example: " +
"details[0].hypervisortoolsversion=xenserver61")
protected Map details;
@Parameter(name = ApiConstants.IS_DYNAMICALLY_SCALABLE,
type = CommandType.BOOLEAN,
description = "true if template contains XS tools inorder to support dynamic scaling of VM cpu/memory")
protected Boolean isDynamicallyScalable;
@Parameter(name = ApiConstants.BITS, type = CommandType.INTEGER, description = "32 or 64 bit")
private Integer bits;
@Parameter(name = ApiConstants.DISPLAY_TEXT,
type = CommandType.STRING,
required = true,
description = "the display text of the template. This is usually used for display purposes.",
length = 4096)
private String displayText;
@Parameter(name = ApiConstants.IS_FEATURED, type = CommandType.BOOLEAN, description = "true if this template is a featured template, false otherwise")
private Boolean featured;
@Parameter(name = ApiConstants.IS_PUBLIC, type = CommandType.BOOLEAN, description = "true if this template is a public template, false otherwise")
private Boolean publicTemplate;
@Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "the name of the template")
private String templateName;
@Parameter(name = ApiConstants.OS_TYPE_ID,
type = CommandType.UUID,
entityType = GuestOSResponse.class,
description = "the ID of the OS Type that best represents the OS of this template.")
private Long osTypeId;
@Parameter(name = ApiConstants.PASSWORD_ENABLED,
type = CommandType.BOOLEAN,
description = "true if the template supports the password reset feature; default is false")
private Boolean passwordEnabled;
@Parameter(name = ApiConstants.URL, type = CommandType.STRING)
private String url;
@Parameter(name = ApiConstants.TEMPLATE_TAG, type = CommandType.STRING, description = "the tag for this template.")
private String templateTag;
@Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, description = "create template for the project")
private Long projectId;
@Parameter(name = ApiConstants.HYPERVISOR, type = CommandType.STRING, description = "the target hypervisor for the template")
private String hypervisor;
@Parameter(name = ApiConstants.MANUFACTURER_STRING, type = CommandType.STRING, description = "Manufacturer String to put in hardware info, defaults to 'Mission Critical Cloud'")
private String manufacturerString;
@Parameter(name = ApiConstants.OPTIMISE_FOR, type = CommandType.STRING, description = "Optimise for 'Windows' or 'Generic'")
private String optimiseFor;
@Parameter(name = ApiConstants.CPU_FLAGS, type = CommandType.STRING, description = "Optionally specify CPU flags to pass to VM")
private String cpuFlags;
@Parameter(name = ApiConstants.MAC_LEARNING, type = CommandType.STRING, description = "Set mag learning boolean, defaults to false")
private Boolean macLearning;
@Parameter(name = ApiConstants.MAINTENANCE_POLICY, type = CommandType.STRING, description = "Maintenance policy for this template, either LiveMigrate or ShutdownAndStart.")
private String maintenancePolicy;
// ///////////////////////////////////////////////////
// ///////////////// Accessors ///////////////////////
// ///////////////////////////////////////////////////
public static String getResultObjectName() {
return "template";
}
public Integer getBits() {
return bits;
}
public String getDisplayText() {
return displayText;
}
public Boolean isFeatured() {
return featured;
}
public Boolean isPublic() {
return publicTemplate;
}
public Long getOsTypeId() {
return osTypeId;
}
public Boolean isPasswordEnabled() {
return passwordEnabled;
}
@Deprecated
public Long getVmId() {
return vmId;
}
@Deprecated
public String getUrl() {
return url;
}
public String getTemplateTag() {
return templateTag;
}
public String getHypervisor() {
return hypervisor;
}
public String getManufacturerString() {
return manufacturerString;
}
public OptimiseFor getOptimiseFor() {
if (optimiseFor != null) {
return OptimiseFor.valueOf(optimiseFor);
} else {
return OptimiseFor.Generic;
}
}
public MaintenancePolicy getMaintenancePolicy() {
if (maintenancePolicy != null) {
return MaintenancePolicy.valueOf(maintenancePolicy);
} else {
return MaintenancePolicy.LiveMigrate;
}
}
public String getCpuFlags() {
return cpuFlags;
}
public Boolean getMacLearning() {
return macLearning;
}
public Map getDetails() {
if (details == null || details.isEmpty()) {
return null;
}
final Collection paramsCollection = details.values();
final Map params = (Map) paramsCollection.toArray()[0];
return params;
}
public boolean isDynamicallyScalable() {
return isDynamicallyScalable == null ? false : isDynamicallyScalable;
}
@Override
public String getEventType() {
return EventTypes.EVENT_TEMPLATE_CREATE;
}
@Override
public String getEventDescription() {
return "creating template: " + getTemplateName();
}
// ///////////////////////////////////////////////////
// ///////////// API Implementation///////////////////
// ///////////////////////////////////////////////////
public String getTemplateName() {
return templateName;
}
@Override
public ApiCommandJobType getInstanceType() {
return ApiCommandJobType.Template;
}
@Override
public void create() throws ResourceAllocationException {
VirtualMachineTemplate template = null;
template = _templateService.createPrivateTemplateRecord(this, _accountService.getAccount(getEntityOwnerId()));
if (template != null) {
setEntityId(template.getId());
setEntityUuid(template.getUuid());
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create a template");
}
}
public Long getVolumeId() {
return volumeId;
}
public Long getSnapshotId() {
return snapshotId;
}
@Override
public void execute() {
CallContext.current().setEventDetails(
"Template Id: " + getEntityId() + (getSnapshotId() == null ? " from volume Id: " + getVolumeId() : " from snapshot Id: " + getSnapshotId()));
VirtualMachineTemplate template = null;
template = _templateService.createPrivateTemplate(this);
if (template != null) {
final List<TemplateResponse> templateResponses = _responseGenerator.createTemplateResponses(ResponseView.Restricted, template.getId(), snapshotId, volumeId, false);
TemplateResponse response = new TemplateResponse();
if (templateResponses != null && !templateResponses.isEmpty()) {
response = templateResponses.get(0);
}
response.setResponseName(getCommandName());
setResponseObject(response);
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create private template");
}
}
@Override
public String getCommandName() {
return s_name;
}
@Override
public long getEntityOwnerId() {
final Long volumeId = getVolumeId();
final Long snapshotId = getSnapshotId();
final Account callingAccount = CallContext.current().getCallingAccount();
if (volumeId != null) {
final Volume volume = _entityMgr.findById(Volume.class, volumeId);
if (volume != null) {
_accountService.checkAccess(callingAccount, SecurityChecker.AccessType.UseEntry, false, volume);
} else {
throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId);
}
} else {
final Snapshot snapshot = _entityMgr.findById(Snapshot.class, snapshotId);
if (snapshot != null) {
_accountService.checkAccess(callingAccount, SecurityChecker.AccessType.UseEntry, false, snapshot);
} else {
throw new InvalidParameterValueException("Unable to find snapshot by id=" + snapshotId);
}
}
if (projectId != null) {
final Project project = _projectService.getProject(projectId);
if (project != null) {
if (project.getState() == Project.State.Active) {
final Account projectAccount = _accountService.getAccount(project.getProjectAccountId());
_accountService.checkAccess(callingAccount, SecurityChecker.AccessType.UseEntry, false, projectAccount);
return project.getProjectAccountId();
} else {
final PermissionDeniedException ex =
new PermissionDeniedException("Can't add resources to the project with specified projectId in state=" + project.getState() +
" as it's no longer active");
ex.addProxyObject(project.getUuid(), "projectId");
throw ex;
}
} else {
throw new InvalidParameterValueException("Unable to find project by id");
}
}
return callingAccount.getId();
}
}
|
package vswe.stevescarts.Arcade;
import java.util.ArrayList;
public class PropertyGroup {
private ArrayList<Property> properties;
public PropertyGroup() {
properties = new ArrayList<Property>();
}
public ArrayList<Property> getProperties() {
return properties;
}
public void add(Property property) {
properties.add(property);
}
}
|
package rocks.inspectit.oce.bootstrap;
import java.lang.instrument.Instrumentation;
/**
* Controller itnerface for the Agent. Its implementation is {@link rocks.inspectit.oce.core.AgentImpl}.
* The implementation must provide a default cosntructor without side effects!
* The actual initialization should happen in {@link #start(String, Instrumentation)}, which is called by {@link AgentManager}
*/
public interface IAgent {
/**
* Initialized and starts the agent.
* @param agentCmdArgs the command line arguments passed to the Agent
* @param instrumentation the {@link Instrumentation} instance passed to the agent
*/
void start(String agentCmdArgs, Instrumentation instrumentation);
/**
* Shuts down and destroys the agent.
*/
void destroy();
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.resourcemanager.cosmos.samples;
import com.azure.core.credential.TokenCredential;
import com.azure.core.http.policy.HttpLogDetailLevel;
import com.azure.core.management.AzureEnvironment;
import com.azure.core.management.exception.ManagementException;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.resourcemanager.Azure;
import com.azure.resourcemanager.cosmos.models.CosmosDBAccount;
import com.azure.resourcemanager.cosmos.models.DatabaseAccountKind;
import com.azure.resourcemanager.cosmos.models.DatabaseAccountListConnectionStringsResult;
import com.azure.resourcemanager.resources.fluentcore.arm.Region;
import com.azure.core.management.profile.AzureProfile;
import com.azure.resourcemanager.samples.Utils;
/**
* Azure CosmosDB sample for high availability.
* - Create a CosmosDB configured with MongoDB kind.
* - Get the mongodb connection string
* - Delete the CosmosDB.
*/
public final class CreateCosmosDBWithKindMongoDB {
static final String DATABASE_ID = "TestDB";
static final String COLLECTION_ID = "TestCollection";
/**
* Main function which runs the actual sample.
* @param azure instance of the azure client
* @return true if sample runs successfully
*/
public static boolean runSample(Azure azure) {
final String docDBName = azure.sdkContext().randomResourceName("docDb", 10);
final String rgName = azure.sdkContext().randomResourceName("rgNEMV", 24);
try {
//============================================================
// Create a CosmosDB
System.out.println("Creating a CosmosDB...");
CosmosDBAccount cosmosDBAccount = azure.cosmosDBAccounts().define(docDBName)
.withRegion(Region.US_EAST)
.withNewResourceGroup(rgName)
.withKind(DatabaseAccountKind.MONGO_DB)
.withEventualConsistency()
.withWriteReplication(Region.US_WEST)
.withReadReplication(Region.US_CENTRAL)
.create();
System.out.println("Created CosmosDB");
Utils.print(cosmosDBAccount);
System.out.println("Get the MongoDB connection string");
DatabaseAccountListConnectionStringsResult databaseAccountListConnectionStringsResult = cosmosDBAccount.listConnectionStrings();
System.out.println("MongoDB connection string: "
+ databaseAccountListConnectionStringsResult.connectionStrings().get(0).connectionString());
//============================================================
// Delete CosmosDB
System.out.println("Deleting the CosmosDB");
// work around CosmosDB service issue returning 404 ManagementException on delete operation
try {
azure.cosmosDBAccounts().deleteById(cosmosDBAccount.id());
} catch (ManagementException e) {
}
System.out.println("Deleted the CosmosDB");
return true;
} catch (Exception e) {
System.err.println(e.getMessage());
} finally {
try {
System.out.println("Deleting resource group: " + rgName);
azure.resourceGroups().beginDeleteByName(rgName);
System.out.println("Deleted resource group: " + rgName);
} catch (NullPointerException npe) {
System.out.println("Did not create any resources in Azure. No clean up is necessary");
} catch (Exception g) {
g.printStackTrace();
}
}
return false;
}
/**
* Main entry point.
* @param args the parameters
*/
public static void main(String[] args) {
try {
//=============================================================
// Authenticate
final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
final TokenCredential credential = new DefaultAzureCredentialBuilder()
.build();
Azure azure = Azure
.configure()
.withLogLevel(HttpLogDetailLevel.BASIC)
.authenticate(credential, profile)
.withDefaultSubscription();
// Print selected subscription
System.out.println("Selected subscription: " + azure.subscriptionId());
runSample(azure);
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
private CreateCosmosDBWithKindMongoDB() {
}
}
|
package com.bestaone.aiwan.user.service;
import com.bestaone.aiwan.core.service.BaseService;
import com.bestaone.aiwan.user.domain.Resource;
import java.util.List;
public interface ResourceService extends BaseService<Resource, Long>{
List<Resource> findByUserId(Long userId);
}
|
package com.pk.mynotes.fragments;
import android.os.Bundle;
import android.os.Parcelable;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.navigation.NavDirections;
import com.pk.mynotes.R;
import com.pk.mynotes.models.Note;
import java.io.Serializable;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
import java.lang.SuppressWarnings;
import java.util.HashMap;
public class NotesListFragmentDirections {
private NotesListFragmentDirections() {
}
@NonNull
public static ActionAddNewNoteToEditNoteFragment2 actionAddNewNoteToEditNoteFragment2() {
return new ActionAddNewNoteToEditNoteFragment2();
}
public static class ActionAddNewNoteToEditNoteFragment2 implements NavDirections {
private final HashMap arguments = new HashMap();
private ActionAddNewNoteToEditNoteFragment2() {
}
@NonNull
public ActionAddNewNoteToEditNoteFragment2 setNote(@Nullable Note Note) {
this.arguments.put("Note", Note);
return this;
}
@Override
@SuppressWarnings("unchecked")
@NonNull
public Bundle getArguments() {
Bundle __result = new Bundle();
if (arguments.containsKey("Note")) {
Note Note = (Note) arguments.get("Note");
if (Parcelable.class.isAssignableFrom(Note.class) || Note == null) {
__result.putParcelable("Note", Parcelable.class.cast(Note));
} else if (Serializable.class.isAssignableFrom(Note.class)) {
__result.putSerializable("Note", Serializable.class.cast(Note));
} else {
throw new UnsupportedOperationException(Note.class.getName() + " must implement Parcelable or Serializable or must be an Enum.");
}
}
return __result;
}
@Override
public int getActionId() {
return R.id.action_addNewNote_to_editNoteFragment2;
}
@SuppressWarnings("unchecked")
@Nullable
public Note getNote() {
return (Note) arguments.get("Note");
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null || getClass() != object.getClass()) {
return false;
}
ActionAddNewNoteToEditNoteFragment2 that = (ActionAddNewNoteToEditNoteFragment2) object;
if (arguments.containsKey("Note") != that.arguments.containsKey("Note")) {
return false;
}
if (getNote() != null ? !getNote().equals(that.getNote()) : that.getNote() != null) {
return false;
}
if (getActionId() != that.getActionId()) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = 1;
result = 31 * result + (getNote() != null ? getNote().hashCode() : 0);
result = 31 * result + getActionId();
return result;
}
@Override
public String toString() {
return "ActionAddNewNoteToEditNoteFragment2(actionId=" + getActionId() + "){"
+ "Note=" + getNote()
+ "}";
}
}
}
|
/*
* Copyright 2000-2009 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.execution.application;
import com.intellij.execution.JavaExecutionUtil;
import com.intellij.execution.Location;
import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.configurations.ConfigurationUtil;
import com.intellij.execution.junit.JavaRunConfigurationProducerBase;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.util.PsiMethodUtil;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.Nullable;
public class ApplicationConfigurationProducer extends JavaRunConfigurationProducerBase<ApplicationConfiguration> {
public ApplicationConfigurationProducer() {
super(ApplicationConfigurationType.getInstance());
}
@Override
protected boolean setupConfigurationFromContext(ApplicationConfiguration configuration,
ConfigurationContext context,
Ref<PsiElement> sourceElement) {
Location location = JavaExecutionUtil.stepIntoSingleClass(context.getLocation());
if (location == null) return false;
final PsiElement element = location.getPsiElement();
if (!element.isPhysical()) return false;
PsiElement currentElement = element;
PsiMethod method;
while ((method = findMain(currentElement)) != null) {
final PsiClass aClass = method.getContainingClass();
if (ConfigurationUtil.MAIN_CLASS.value(aClass)) {
sourceElement.set(method);
setupConfiguration(configuration, aClass, context);
return true;
}
currentElement = method.getParent();
}
final PsiClass aClass = ApplicationConfigurationType.getMainClass(element);
if (aClass == null) return false;
sourceElement.set(aClass);
setupConfiguration(configuration, aClass, context);
return true;
}
private void setupConfiguration(ApplicationConfiguration configuration,
final PsiClass aClass,
final ConfigurationContext context) {
configuration.MAIN_CLASS_NAME = JavaExecutionUtil.getRuntimeQualifiedName(aClass);
configuration.setGeneratedName();
setupConfigurationModule(context, configuration);
}
@Nullable
private static PsiMethod findMain(PsiElement element) {
PsiMethod method;
while ((method = PsiTreeUtil.getParentOfType(element, PsiMethod.class)) != null) {
if (PsiMethodUtil.isMainMethod(method)) return method;
else element = method.getParent();
}
return null;
}
@Override
public boolean isConfigurationFromContext(ApplicationConfiguration appConfiguration, ConfigurationContext context) {
final PsiClass aClass = ApplicationConfigurationType.getMainClass(context.getPsiLocation());
if (aClass != null && Comparing.equal(JavaExecutionUtil.getRuntimeQualifiedName(aClass), appConfiguration.MAIN_CLASS_NAME)) {
final Module configurationModule = appConfiguration.getConfigurationModule().getModule();
if (Comparing.equal(context.getModule(), configurationModule)) return true;
ApplicationConfiguration template = (ApplicationConfiguration)context.getRunManager()
.getConfigurationTemplate(getConfigurationFactory())
.getConfiguration();
final Module predefinedModule = template.getConfigurationModule().getModule();
if (Comparing.equal(predefinedModule, configurationModule)) {
return true;
}
}
return false;
}
}
|
package com.rocket.core.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.rocket.core.StaticHolder;
@Configuration
public class CoreSpringConfiguration {
@Bean
public ObjectMapper objectMapper() {
return StaticHolder.getMapper();
}
@Bean
public ObjectReader objectReader() {
return StaticHolder.getMapper().reader();
}
@Bean
public ObjectWriter objectWriter() {
return StaticHolder.getMapper().writer();
}
}
|
package eu.codeloop.task1;
import java.util.List;
public final class Numbers {
private Numbers() {
}
public static List<Integer> findOddNumbers(List<String> numbers) {
throw new UnsupportedOperationException("TODO");
}
}
|
package benchmarks.REVE.loop3.Eq;
public class newV {
int f(int n) {
int i = 1;
int j = 2;
if (n < 1) {
n = 1;
}
while (i < n) {
j = j + 2;
i++;
}
return j;
}
}
|
package com.google.android.gms.internal;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
public final class zzeuh {
private static final AtomicReference<zzeuh> zzlws = new AtomicReference();
private zzeuh(Context context) {
}
@Nullable
public static zzeuh zzchr() {
return (zzeuh) zzlws.get();
}
public static Set<String> zzchs() {
return Collections.emptySet();
}
public static zzeuh zzew(Context context) {
zzlws.compareAndSet(null, new zzeuh(context));
return (zzeuh) zzlws.get();
}
public static void zzf(@NonNull FirebaseApp firebaseApp) {
}
public static FirebaseOptions zzra(@NonNull String str) {
return null;
}
}
|
package com.catherine.intercepting_filter;
import com.catherine.intercepting_filter.member.MemberInfo;
public class CountryFilter implements Filter {
private int country;
public CountryFilter(int country) {
this.country = country;
}
@Override
public boolean run(MemberInfo info) {
// System.out.println(String.format("Country:%s", info.getCountry()));
return country == info.getCountry();
}
}
|
/*
* Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opensingular.form.script;
import org.opensingular.form.SIList;
/**
* Wrapper para adaptação de um SIList em um objeto manipulado pela engine de Javascript.
*
* @author Daniel Bordin
*/
public class JSWrapperList extends JSWrapperInstance<SIList<?>> {
public JSWrapperList(RuntimeDocumentScript runtime, SIList<?> instance) {
super(runtime, instance);
}
@Override
public Object getSlot(int index) {
return getRuntime().wrapper(getInstance().get(index));
}
@Override
public boolean hasSlot(int index) {
return getInstance().size() > index;
}
@Override
public boolean isArray() {
return true;
}
}
|
/* *******************************************************************************************************
Copyright (c) 2015 EXILANT Technologies Private Limited
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.exilant.exility.core;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
* used only for debugging. Should not used in regular production
*
*/
public class SessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent evt) {
System.out.println(" A new sssion was created with id "
+ evt.getSession().getId());
}
@Override
public void sessionDestroyed(HttpSessionEvent evt) {
System.out.println(" Session is going to be destoyed with id "
+ evt.getSession().getId());
}
}
|
package dakara.eclipse.plugin.log;
import org.eclipse.core.runtime.ILog;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.osgi.framework.Bundle;
public class EclipsePluginLogger {
private final String bundleId;
private final ILog logger;
public EclipsePluginLogger(String bundleId) {
this.bundleId = bundleId;
final Bundle bundle = Platform.getBundle(bundleId);
logger = Platform.getLog(bundle);
}
public void info(String message) {
logger.log(new Status(IStatus.INFO, bundleId, message));
}
public void warn(String message) {
logger.log(new Status(IStatus.WARNING, bundleId, message));
}
public void error(String message, Throwable error) {
logger.log(new Status(IStatus.ERROR, bundleId, message, error));
}
}
|
package com.microservices.auth.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.microservices.auth.domain.Response;
import com.microservices.auth.model.User;
import com.microservices.auth.service.UserService;
@RestController
@CrossOrigin
public class PreLoginController {
@Autowired private UserService userService;
@RequestMapping(value="/registration",method=RequestMethod.POST)
public ResponseEntity<Response> registration(@RequestBody User user){
User dbUser = userService.save(user);
if(dbUser != null) {
return new ResponseEntity<Response>(new Response("User is saved successfully"), HttpStatus.OK);
}
return null;
}
}
|
package com.alibaba.alink.pipeline.dataproc.format;
import org.apache.flink.ml.api.misc.param.Params;
import com.alibaba.alink.operator.common.dataproc.format.FormatType;
import com.alibaba.alink.params.dataproc.format.ColumnsToKvParams;
/**
* Transform data type from Columns to Kv.
*/
public class ColumnsToKv extends BaseFormatTrans <ColumnsToKv> implements ColumnsToKvParams <ColumnsToKv> {
private static final long serialVersionUID = 7120784602225738871L;
public ColumnsToKv() {
this(new Params());
}
public ColumnsToKv(Params params) {
super(FormatType.COLUMNS, FormatType.KV, params);
}
}
|
/*
* Copyright 2016 http://www.hswebframework.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.hswebframework.web.controller.authorization;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.hswebframework.web.authorization.Authentication;
import org.hswebframework.web.authorization.Permission;
import org.hswebframework.web.authorization.annotation.Authorize;
import org.hswebframework.web.authorization.exception.UnAuthorizedException;
import org.hswebframework.web.authorization.token.TokenState;
import org.hswebframework.web.authorization.token.UserToken;
import org.hswebframework.web.authorization.token.UserTokenManager;
import org.hswebframework.web.commons.entity.PagerResult;
import org.hswebframework.web.commons.entity.param.QueryParamEntity;
import org.hswebframework.web.controller.CreateController;
import org.hswebframework.web.controller.QueryController;
import org.hswebframework.web.controller.message.ResponseMessage;
import org.hswebframework.web.entity.authorization.UserEntity;
import org.hswebframework.web.entity.authorization.bind.BindRoleUserEntity;
import org.hswebframework.web.logging.AccessLogger;
import org.hswebframework.web.service.authorization.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import static org.hswebframework.web.controller.message.ResponseMessage.ok;
/**
* 用户管理控制器
*
* @author zhouhao
*/
@RestController
@RequestMapping("${hsweb.web.mappings.user:user}")
@Authorize(permission = "user")
@AccessLogger("用户管理")
@Api(tags = "user-manager", description = "用户基本信息管理")
public class UserController implements
QueryController<UserEntity, String, QueryParamEntity>,
CreateController<BindRoleUserEntity, String, BindRoleUserEntity> {
private UserService userService;
private UserTokenManager userTokenManager;
@Override
@SuppressWarnings("unchecked")
public UserService getService() {
return userService;
}
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
@Autowired(required = false)
public void setUserTokenManager(UserTokenManager userTokenManager) {
this.userTokenManager = userTokenManager;
}
@GetMapping("/tokens")
@Authorize(action = Permission.ACTION_QUERY)
@AccessLogger("获取所有已登录用户的信息")
public ResponseMessage<List<UserToken>> userTokens() {
if (userTokenManager == null) throw new UnsupportedOperationException("userTokenManager is null");
return ok(userTokenManager.allLoggedUser());
}
@PutMapping("/tokens/{token}/{state}")
@Authorize(action = "change-state")
@AccessLogger("修改token的状态")
public ResponseMessage<List<UserToken>> makeOffline(@PathVariable String token, @PathVariable TokenState state) {
if (userTokenManager == null) throw new UnsupportedOperationException("userTokenManager is null");
userTokenManager.changeTokenState(token, state);
return ok();
}
@Override
public ResponseMessage<PagerResult<UserEntity>> list(QueryParamEntity param) {
param.excludes("password", "salt");
return QueryController.super.list(param)
.exclude(UserEntity.class, "password", "salt");
}
@Override
public ResponseMessage<UserEntity> getByPrimaryKey(@PathVariable String id) {
return QueryController.super.getByPrimaryKey(id)
.exclude(UserEntity.class, "password", "salt");
}
@Authorize(action = "update")
@PutMapping(path = "/{id:.+}")
@AccessLogger("{update_by_primary_key}")
@ApiOperation("根据ID修改用户信息")
public ResponseMessage<Void> updateByPrimaryKey(@PathVariable String id,
@RequestBody BindRoleUserEntity userModel) {
getService().update(id, userModel);
return ok();
}
@Authorize(merge = false)
@PutMapping(path = "/password")
@AccessLogger("{update_password_login_user}")
@ApiOperation("修改当前用户的密码")
public ResponseMessage<Void> updateLoginUserPassword(@RequestParam String password,
@RequestParam String oldPassword) {
Authentication authentication = Authentication.current().orElseThrow(UnAuthorizedException::new);
getService().updatePassword(authentication.getUser().getId(), oldPassword, password);
return ok();
}
@Authorize(action = Permission.ACTION_UPDATE)
@PutMapping(path = "/password/{id:.+}")
@AccessLogger("{update_password_by_id}")
@ApiOperation("修改指定用户的密码")
public ResponseMessage<Void> updateByPasswordPrimaryKey(@PathVariable String id,
@RequestParam String password,
@RequestParam String oldPassword) {
getService().updatePassword(id, oldPassword, password);
return ok();
}
@Override
public ResponseMessage<String> add(@RequestBody BindRoleUserEntity data) {
Authentication authentication = Authentication.current().orElse(null);
if (null != authentication) {
data.setCreatorId(authentication.getUser().getId());
}
return CreateController.super.add(data);
}
@Authorize(action = "enable")
@PutMapping(path = "/{id}/enable")
@AccessLogger("{enable_user}")
@ApiOperation("启用用户")
public ResponseMessage<Boolean> enable(@PathVariable String id) {
return ok(getService().enable(id));
}
@Authorize(action = "disable")
@PutMapping(path = "/{id}/disable")
@AccessLogger("{disable_user}")
@ApiOperation("禁用用户")
public ResponseMessage<Boolean> disable(@PathVariable String id) {
return ok(getService().disable(id));
}
@Override
public BindRoleUserEntity modelToEntity(BindRoleUserEntity model, BindRoleUserEntity entity) {
return model;
}
}
|
package com.baidubce.services.iotviz.model;
import com.baidubce.services.iothub.model.BaseRequest;
/**
* Request to create a token
*/
public class CreateTokenRequest extends BaseRequest {
private int ttl;
public int getTtl() {
return ttl;
}
public void setTtl(int ttl) {
this.ttl = ttl;
}
}
|
package com.huijiewei.agile.app.admin.adapter.persistence.repository;
import com.cosium.spring.data.jpa.entity.graph.domain.EntityGraphUtils;
import com.cosium.spring.data.jpa.entity.graph.repository.EntityGraphJpaRepository;
import com.cosium.spring.data.jpa.entity.graph.repository.EntityGraphJpaSpecificationExecutor;
import com.huijiewei.agile.app.admin.adapter.persistence.entity.Admin;
import com.huijiewei.agile.app.admin.adapter.persistence.entity.AdminAccessToken;
import com.huijiewei.agile.core.adapter.persistence.repository.IdentityJpaRepository;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Repository;
import java.util.Optional;
/**
* @author huijiewei
*/
@Repository
public interface AdminRepository extends
IdentityJpaRepository<Admin>,
EntityGraphJpaRepository<Admin, Integer>,
EntityGraphJpaSpecificationExecutor<Admin> {
/**
* 根据 accessToken 和 clientId 获取管理员
*
* @param accessToken accessToken
* @param clientId clientId
* @return 管理员
*/
@Override
default Optional<Admin> findByAccessToken(String accessToken, String clientId) {
Specification<Admin> adminSpecification = (root, query, criteriaBuilder) -> {
var subQuery = query.subquery(Integer.class);
var subRoot = subQuery.from(AdminAccessToken.class);
subQuery.select(subRoot.get("adminId"))
.where(
criteriaBuilder.equal(subRoot.get("accessToken"), accessToken),
criteriaBuilder.equal(subRoot.get("clientId"), clientId)
);
return criteriaBuilder.and(root.get("id").in(subQuery));
};
return this.findOne(adminSpecification, EntityGraphUtils.fromAttributePaths("adminGroup"));
}
/**
* 判断管理组 Id 是否存在
*
* @param adminGroupId 管理组 Id
* @return Boolean
*/
boolean existsByAdminGroupId(Integer adminGroupId);
}
|
package eapli.base.spm.application.processamento;
import eapli.base.gestaomensagens.dominio.Mensagem;
import eapli.base.gestaoordensproducao.domain.CodigoOrdemProducao;
import eapli.base.gestaoordensproducao.domain.DataFim;
import eapli.base.gestaoordensproducao.domain.EstadoOrdemProducao;
import eapli.base.gestaoordensproducao.domain.ExecucaoOrdemProducao;
import eapli.base.gestaoordensproducao.domain.OrdemProducao;
import eapli.base.spm.application.processamento.validacao.exceptions.OrdemProducaoInvalidaException;
import eapli.base.spm.application.processamento.validacao.exceptions.SPMException;
import java.util.Iterator;
public class S9 extends ProcessaMensagem {
public S9(Mensagem mensagem) throws SPMException {
super(mensagem);
}
public OrdemProducao ordemProducao() throws SPMException {
try {
return this.ordemProducaoRepository.ofIdentity(new CodigoOrdemProducao(campos[3])).get();
} catch (Exception ex) {
throw new OrdemProducaoInvalidaException();
}
}
//S9 -> Fim de Atividade
//S9 -> Máquina;TipoMsg;DataHora;OrdemProducao
//Nota : Só a primeira máquina conhece a ordem de producao.
@Override
public boolean processa() throws SPMException {
if(mensagem.obterOrdemProducao()==null) return false;
//execução ordem orid existe? | Inicio de atividade
Iterator<ExecucaoOrdemProducao> execucaoDaOrdensProducao = this.execOrdemProducaoRepository.execucaoDaOrdensProducao(mensagem.obterOrdemProducao()).iterator();
if(execucaoDaOrdensProducao.hasNext()) {
ExecucaoOrdemProducao execOrdProd = execucaoDaOrdensProducao.next();
//regista fim atividade máquina.
execOrdProd.registarFimAtividade(maquina(), buildCalendar());
if(execOrdProd.atividadeConcluida()) {
//calculos finais..
System.out.println("Ordem Produção " + execOrdProd.ordemProducao().identity() + " concluída na linha de produção [" + mensagem.obterLinhaProducao().identity() + "].");
//execucaoOrdemProd.
//******* Calcula desvios *******
execOrdProd.updateDesvios();
//Dá por concluido a ordem de producão
OrdemProducao ordProd = this.ordemProducaoRepository.ofIdentity(mensagem.obterOrdemProducao().identity()).get();
ordProd.updateEstadoOrdemProducao(EstadoOrdemProducao.CONCLUIDA);
ordProd.updateDataFim(new DataFim(stringData()));
this.ordemProducaoRepository.save(ordProd);
}
this.execOrdemProducaoRepository.save(execOrdProd);
}
return false;
}
}
|
package cn.kgc.tools;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateConverter implements Converter<String, Date> {
private String pattern=null;
public StringToDateConverter(String pattern) {
super();
this.pattern = pattern;
}
@Override
public Date convert(String arg0) {
Date date = null;
try {
date = new SimpleDateFormat(pattern).parse(arg0);
System.out.println("StringToDateConverter convert date ================================= > " + date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date;
}
}
|
/*
* 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.tserver.compaction;
public enum MajorCompactionReason {
// do not change the order, the order of this enum determines the order
// in which queued major compactions are executed
USER, CHOP, NORMAL, IDLE
}
|
package tech.jiangtao.backstage.mapper;
import java.util.List;
import tech.jiangtao.backstage.model.TigPairs;
/**
* @class: </br>
* @description: 自定义查询 </br>
* @creator: kevin </br>
* @email: jiangtao103cp@gmail.com </br>
* @date: 2017/3/29 上午10:06</br>
* @version: 0.0.1 </br>
**/
public interface TigPairsCustomMapper {
public long insertPairsReturnKeys(TigPairs pairs) throws Exception;
public TigPairs queryTigPairs(long uid) throws Exception;
public void updateTigPairs(TigPairs pairs) throws Exception;
public TigPairs queryTigPairsFromObject(TigPairs pairs) throws Exception;
public List<TigPairs> queryTigPairsListByUidAndRoster(List<Long> uids) throws Exception;
}
|
/*
* (C) Copyright IBM Corp. 2021
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.alvearie.imaging.ingestion.dimse;
import java.io.IOException;
import javax.enterprise.context.ApplicationScoped;
import org.dcm4che3.data.Attributes;
import org.dcm4che3.data.UID;
import org.dcm4che3.net.Association;
import org.dcm4che3.net.Commands;
import org.dcm4che3.net.Dimse;
import org.dcm4che3.net.Status;
import org.dcm4che3.net.pdu.PresentationContext;
import org.dcm4che3.net.service.DicomServiceException;
@ApplicationScoped
public class CEchoSCPImpl extends AbstractDicomService {
public CEchoSCPImpl() {
super(UID.Verification);
}
public CEchoSCPImpl(String... sopClasses) {
super(sopClasses);
}
@Override
public void onDimseRQ(Association as, PresentationContext pc, Dimse dimse, Attributes cmd, Attributes data)
throws IOException {
if (dimse != Dimse.C_ECHO_RQ)
throw new DicomServiceException(Status.UnrecognizedOperation);
as.tryWriteDimseRSP(pc, Commands.mkEchoRSP(cmd, Status.Success));
}
}
|
package com.plkpiotr.forum.repositories;
import com.plkpiotr.forum.entities.Answer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
public interface AnswerRepository extends JpaRepository<Answer, Long> {
@Modifying
@Transactional
@Query ("UPDATE Answer a SET a.useful = :bool WHERE a.id = :id")
void setUsefulForAnswer(@Param("bool") Boolean bool, @Param("id") Long id);
@Transactional
void deleteAnswerById(Long id);
Long countAnswersByUser_Id(Long id);
Long countAnswersByUser_IdAndUseful(Long user_id, boolean useful);
Long countAnswersByTopic_Id(Long topic_id);
List<Answer> findAnswerByUser_IdOrderByCreatedDateDesc(Long id);
List<Answer> findAnswerByUser_IdAndUsefulOrderByCreatedDateDesc(Long user_id, boolean useful);
List<Answer> findAnswerByTopic_Id(Long topic_id);
}
|
// Copyright 2017 Google 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.
/**
* Goal.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201705;
/**
* Defines the criteria a {@link LineItem} needs to satisfy to meet
* its delivery goal.
*/
public class Goal implements java.io.Serializable {
/* The type of the goal for the {@code LineItem}. It defines the
* period over which the goal
* for {@code LineItem} should be reached. */
private com.google.api.ads.dfp.axis.v201705.GoalType goalType;
/* The type of the goal unit for the {@code LineItem}. */
private com.google.api.ads.dfp.axis.v201705.UnitType unitType;
/* If this is a primary goal, it represents the number or percentage
* of impressions or clicks
* that will be reserved for the {@code LineItem}. If
* the line item is of type
* {@link LineItemType#SPONSORSHIP}, it represents the
* percentage of available impressions
* reserved. If the line item is of type {@link LineItemType#BULK}
* or
* {@link LineItemType#PRICE_PRIORITY}, it represents
* the number of remaining impressions
* reserved. If the line item is of type {@link LineItemType#NETWORK}
* or
* {@link LineItemType#HOUSE}, it represents the percentage
* of remaining impressions
* reserved.
*
* <p>If this is a secondary goal, it represents the
* number of impressions or conversions that
* the line item will stop serving at if reached. For
* valid line item types, see
* {@link LineItem#secondaryGoals}. */
private java.lang.Long units;
public Goal() {
}
public Goal(
com.google.api.ads.dfp.axis.v201705.GoalType goalType,
com.google.api.ads.dfp.axis.v201705.UnitType unitType,
java.lang.Long units) {
this.goalType = goalType;
this.unitType = unitType;
this.units = units;
}
@Override
public String toString() {
return com.google.common.base.MoreObjects.toStringHelper(this.getClass())
.omitNullValues()
.add("goalType", getGoalType())
.add("unitType", getUnitType())
.add("units", getUnits())
.toString();
}
/**
* Gets the goalType value for this Goal.
*
* @return goalType * The type of the goal for the {@code LineItem}. It defines the
* period over which the goal
* for {@code LineItem} should be reached.
*/
public com.google.api.ads.dfp.axis.v201705.GoalType getGoalType() {
return goalType;
}
/**
* Sets the goalType value for this Goal.
*
* @param goalType * The type of the goal for the {@code LineItem}. It defines the
* period over which the goal
* for {@code LineItem} should be reached.
*/
public void setGoalType(com.google.api.ads.dfp.axis.v201705.GoalType goalType) {
this.goalType = goalType;
}
/**
* Gets the unitType value for this Goal.
*
* @return unitType * The type of the goal unit for the {@code LineItem}.
*/
public com.google.api.ads.dfp.axis.v201705.UnitType getUnitType() {
return unitType;
}
/**
* Sets the unitType value for this Goal.
*
* @param unitType * The type of the goal unit for the {@code LineItem}.
*/
public void setUnitType(com.google.api.ads.dfp.axis.v201705.UnitType unitType) {
this.unitType = unitType;
}
/**
* Gets the units value for this Goal.
*
* @return units * If this is a primary goal, it represents the number or percentage
* of impressions or clicks
* that will be reserved for the {@code LineItem}. If
* the line item is of type
* {@link LineItemType#SPONSORSHIP}, it represents the
* percentage of available impressions
* reserved. If the line item is of type {@link LineItemType#BULK}
* or
* {@link LineItemType#PRICE_PRIORITY}, it represents
* the number of remaining impressions
* reserved. If the line item is of type {@link LineItemType#NETWORK}
* or
* {@link LineItemType#HOUSE}, it represents the percentage
* of remaining impressions
* reserved.
*
* <p>If this is a secondary goal, it represents the
* number of impressions or conversions that
* the line item will stop serving at if reached. For
* valid line item types, see
* {@link LineItem#secondaryGoals}.
*/
public java.lang.Long getUnits() {
return units;
}
/**
* Sets the units value for this Goal.
*
* @param units * If this is a primary goal, it represents the number or percentage
* of impressions or clicks
* that will be reserved for the {@code LineItem}. If
* the line item is of type
* {@link LineItemType#SPONSORSHIP}, it represents the
* percentage of available impressions
* reserved. If the line item is of type {@link LineItemType#BULK}
* or
* {@link LineItemType#PRICE_PRIORITY}, it represents
* the number of remaining impressions
* reserved. If the line item is of type {@link LineItemType#NETWORK}
* or
* {@link LineItemType#HOUSE}, it represents the percentage
* of remaining impressions
* reserved.
*
* <p>If this is a secondary goal, it represents the
* number of impressions or conversions that
* the line item will stop serving at if reached. For
* valid line item types, see
* {@link LineItem#secondaryGoals}.
*/
public void setUnits(java.lang.Long units) {
this.units = units;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof Goal)) return false;
Goal other = (Goal) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.goalType==null && other.getGoalType()==null) ||
(this.goalType!=null &&
this.goalType.equals(other.getGoalType()))) &&
((this.unitType==null && other.getUnitType()==null) ||
(this.unitType!=null &&
this.unitType.equals(other.getUnitType()))) &&
((this.units==null && other.getUnits()==null) ||
(this.units!=null &&
this.units.equals(other.getUnits())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getGoalType() != null) {
_hashCode += getGoalType().hashCode();
}
if (getUnitType() != null) {
_hashCode += getUnitType().hashCode();
}
if (getUnits() != null) {
_hashCode += getUnits().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(Goal.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201705", "Goal"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("goalType");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201705", "goalType"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201705", "GoalType"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("unitType");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201705", "unitType"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201705", "UnitType"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("units");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201705", "units"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
|
package com.devonfw.application.mtsj.general.dataaccess.base;
import org.h2.tools.Server;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.sql.SQLException;
@Configuration
public class H2Configuration {
@Bean(initMethod = "start", destroyMethod = "stop")
public Server inMemoryH2DatabaseServer() throws SQLException {
return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9090");
}
}
|
/*
* 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.taobao.weex.bridge;
import static com.taobao.weex.bridge.WXModuleManager.createDomModule;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.UiThread;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taobao.weex.Script;
import com.taobao.weex.WXEnvironment;
import com.taobao.weex.WXSDKEngine;
import com.taobao.weex.WXSDKInstance;
import com.taobao.weex.WXSDKManager;
import com.taobao.weex.adapter.IWXJSExceptionAdapter;
import com.taobao.weex.adapter.IWXJsFileLoaderAdapter;
import com.taobao.weex.adapter.IWXUserTrackAdapter;
import com.taobao.weex.common.IWXBridge;
import com.taobao.weex.common.IWXDebugConfig;
import com.taobao.weex.common.WXConfig;
import com.taobao.weex.common.WXErrorCode;
import com.taobao.weex.common.WXException;
import com.taobao.weex.common.WXJSBridgeMsgType;
import com.taobao.weex.common.WXJSExceptionInfo;
import com.taobao.weex.common.WXRefreshData;
import com.taobao.weex.common.WXRenderStrategy;
import com.taobao.weex.common.WXRuntimeException;
import com.taobao.weex.common.WXThread;
import com.taobao.weex.dom.CSSShorthand;
import com.taobao.weex.layout.ContentBoxMeasurement;
import com.taobao.weex.performance.WXInstanceApm;
import com.taobao.weex.ui.WXComponentRegistry;
import com.taobao.weex.ui.action.ActionReloadPage;
import com.taobao.weex.ui.action.BasicGraphicAction;
import com.taobao.weex.ui.action.GraphicActionAddElement;
import com.taobao.weex.ui.action.GraphicActionAddEvent;
import com.taobao.weex.ui.action.GraphicActionAppendTreeCreateFinish;
import com.taobao.weex.ui.action.GraphicActionCreateBody;
import com.taobao.weex.ui.action.GraphicActionCreateFinish;
import com.taobao.weex.ui.action.GraphicActionLayout;
import com.taobao.weex.ui.action.GraphicActionMoveElement;
import com.taobao.weex.ui.action.GraphicActionRefreshFinish;
import com.taobao.weex.ui.action.GraphicActionRemoveElement;
import com.taobao.weex.ui.action.GraphicActionRemoveEvent;
import com.taobao.weex.ui.action.GraphicActionRenderSuccess;
import com.taobao.weex.ui.action.GraphicActionUpdateAttr;
import com.taobao.weex.ui.action.GraphicActionUpdateStyle;
import com.taobao.weex.ui.action.GraphicPosition;
import com.taobao.weex.ui.action.GraphicSize;
import com.taobao.weex.ui.component.WXComponent;
import com.taobao.weex.ui.module.WXDomModule;
import com.taobao.weex.utils.WXExceptionUtils;
import com.taobao.weex.utils.WXFileUtils;
import com.taobao.weex.utils.WXJsonUtils;
import com.taobao.weex.utils.WXLogUtils;
import com.taobao.weex.utils.WXUtils;
import com.taobao.weex.utils.WXViewUtils;
import com.taobao.weex.utils.WXWsonJSONSwitch;
import com.taobao.weex.utils.batch.BactchExecutor;
import com.taobao.weex.utils.batch.Interceptor;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
/**
* Manager class for communication between JavaScript and Android.
* <ol>
* <li>
* Handle Android to JavaScript call, can be one of the following
* <ul>
* <li>{@link #createInstance(String, String, Map, String)}</li>
* <li>{@link #destroyInstance(String)}</li>
* <li>{@link #refreshInstance(String, WXRefreshData)}</li>
* <li>{@link #registerModules(Map)}</li>
* <li>{@link #registerComponents(List)}</li>
* <li>{@link #invokeCallJSBatch(Message)}</li>
* </ul>
* </li>
* <li>
* Handle JavaScript to Android call
* </li>
* <li>
* Handle next tick of message.
* </li>
* </ol>
*/
public class WXBridgeManager implements Callback, BactchExecutor {
private static Class clazz_debugProxy = null;
public static final String METHOD_CREATE_INSTANCE = "createInstance";
public static final String METHOD_DESTROY_INSTANCE = "destroyInstance";
public static final String METHOD_CALL_JS = "callJS";
public static final String METHOD_SET_TIMEOUT = "setTimeoutCallback";
public static final String METHOD_REGISTER_MODULES = "registerModules";
public static final String METHOD_REGISTER_COMPONENTS = "registerComponents";
public static final String METHOD_FIRE_EVENT = "fireEvent";
public static final String METHD_FIRE_EVENT_SYNC = "fireEventSync";
public static final String METHD_COMPONENT_HOOK_SYNC = "componentHook";
public static final String METHOD_CALLBACK = "callback";
public static final String METHOD_REFRESH_INSTANCE = "refreshInstance";
public static final String METHOD_FIRE_EVENT_ON_DATA_RENDER_NODE = "fireEventOnDataRenderNode";
public static final String METHOD_NOTIFY_TRIM_MEMORY = "notifyTrimMemory";
public static final String METHOD_NOTIFY_SERIALIZE_CODE_CACHE =
"notifySerializeCodeCache";
public static final String METHOD_CREATE_INSTANCE_CONTEXT = "createInstanceContext";
public static final String KEY_METHOD = "method";
public static final String KEY_ARGS = "args";
// args
public static final String COMPONENT = "component";
public static final String REF = "ref";
public static final String MODULE = "module";
public static final String METHOD = "method";
public static final String KEY_PARAMS = "params";
public static final String ARGS = "args";
public static final String OPTIONS = "options";
public static final String INITLOGFILE = "/jsserver_start.log";
private static final String NON_CALLBACK = "-1";
private static final String UNDEFINED = "undefined";
private static final String BUNDLE_TYPE = "bundleType";
private static final String RENDER_STRATEGY = "renderStrategy";
private static final int INIT_FRAMEWORK_OK = 1;
private static final int CRASHREINIT = 50;
static volatile WXBridgeManager mBridgeManager;
private static long LOW_MEM_VALUE = 120;
private volatile static int reInitCount = 1;
private static String crashUrl = null;
private static long lastCrashTime = 0;
private static String mRaxApi = null;
// private static String mRaxExtApi = null;
// add for clound setting, default value is true
// can use it to control weex sandbox
// if true will open weex sandbox for multi context
private volatile static boolean isSandBoxContext = true;
// add for cloud setting, default value is false.
// weexcore use single process or not
private static boolean isUseSingleProcess = false;
public enum BundType {
Vue,
Rax,
Others
};
private static final boolean BRIDGE_LOG_SWITCH = false;
/**
* Whether JS Framework(main.js) has been initialized.
*/
private volatile static boolean mInit = false;
private static String globalConfig = "none";
private static String GLOBAL_CONFIG_KEY = "global_switch_config";
private static Map<String, String> mWeexCoreEnvOptions = new HashMap<>();
/**
* package
**/
Handler mJSHandler;
/**
* next tick tasks, can set priority
*/
private WXHashMap<String, ArrayList<WXHashMap<String, Object>>> mNextTickTasks = new WXHashMap<>();
/**
* JSThread
*/
private WXThread mJSThread;
private IWXBridge mWXBridge;
private Object mWxDebugProxy;
private boolean mMock = false;
private List<Map<String, Object>> mRegisterComponentFailList = new ArrayList<>(8);
private List<Map<String, Object>> mRegisterModuleFailList = new ArrayList<>(8);
private List<String> mRegisterServiceFailList = new ArrayList<>(8);
private HashSet<String> mDestroyedInstanceId = new HashSet<>();
private StringBuilder mLodBuilder = new StringBuilder(50);
private Interceptor mInterceptor;
private WXParams mInitParams;
private WXBridgeManager() {
initWXBridge(WXEnvironment.sRemoteDebugMode);
mJSThread = new WXThread("WeexJSBridgeThread", this);
mJSHandler = mJSThread.getHandler();
}
public static WXBridgeManager getInstance() {
if (mBridgeManager == null) {
synchronized (WXBridgeManager.class) {
if (mBridgeManager == null) {
mBridgeManager = new WXBridgeManager();
}
}
}
return mBridgeManager;
}
public void setUseSingleProcess(final boolean flag) {
if (flag != isUseSingleProcess) {
isUseSingleProcess = flag;
// //we should reinit framework if js framework has been initialized
// if (isJSFrameworkInit()) {
// if (isJSThread()) {
// WXSDKEngine.reload();
// } else {
// post(new Runnable() {
// @Override
// public void run() {
// WXSDKEngine.reload();
// }
// });
// }
// }
}
}
public void setSandBoxContext(final boolean flag) {
if (flag != isSandBoxContext) {
isSandBoxContext = flag;
// use diff context reinit jsf
if (isJSThread()) {
setJSFrameworkInit(false);
WXModuleManager.resetAllModuleState();
String jsf = "";
if (!isSandBoxContext) {
jsf = WXFileUtils.loadAsset("main.js", WXEnvironment.getApplication());
} else {
jsf = WXFileUtils.loadAsset("weex-main-jsfm.js", WXEnvironment.getApplication());
}
initFramework(jsf);
WXServiceManager.reload();
WXModuleManager.reload();
WXComponentRegistry.reload();
} else {
post(new Runnable() {
@Override
public void run() {
setJSFrameworkInit(false);
WXModuleManager.resetAllModuleState();
String jsf = "";
if (!isSandBoxContext) {
jsf = WXFileUtils.loadAsset("main.js", WXEnvironment.getApplication());
} else {
jsf = WXFileUtils.loadAsset("weex-main-jsfm.js", WXEnvironment.getApplication());
}
initFramework(jsf);
WXServiceManager.reload();
WXModuleManager.reload();
WXComponentRegistry.reload();
}
}, null);
}
}
}
// setJSFrameworkInit and isJSFrameworkInit may use on diff thread
// use volatile
private boolean isJSFrameworkInit() {
return mInit;
}
private void setJSFrameworkInit(boolean init) {
mInit = init;
if (init == true) {
onJsFrameWorkInitSuccees();
}
}
private void initWXBridge(boolean remoteDebug) {
if (remoteDebug && WXEnvironment.isApkDebugable()) {
WXEnvironment.sDebugServerConnectable = true;
}
if (WXEnvironment.sDebugServerConnectable && (WXEnvironment.isApkDebugable() || WXEnvironment.sForceEnableDevTool)) {
if (WXEnvironment.getApplication() != null) {
try {
if (clazz_debugProxy == null) {
clazz_debugProxy = Class.forName("com.taobao.weex.devtools.debug.DebugServerProxy");
}
if (clazz_debugProxy != null) {
Constructor constructor = clazz_debugProxy.getConstructor(Context.class, IWXDebugConfig.class);
if (constructor != null) {
mWxDebugProxy = constructor.newInstance(WXEnvironment.getApplication(),
new IWXDebugConfig() {
@Override
public WXBridgeManager getWXJSManager() {
return WXBridgeManager.this;
}
@Override
public WXDebugJsBridge getWXDebugJsBridge() {
return new WXDebugJsBridge();
}
});
if (mWxDebugProxy != null) {
Method method_start = clazz_debugProxy.getMethod("start");
if (method_start != null) {
method_start.invoke(mWxDebugProxy);
}
}
}
}
} catch (Throwable e) {
//Ignore, It will throw Exception on Release environment
}
WXServiceManager.execAllCacheJsService();
} else {
WXLogUtils.e("WXBridgeManager", "WXEnvironment.sApplication is null, skip init Inspector");
}
}
if (remoteDebug && mWxDebugProxy != null) {
try {
if (clazz_debugProxy == null ) {
clazz_debugProxy = Class.forName("com.taobao.weex.devtools.debug.DebugServerProxy");
}
if (clazz_debugProxy != null) {
Method method_getWXBridge = clazz_debugProxy.getMethod("getWXBridge");
if (method_getWXBridge != null) {
mWXBridge = (IWXBridge) method_getWXBridge.invoke(mWxDebugProxy);
}
}
} catch (Throwable e) {
//Ignore, It will throw Exception on Release environment
}
} else {
mWXBridge = new WXBridge();
}
}
public void stopRemoteDebug() {
if (mWxDebugProxy != null) {
try {
if (clazz_debugProxy == null) {
clazz_debugProxy = Class.forName("com.taobao.weex.devtools.debug.DebugServerProxy");
}
if (clazz_debugProxy != null) {
Method method_stop = clazz_debugProxy.getMethod("stop", boolean.class);
if (method_stop != null) {
method_stop.invoke(mWxDebugProxy, true);
}
}
} catch (Throwable e) {
//Ignore, It will throw Exception on Release environment
}
}
}
public Object callModuleMethod(String instanceId, String moduleStr, String methodStr, JSONArray args) {
return callModuleMethod(instanceId, moduleStr, methodStr, args, null);
}
public Object callModuleMethod(String instanceId, String moduleStr, String methodStr, JSONArray args, JSONObject options) {
WXSDKInstance wxsdkInstance = WXSDKManager.getInstance()
.getSDKInstance(instanceId);
if (wxsdkInstance == null) {
return null;
}
if (wxsdkInstance.isNeedValidate()
&& WXSDKManager.getInstance().getValidateProcessor() != null) {
WXValidateProcessor.WXModuleValidateResult validateResult = WXSDKManager
.getInstance().getValidateProcessor()
.onModuleValidate(wxsdkInstance, moduleStr, methodStr, args, options);
if (validateResult == null) {
return null;
}
if (validateResult.isSuccess) {
return WXModuleManager.callModuleMethod(instanceId, moduleStr, methodStr,
args);
} else {
JSONObject validateInfo = validateResult.validateInfo;
if (validateInfo != null) {
WXLogUtils.e("[WXBridgeManager] module validate fail. >>> " + validateInfo.toJSONString());
}
return validateInfo;
}
}
try {
return WXModuleManager.callModuleMethod(instanceId, moduleStr, methodStr, args);
}catch(NumberFormatException e){
ArrayMap<String, String> ext = new ArrayMap<>();
ext.put("moduleName", moduleStr);
ext.put("methodName", methodStr);
ext.put("args", args.toJSONString());
WXLogUtils.e("[WXBridgeManager] callNative : numberFormatException when parsing string to numbers in args", ext.toString());
return null;
}
}
/**
* Model switch. For now, debug model and release model are supported
*/
public void restart() {
setJSFrameworkInit(false);
WXModuleManager.resetAllModuleState();
initWXBridge(WXEnvironment.sRemoteDebugMode);
mWXBridge.resetWXBridge(WXEnvironment.sRemoteDebugMode);
}
/**
* Set current Instance
*
* @param instanceId {@link WXSDKInstance#mInstanceId}
*/
public synchronized void setStackTopInstance(final String instanceId) {
post(new Runnable() {
@Override
public void run() {
mNextTickTasks.setStackTopInstance(instanceId);
}
}, instanceId);
}
@Override
public void post(Runnable r) {
if (mInterceptor != null && mInterceptor.take(r)) {
//task is token by the interceptor
return;
}
if (mJSHandler == null) {
return;
}
mJSHandler.post(WXThread.secure(r));
}
@Override
public void setInterceptor(Interceptor interceptor) {
mInterceptor = interceptor;
}
public void post(Runnable r, Object token) {
if (mJSHandler == null) {
return;
}
Message m = Message.obtain(mJSHandler, WXThread.secure(r));
m.obj = token;
m.sendToTarget();
}
public void postDelay(Runnable r,long delayMillis){
if (mJSHandler == null) {
return;
}
mJSHandler.postDelayed(WXThread.secure(r),delayMillis);
}
void setTimeout(String callbackId, String time) {
Message message = Message.obtain();
message.what = WXJSBridgeMsgType.SET_TIMEOUT;
TimerInfo timerInfo = new TimerInfo();
timerInfo.callbackId = callbackId;
timerInfo.time = (long) Float.parseFloat(time);
message.obj = timerInfo;
mJSHandler.sendMessageDelayed(message, timerInfo.time);
}
public void sendMessageDelayed(Message message, long delayMillis) {
if (message == null || mJSHandler == null || mJSThread == null
|| !mJSThread.isWXThreadAlive() || mJSThread.getLooper() == null) {
return;
}
mJSHandler.sendMessageDelayed(message, delayMillis);
}
public void removeMessage(int what, Object obj) {
if (mJSHandler == null || mJSThread == null
|| !mJSThread.isWXThreadAlive() || mJSThread.getLooper() == null) {
return;
}
mJSHandler.removeMessages(what, obj);
}
public Object callNativeModule(String instanceId, String module, String method, JSONArray arguments, Object options) {
if (TextUtils.isEmpty(instanceId) || TextUtils.isEmpty(module) || TextUtils.isEmpty(method)) {
WXLogUtils.d("[WXBridgeManager] call callNativeModule arguments is null");
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_RENDER_ERR_BRIDGE_ARG_NULL, "callNativeModule",
"arguments is empty, INSTANCE_RENDERING_ERROR will be set", null);
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
if (WXEnvironment.isApkDebugable() && BRIDGE_LOG_SWITCH) {
mLodBuilder.append("[WXBridgeManager] callNativeModule >>>> instanceId:").append(instanceId)
.append(", module:").append(module).append(", method:").append(method).append(", arguments:").append(arguments);
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
}
try {
if (WXDomModule.WXDOM.equals(module)) {
WXDomModule dom = WXModuleManager.getDomModule(instanceId);
return dom.callDomMethod(method, arguments);
} else {
return callModuleMethod(instanceId, module,
method, arguments);
}
} catch (Exception e) {
String err = "[WXBridgeManager] callNative exception: " + WXLogUtils.getStackTrace(e);
WXLogUtils.e(err);
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_BRIDGE, "callNativeModule",
err, null);
}
return null;
}
public Object callNativeModule(String instanceId, String module, String method, JSONArray arguments, JSONObject options) {
if (TextUtils.isEmpty(instanceId) || TextUtils.isEmpty(module) || TextUtils.isEmpty(method)) {
WXLogUtils.d("[WXBridgeManager] call callNativeModule arguments is null");
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_RENDER_ERR_BRIDGE_ARG_NULL, "callNativeModule",
"arguments is empty, INSTANCE_RENDERING_ERROR will be set", null);
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
if (WXEnvironment.isApkDebugable() && BRIDGE_LOG_SWITCH) {
mLodBuilder.append("[WXBridgeManager] callNativeModule >>>> instanceId:").append(instanceId)
.append(", module:").append(module).append(", method:").append(method).append(", arguments:").append(arguments);
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
}
try {
if (WXDomModule.WXDOM.equals(module)) {
WXDomModule dom = WXModuleManager.getDomModule(instanceId);
if(dom != null){
return dom.callDomMethod(method, arguments);
} else {
createDomModule(WXSDKManager.getInstance().getSDKInstance(instanceId));
}
} else {
return callModuleMethod(instanceId, module,
method, arguments, options);
}
} catch (Exception e) {
String err = "[WXBridgeManager] callNativeModule exception: " + WXLogUtils.getStackTrace(e);
WXLogUtils.e(err);
}
return null;
}
public Object callNativeComponent(String instanceId, String componentRef, String method, JSONArray arguments, Object options) {
if (TextUtils.isEmpty(instanceId) || TextUtils.isEmpty(componentRef) || TextUtils.isEmpty(method)) {
WXLogUtils.d("[WXBridgeManager] call callNativeComponent arguments is null");
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_RENDER_ERR_BRIDGE_ARG_NULL, "callNativeComponent",
"arguments is empty, INSTANCE_RENDERING_ERROR will be set", null);
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
if (WXEnvironment.isApkDebugable() && BRIDGE_LOG_SWITCH) {
mLodBuilder.append("[WXBridgeManager] callNativeComponent >>>> instanceId:").append(instanceId)
.append(", componentRef:").append(componentRef).append(", method:").append(method).append(", arguments:").append(arguments);
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
}
try {
WXDomModule dom = WXModuleManager.getDomModule(instanceId);
if (null != dom){
dom.invokeMethod(componentRef, method, arguments);
}else {
WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId);
if(null == instance || !instance.isDestroy()){
WXLogUtils.e("WXBridgeManager","callNativeComponent exception :null == dom ,method:"+method);
}
}
} catch (Exception e) {
WXLogUtils.e("[WXBridgeManager] callNativeComponent exception: ", e);
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_BRIDGE, "callNativeComponent",
WXLogUtils.getStackTrace(e), null);
}
return null;
}
/**
* Dispatch the native task to be executed.
*
* @param instanceId {@link WXSDKInstance#mInstanceId}
* @param tasks tasks to be executed
* @param callback next tick id
*/
public int callNative(String instanceId, JSONArray tasks, String callback) {
if (TextUtils.isEmpty(instanceId) || tasks == null) {
WXLogUtils.d("[WXBridgeManager] call callNative arguments is null");
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_RENDER_ERR_BRIDGE_ARG_NULL, "callNative",
"arguments is empty, INSTANCE_RENDERING_ERROR will be set", null);
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
if (WXEnvironment.isApkDebugable() && BRIDGE_LOG_SWITCH) {
mLodBuilder.append("[WXBridgeManager] callNative >>>> instanceId:").append(instanceId)
.append(", tasks:").append(tasks).append(", callback:").append(callback);
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
}
if (mDestroyedInstanceId != null && mDestroyedInstanceId.contains(instanceId)) {
return IWXBridge.DESTROY_INSTANCE;
}
long parseNanos = System.nanoTime();
JSONArray array = tasks;
parseNanos = System.nanoTime() - parseNanos;
if (null != array && array.size() > 0) {
int size = array.size();
try {
JSONObject task;
for (int i = 0; i < size; ++i) {
task = (JSONObject) array.get(i);
if (task != null && WXSDKManager.getInstance().getSDKInstance(instanceId) != null) {
Object module = task.get(MODULE);
if (module != null) {
if (WXDomModule.WXDOM.equals(module)) {
WXDomModule dom = WXModuleManager.getDomModule(instanceId);
dom.callDomMethod(task, parseNanos);
} else {
JSONObject optionObj = task.getJSONObject(OPTIONS);
callModuleMethod(instanceId, (String) module,
(String) task.get(METHOD), (JSONArray) task.get(ARGS), optionObj);
}
} else if (task.get(COMPONENT) != null) {
WXDomModule dom = WXModuleManager.getDomModule(instanceId);
dom.invokeMethod((String) task.get(REF), (String) task.get(METHOD), (JSONArray) task.get(ARGS));
} else {
throw new IllegalArgumentException("unknown callNative");
}
}
}
} catch (Exception e) {
WXLogUtils.e("[WXBridgeManager] callNative exception: ", e);
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_BRIDGE, "callNative",
WXLogUtils.getStackTrace(e) , null);
}
}
if (UNDEFINED.equals(callback) || NON_CALLBACK.equals(callback)) {
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
// get next tick
getNextTick(instanceId, callback);
return IWXBridge.INSTANCE_RENDERING;
}
// callUpdateFinish
public int callUpdateFinish(String instanceId, String callback) {
if (TextUtils.isEmpty(instanceId)) {
WXLogUtils.d("[WXBridgeManager] call callUpdateFinish arguments is null");
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_RENDER_ERR_BRIDGE_ARG_NULL, "callUpdateFinish",
"arguments is empty, INSTANCE_RENDERING_ERROR will be set", null);
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
if (WXEnvironment.isApkDebugable() && BRIDGE_LOG_SWITCH) {
mLodBuilder.append("[WXBridgeManager] callUpdateFinish >>>> instanceId:").append(instanceId)
.append(", callback:").append(callback);
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
}
if (mDestroyedInstanceId != null && mDestroyedInstanceId.contains(instanceId)) {
return IWXBridge.DESTROY_INSTANCE;
}
try {
if (WXSDKManager.getInstance().getSDKInstance(instanceId) != null) {
}
} catch (Exception e) {
WXLogUtils.e("[WXBridgeManager] callUpdateFinish exception: ", e);
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_BRIDGE, "callUpdateFinish",
WXLogUtils.getStackTrace(e), null);
}
if (callback == null || callback.isEmpty() || UNDEFINED.equals(callback) || NON_CALLBACK.equals(callback)) {
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
// get next tick
getNextTick(instanceId, callback);
return IWXBridge.INSTANCE_RENDERING;
}
// callRefreshFinish
public int callRefreshFinish(String instanceId, String callback) {
if (TextUtils.isEmpty(instanceId)) {
WXLogUtils.d("[WXBridgeManager] call callRefreshFinish arguments is null");
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_RENDER_ERR_BRIDGE_ARG_NULL, "callRefreshFinish",
"arguments is empty, INSTANCE_RENDERING_ERROR will be set", null);
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
if (WXEnvironment.isApkDebugable() && BRIDGE_LOG_SWITCH) {
mLodBuilder.append("[WXBridgeManager] callRefreshFinish >>>> instanceId:").append(instanceId)
.append(", callback:").append(callback);
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
}
if (mDestroyedInstanceId != null && mDestroyedInstanceId.contains(instanceId)) {
return IWXBridge.DESTROY_INSTANCE;
}
try {
WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId);
if (instance != null) {
GraphicActionRefreshFinish action = new GraphicActionRefreshFinish(instance);
WXSDKManager.getInstance().getWXRenderManager().postGraphicAction(instanceId, action);
}
} catch (Exception e) {
WXLogUtils.e("[WXBridgeManager] callRefreshFinish exception: ", e);
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_BRIDGE, "callRefreshFinish",
WXLogUtils.getStackTrace(e), null);
}
if (UNDEFINED.equals(callback) || NON_CALLBACK.equals(callback)) {
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
// get next tick
getNextTick(instanceId, callback);
return IWXBridge.INSTANCE_RENDERING;
}
public int callReportCrashReloadPage(String instanceId, String crashFile) {
boolean isCrashFileEmpty = TextUtils.isEmpty(crashFile);
try {
String url = null;
WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId);
if (instance != null) {
url = instance.getBundleUrl();
}
if(!isCrashFileEmpty) {
try {
if (WXEnvironment.getApplication() != null) {
crashFile = mInitParams.getCrashFilePath() + crashFile;
Log.d("jsengine", "callReportCrashReloadPage crashFile:" + crashFile);
}
} catch (Throwable e) {
e.printStackTrace();
}
callReportCrash(crashFile, instanceId, url);
} else {
commitJscCrashAlarmMonitor(IWXUserTrackAdapter.JS_BRIDGE, WXErrorCode.WX_ERR_RELOAD_PAGE, "reboot jsc Engine", instanceId, url);
}
if (reInitCount > CRASHREINIT) {
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
reInitCount++;
// reinit frame work
setJSFrameworkInit(false);
WXModuleManager.resetAllModuleState();
initScriptsFramework("");
if (mDestroyedInstanceId != null && mDestroyedInstanceId.contains(instanceId)) {
return IWXBridge.DESTROY_INSTANCE;
}
} catch (Exception e) {
WXLogUtils.e("[WXBridgeManager] callReportCrashReloadPage exception: ", e);
}
try {
if (WXSDKManager.getInstance().getSDKInstance(instanceId) != null) {
boolean reloadThisInstance = shouReloadCurrentInstance(
WXSDKManager.getInstance().getSDKInstance(instanceId).getBundleUrl());
new ActionReloadPage(instanceId, reloadThisInstance).executeAction();
}
} catch (Exception e) {
WXLogUtils.e("[WXBridgeManager] callReloadPage exception: ", e);
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_BRIDGE, "callReportCrashReloadPage",
WXLogUtils.getStackTrace(e), null);
}
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
public boolean shouReloadCurrentInstance(String aUrl) {
long time = System.currentTimeMillis();
if (crashUrl == null ||
(crashUrl != null && !crashUrl.equals(aUrl)) ||
((time - lastCrashTime) > 15000)) {
crashUrl = aUrl;
lastCrashTime = time;
return true;
}
lastCrashTime = time;
return false;
}
public void callReportCrash(String crashFile, final String instanceId, final String url) {
// statistic weex core process crash
Date date = new Date();
DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
String time = format.format(date);
final String origin_filename = crashFile + "." + time;
File oldfile = new File(crashFile);
File newfile = new File(origin_filename);
if (oldfile.exists()) {
oldfile.renameTo(newfile);
}
Thread t = new Thread(new Runnable() {
public void run() {
try {
File file = new File(origin_filename);
if (file.exists()) {
if (file.length() > 0) {
StringBuilder result = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(origin_filename));
String s = null;
// boolean foundStart = false;
while ((s = br.readLine()) != null) {
if ("".equals(s)) {
continue;
}
// if (("r0:").equals(s)) {
// break;
// }
result.append(s + "\n");
}
commitJscCrashAlarmMonitor(IWXUserTrackAdapter.JS_BRIDGE, WXErrorCode.WX_ERR_JSC_CRASH, result.toString(), instanceId, url);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
WXLogUtils.e("[WXBridgeManager] callReportCrash crash file is empty");
}
file.delete();
}
} catch (Throwable throwable) {
WXLogUtils.e("[WXBridgeManager] callReportCrash exception: ", throwable);
}
}
});
t.start();
}
private void getNextTick(final String instanceId, final String callback) {
addJSTask(METHOD_CALLBACK, instanceId, callback, "{}");
sendMessage(instanceId, WXJSBridgeMsgType.CALL_JS_BATCH);
}
private void getNextTick(final String instanceId) {
addJSTask(METHOD_CALLBACK, instanceId, "", "{}");
sendMessage(instanceId, WXJSBridgeMsgType.CALL_JS_BATCH);
}
public String syncExecJsOnInstanceWithResult(final String instanceId, final String js, final int type) {
final CountDownLatch waitLatch = new CountDownLatch(1);
EventResult callback = new EventResult(){
@Override
public void onCallback(Object result) {
super.onCallback(result);
waitLatch.countDown();
}
};
try{
execJSOnInstance(callback, instanceId, js, type);
waitLatch.await(100, TimeUnit.MILLISECONDS);
if (callback != null && callback.getResult() != null) {
return callback.getResult().toString();
}
return "";
}catch (Throwable e){
WXLogUtils.e("syncCallExecJsOnInstance", e);
return "";
}
}
/**
* ref, type, data, domChanges
* */
public EventResult syncCallJSEventWithResult(final String method, final String instanceId, final List<Object> params, final Object... args) {
final CountDownLatch waitLatch = new CountDownLatch(1);
EventResult callback = new EventResult(){
@Override
public void onCallback(Object result) {
super.onCallback(result);
waitLatch.countDown();
}
};
try{
asyncCallJSEventWithResult(callback, method, instanceId, params, args);
waitLatch.await(100, TimeUnit.MILLISECONDS);
return callback;
}catch (Exception e){
WXLogUtils.e("syncCallJSEventWithResult", e);
return callback;
}
}
public void asyncCallJSEventVoidResult(final String method, final String instanceId, final List<Object> params, final Object... args) {
post(new Runnable() {
@Override
public void run() {
try{
if (args == null || args.length == 0) {
return;
}
ArrayList<Object> argsList = new ArrayList<>();
for (Object arg : args) {
argsList.add(arg);
}
if (params != null) {
ArrayMap map = new ArrayMap(4);
map.put(KEY_PARAMS, params);
argsList.add(map);
}
WXHashMap<String, Object> task = new WXHashMap<>();
task.put(KEY_METHOD, method);
task.put(KEY_ARGS, argsList);
Object[] tasks = {task};
WXJSObject[] jsArgs = {
new WXJSObject(WXJSObject.String, instanceId),
WXWsonJSONSwitch.toWsonOrJsonWXJSObject(tasks)};
invokeExecJS(String.valueOf(instanceId), null, METHOD_CALL_JS, jsArgs, true);
jsArgs[0] = null;
jsArgs = null;
}catch (Exception e){
WXLogUtils.e("asyncCallJSEventVoidResult" , e);
}
}
});
}
/**
* aync call js event and return result in eventResult callback
* */
private void asyncCallJSEventWithResult(final EventResult eventCallback, final String method, final String instanceId, final List<Object> params, final Object... args) {
post(new Runnable() {
@Override
public void run() {
Object result = null;
try{
if (args == null || args.length == 0) {
return;
}
ArrayList<Object> argsList = new ArrayList<>();
for (Object arg : args) {
argsList.add(arg);
}
if (params != null) {
ArrayMap map = new ArrayMap(4);
map.put(KEY_PARAMS, params);
argsList.add(map);
}
WXHashMap<String, Object> task = new WXHashMap<>();
task.put(KEY_METHOD, method);
task.put(KEY_ARGS, argsList);
Object[] tasks = {task};
WXJSObject[] jsArgs = {
new WXJSObject(WXJSObject.String, instanceId),
WXWsonJSONSwitch.toWsonOrJsonWXJSObject(tasks)};
ResultCallback<byte[]> resultCallback = null;
if (eventCallback != null) {
resultCallback = new ResultCallback<byte[]>() {
@Override
public void onReceiveResult(byte[] result) {
JSONArray arrayResult = (JSONArray) WXWsonJSONSwitch.parseWsonOrJSON(result);
if(arrayResult != null && arrayResult.size() > 0){
eventCallback.onCallback(arrayResult.get(0));
}
}
};
}
invokeExecJSWithCallback(String.valueOf(instanceId), null, METHOD_CALL_JS,
jsArgs, resultCallback, true);
jsArgs[0] = null;
}catch (Exception e){
WXLogUtils.e("asyncCallJSEventWithResult" , e);
}
}
});
}
private void addJSEventTask(final String method, final String instanceId, final List<Object> params, final Object... args) {
post(new Runnable() {
@Override
public void run() {
if (args == null || args.length == 0) {
return;
}
ArrayList<Object> argsList = new ArrayList<>();
for (Object arg : args) {
argsList.add(arg);
}
if (params != null) {
ArrayMap map = new ArrayMap(4);
map.put(KEY_PARAMS, params);
argsList.add(map);
}
WXHashMap<String, Object> task = new WXHashMap<>();
task.put(KEY_METHOD, method);
task.put(KEY_ARGS, argsList);
if (mNextTickTasks.get(instanceId) == null) {
ArrayList<WXHashMap<String, Object>> list = new ArrayList<>();
list.add(task);
mNextTickTasks.put(instanceId, list);
} else {
mNextTickTasks.get(instanceId).add(task);
}
}
});
}
private void addJSTask(final String method, final String instanceId, final Object... args) {
addJSEventTask(method, instanceId, null, args);
}
private void sendMessage(String instanceId, int what) {
Message msg = Message.obtain(mJSHandler);
msg.obj = instanceId;
msg.what = what;
msg.sendToTarget();
}
/**
* Initialize JavaScript framework
*
* @param framework String representation of the framework to be init.
*/
public synchronized void initScriptsFramework(String framework) {
Message msg = mJSHandler.obtainMessage();
msg.obj = framework;
msg.what = WXJSBridgeMsgType.INIT_FRAMEWORK;
msg.setTarget(mJSHandler);
msg.sendToTarget();
}
@Deprecated
public void fireEvent(final String instanceId, final String ref,
final String type, final Map<String, Object> data) {
this.fireEvent(instanceId, ref, type, data, null);
}
/**
* Do not direct invoke this method in Components, use {@link WXSDKInstance#fireEvent(String, String, Map, Map)} instead.
*
* @param instanceId
* @param ref
* @param type
* @param data
* @param domChanges
*/
@Deprecated
public void fireEvent(final String instanceId, final String ref,
final String type, final Map<String, Object> data, final Map<String, Object> domChanges) {
fireEventOnNode(instanceId, ref, type, data, domChanges);
}
/**
* Notify the JavaScript about the event happened on Android
*/
public void fireEventOnNode(final String instanceId, final String ref,
final String type, final Map<String, Object> data, final Map<String, Object> domChanges) {
fireEventOnNode(instanceId, ref, type, data, domChanges, null, null);
}
/**
* Notify the JavaScript about the event happened on Android
*/
public void fireEventOnNode(final String instanceId, final String ref,
final String type, final Map<String, Object> data,
final Map<String, Object> domChanges, List<Object> params){
fireEventOnNode(instanceId, ref, type, data, domChanges, params, null);
}
public void fireEventOnNode(final String instanceId, final String ref,
final String type, final Map<String, Object> data,
final Map<String, Object> domChanges, List<Object> params, EventResult callback) {
if (TextUtils.isEmpty(instanceId) || TextUtils.isEmpty(ref)
|| TextUtils.isEmpty(type) || mJSHandler == null) {
return;
}
if (!checkMainThread()) {
throw new WXRuntimeException(
"fireEvent must be called by main thread");
}
WXSDKInstance instance = WXSDKManager.getInstance().getAllInstanceMap().get(instanceId);
if (instance != null && (instance.getRenderStrategy() == WXRenderStrategy.DATA_RENDER ||
instance.getRenderStrategy() == WXRenderStrategy.DATA_RENDER_BINARY)) {
fireEventOnDataRenderNode(instanceId, ref, type, data, domChanges);
} else {
if(callback == null) {
addJSEventTask(METHOD_FIRE_EVENT, instanceId, params, ref, type, data, domChanges);
sendMessage(instanceId, WXJSBridgeMsgType.CALL_JS_BATCH);
}else{
asyncCallJSEventWithResult(callback, METHD_FIRE_EVENT_SYNC, instanceId, params, ref, type, data, domChanges);
}
}
}
private void fireEventOnDataRenderNode(final String instanceId, final String ref,
final String type, final Map<String, Object> data, final Map<String, Object> domChanges) {
mJSHandler.postDelayed(WXThread.secure(new Runnable() {
@Override
public void run() {
try {
WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId);
long start = System.currentTimeMillis();
if (WXEnvironment.isApkDebugable()) {
WXLogUtils.d("fireEventOnDataRenderNode >>>> instanceId:" + instanceId
+ ", data:" + data);
}
if (mWXBridge instanceof WXBridge) {
((WXBridge) mWXBridge).fireEventOnDataRenderNode(instanceId, ref, type,
(data == null || data.isEmpty()) ? "{}" : JSON.toJSONString(data),
(domChanges == null || domChanges.isEmpty()) ? "{}" : JSON.toJSONString(domChanges));
}
WXLogUtils.renderPerformanceLog("fireEventOnDataRenderNode", System.currentTimeMillis() - start);
} catch (Throwable e) {
String err = "[WXBridgeManager] fireEventOnDataRenderNode " + WXLogUtils.getStackTrace(e);
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_BRIDGE, "fireEventOnDataRenderNode",
err, null);
WXLogUtils.e(err);
}
}
}), 0);
}
private boolean checkMainThread() {
return Looper.myLooper() == Looper.getMainLooper();
}
/**
* Invoke JavaScript callback. Use {@link JSCallback} instead.
*
* @see #callback(String, String, String)
*/
@Deprecated
public void callback(String instanceId, String callback, String data) {
callback(instanceId, callback, data, false);
}
/**
* Invoke JavaScript callback. Use {@link JSCallback} instead.
*/
@Deprecated
public void callback(final String instanceId, final String callback,
final Map<String, Object> data) {
callback(instanceId, callback, data, false);
}
/**
* Use {@link JSCallback} instead.
*
* @param instanceId Weex Instance Id
* @param callback callback referenece handle
* @param data callback data
* @param keepAlive if keep callback instance alive for later use
*/
@Deprecated
public void callback(final String instanceId, final String callback,
final Object data, boolean keepAlive) {
callbackJavascript(instanceId, callback, data, keepAlive);
}
/**
* Callback to Javascript function.
*
* @param instanceId Weex Instance Id
* @param callback callback referenece handle
* @param data callback data
* @param keepAlive if keep callback instance alive for later use
*/
void callbackJavascript(final String instanceId, final String callback,
final Object data, boolean keepAlive) {
if (TextUtils.isEmpty(instanceId) || TextUtils.isEmpty(callback)
|| mJSHandler == null) {
return;
}
addJSTask(METHOD_CALLBACK, instanceId, callback, data, keepAlive);
sendMessage(instanceId, WXJSBridgeMsgType.CALL_JS_BATCH);
}
/**
* Refresh instance
*/
public void refreshInstance(final String instanceId, final WXRefreshData jsonData) {
if (TextUtils.isEmpty(instanceId) || jsonData == null) {
return;
}
mJSHandler.postDelayed(WXThread.secure(new Runnable() {
@Override
public void run() {
invokeRefreshInstance(instanceId, jsonData);
}
}), 0);
}
private void invokeRefreshInstance(String instanceId, WXRefreshData refreshData) {
try {
WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId);
if (!isJSFrameworkInit()) {
if (instance != null) {
instance.onRenderError(
WXErrorCode.WX_DEGRAD_ERR_INSTANCE_CREATE_FAILED.getErrorCode(),
WXErrorCode.WX_DEGRAD_ERR_INSTANCE_CREATE_FAILED.getErrorMsg()
+ "invokeRefreshInstance FAILED for JSFrameworkInit FAILED, intance will invoke instance.onRenderError"
);
}
String err = "[WXBridgeManager] invokeRefreshInstance: framework.js uninitialized.";
WXLogUtils.e(err);
return;
}
long start = System.currentTimeMillis();
if (WXEnvironment.isApkDebugable()) {
WXLogUtils.d("refreshInstance >>>> instanceId:" + instanceId
+ ", data:" + refreshData.data + ", isDirty:" + refreshData.isDirty);
}
if (refreshData.isDirty) {
return;
}
WXJSObject instanceIdObj = new WXJSObject(WXJSObject.String,
instanceId);
WXJSObject dataObj = new WXJSObject(WXJSObject.JSON,
refreshData.data == null ? "{}" : refreshData.data);
WXJSObject[] args = {instanceIdObj, dataObj};
mWXBridge.refreshInstance(instanceId, null, METHOD_REFRESH_INSTANCE, args);
} catch (Throwable e) {
String err = "[WXBridgeManager] invokeRefreshInstance " + WXLogUtils.getStackTrace(e);
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_BRIDGE, "invokeRefreshInstance",
err, null);
WXLogUtils.e(err);
}
}
public void commitJscCrashAlarmMonitor(final String type, final WXErrorCode errorCode, String errMsg,
String instanceId, String url) {
if (TextUtils.isEmpty(type) || errorCode == null) {
return;
}
Log.d("ReportCrash", " commitJscCrashAlarmMonitor errMsg " + errMsg);
String method = "callReportCrash";
String exception = "weex core process crash and restart exception";
Map<String, String> extParams = new HashMap<String, String>();
extParams.put("jscCrashStack", errMsg);
IWXJSExceptionAdapter adapter = WXSDKManager.getInstance().getIWXJSExceptionAdapter();
if (adapter != null) {
WXJSExceptionInfo jsException = new WXJSExceptionInfo(instanceId, url, errorCode, method, exception, extParams);
adapter.onJSException(jsException);
// if (WXEnvironment.isApkDebugable()) {
WXLogUtils.e(jsException.toString());
// }
}
}
/**
* Create instance.
*/
public void createInstance(final String instanceId, final String template,
final Map<String, Object> options, final String data) {
createInstance(instanceId, new Script(template), options, data);
}
public void createInstance(final String instanceId, final Script template,
final Map<String, Object> options, final String data) {
final WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId);
if (instance == null) {
WXLogUtils.e("WXBridgeManager", "createInstance failed, SDKInstance does not exist");
return;
}
if (TextUtils.isEmpty(instanceId) || template == null || template.isEmpty() || mJSHandler == null) {
instance.onRenderError(
WXErrorCode.WX_DEGRAD_ERR_INSTANCE_CREATE_FAILED.getErrorCode(),
WXErrorCode.WX_DEGRAD_ERR_INSTANCE_CREATE_FAILED.getErrorMsg() +
" instanceId==" + instanceId + " template ==" + template + " mJSHandler== " + mJSHandler.toString()
);
return;
}
if (!isJSFrameworkInit() && reInitCount == 1 && !WXEnvironment.sDebugServerConnectable) {
instance.onRenderError(
WXErrorCode.WX_DEGRAD_ERR_INSTANCE_CREATE_FAILED.getErrorCode(),
WXErrorCode.WX_DEGRAD_ERR_INSTANCE_CREATE_FAILED.getErrorMsg() +
" isJSFrameworkInit==" + isJSFrameworkInit() + " reInitCount == 1" );
post(new Runnable() {
@Override
public void run() {
initFramework("");
}
}, instanceId);
return;
}
WXModuleManager.createDomModule(instance);
post(new Runnable() {
@Override
public void run() {
long start = System.currentTimeMillis();
instance.getApmForInstance().onStage(WXInstanceApm.KEY_PAGE_STAGES_LOAD_BUNDLE_START);
invokeCreateInstance(instance, template, options, data);
long end = System.currentTimeMillis();
instance.getWXPerformance().callCreateInstanceTime = end - start;
instance.getWXPerformance().communicateTime = instance.getWXPerformance().callCreateInstanceTime;
}
}, instanceId);
}
private void invokeCreateInstance(@NonNull WXSDKInstance instance, Script template,
Map<String, Object> options, String data) {
// add for sandbox, will delete on sandbox ok
initFramework("");
if (mMock) {
mock(instance.getInstanceId());
} else {
if (!isJSFrameworkInit()) {
String err = "[WXBridgeManager] invokeCreateInstance: framework.js uninitialized.";
instance.onRenderError(
WXErrorCode.WX_DEGRAD_ERR_INSTANCE_CREATE_FAILED.getErrorCode(),
WXErrorCode.WX_DEGRAD_ERR_INSTANCE_CREATE_FAILED.getErrorMsg()
);
WXLogUtils.e(err);
return;
}
WXModuleManager.registerWhenCreateInstance();
try {
BundType type = BundType.Others;
try {
long start = System.currentTimeMillis();
type = getBundleType(instance.getBundleUrl(), template.getContent());
if (WXEnvironment.isOpenDebugLog()) {
long end = System.currentTimeMillis();
WXLogUtils.e("end getBundleType type:" + type.toString() + " time:" + (end - start));
}
} catch (Throwable e) {
e.printStackTrace();
}
try {
if (options == null) {
options = new HashMap<>();
}
// on file there is { "framework": "Vue" } or others
if (options.get(BUNDLE_TYPE) == null) {
// may vue or Rax
if (type == BundType.Vue) {
options.put(BUNDLE_TYPE, "Vue");
} else if (type == BundType.Rax) {
options.put(BUNDLE_TYPE, "Rax");
} else {
options.put(BUNDLE_TYPE, "Others");
}
instance.getApmForInstance().addProperty(WXInstanceApm.KEY_PAGE_PROPERTIES_BUNDLE_TYPE, options.get(BUNDLE_TYPE));
}
if (options.get("env") == null) {
options.put("env", mInitParams.toMap());
}
} catch (Throwable e) {
e.printStackTrace();
}
instance.bundleType = type;
if (WXEnvironment.isApkDebugable() && BRIDGE_LOG_SWITCH) {
WXLogUtils.d("createInstance >>>> instanceId:" + instance.getInstanceId()
+ ", options:"
+ WXJsonUtils.fromObjectToJSONString(options)
+ ", data:" + data);
}
WXJSObject instanceIdObj = new WXJSObject(WXJSObject.String,
instance.getInstanceId());
WXJSObject instanceObj = new WXJSObject(WXJSObject.String,
template.getContent());
Object extraOption = null;
if(options != null && options.containsKey("extraOption")) {
extraOption = options.get("extraOption");
options.remove("extraOption");
}
WXJSObject extraOptionObj = new WXJSObject(WXJSObject.JSON,
extraOption == null ? "{}"
: WXJsonUtils.fromObjectToJSONString(extraOption));
WXJSObject optionsObj = new WXJSObject(WXJSObject.JSON,
options == null ? "{}"
: WXJsonUtils.fromObjectToJSONString(options));
optionsObj = optionObjConvert(isSandBoxContext, type, optionsObj);
WXJSObject dataObj = new WXJSObject(WXJSObject.JSON,
data == null ? "{}" : data);
WXJSObject apiObj;
if (type == BundType.Rax) {
if (mRaxApi == null) {
IWXJsFileLoaderAdapter iwxJsFileLoaderAdapter = WXSDKEngine.getIWXJsFileLoaderAdapter();
if(iwxJsFileLoaderAdapter != null) {
mRaxApi = iwxJsFileLoaderAdapter.loadRaxApi();
}
if(TextUtils.isEmpty(mRaxApi)) {
mRaxApi = WXFileUtils.loadAsset("weex-rax-api.js", WXEnvironment.getApplication());
}
}
apiObj = new WXJSObject(WXJSObject.String,
mRaxApi);
} else {
apiObj = new WXJSObject(WXJSObject.String,
"");
}
// When render strategy is data_render, put it into options. Others keep null.
WXJSObject renderStrategy = null;
if (instance.getRenderStrategy() == WXRenderStrategy.DATA_RENDER) {
renderStrategy = new WXJSObject(WXJSObject.String, WXRenderStrategy.DATA_RENDER.getFlag());
} else if (instance.getRenderStrategy() == WXRenderStrategy.DATA_RENDER_BINARY) {
renderStrategy = new WXJSObject(WXJSObject.String, WXRenderStrategy.DATA_RENDER_BINARY.getFlag());
// In DATA_RENDER_BINARY strategy script is binary
instanceObj.data = template.getBinary();
}
WXJSObject[] args = {instanceIdObj, instanceObj, optionsObj,
dataObj, apiObj, renderStrategy, extraOptionObj};
instance.setTemplate(template.getContent());
instance.getApmForInstance().onStage(WXInstanceApm.KEY_PAGE_STAGES_LOAD_BUNDLE_END);
// if { "framework": "Vue" } or { "framework": "Rax" } will use invokeCreateInstanceContext
// others will use invokeExecJS
if (!isSandBoxContext) {
invokeExecJS(instance.getInstanceId(), null, METHOD_CREATE_INSTANCE, args, false);
return;
}
if (type == BundType.Vue || type == BundType.Rax
|| instance.getRenderStrategy() == WXRenderStrategy.DATA_RENDER
|| instance.getRenderStrategy() == WXRenderStrategy.DATA_RENDER_BINARY) {
int ret = invokeCreateInstanceContext(instance.getInstanceId(), null, "createInstanceContext", args, false);
if(ret == 0) {
String err = "[WXBridgeManager] invokeCreateInstance : " + instance.getTemplateInfo();
instance.onRenderError(
WXErrorCode.WX_DEGRAD_ERR_INSTANCE_CREATE_FAILED.getErrorCode(),
WXErrorCode.WX_DEGRAD_ERR_INSTANCE_CREATE_FAILED.getErrorMsg() + err);
}
return;
} else {
invokeExecJS(instance.getInstanceId(), null, METHOD_CREATE_INSTANCE, args, false);
return;
}
} catch (Throwable e) {
String err = "[WXBridgeManager] invokeCreateInstance " + e.getCause()
+ instance.getTemplateInfo();
instance.onRenderError(
WXErrorCode.WX_DEGRAD_ERR_INSTANCE_CREATE_FAILED.getErrorCode(),
WXErrorCode.WX_DEGRAD_ERR_INSTANCE_CREATE_FAILED.getErrorMsg() + err);
WXLogUtils.e(err);
}
}
}
public WXJSObject optionObjConvert(boolean useSandBox, BundType type, WXJSObject opt) {
if (!useSandBox || type == BundType.Others) {
return opt;
}
try {
String data = opt.data.toString();
JSONObject obj = JSON.parseObject(data);
if (obj.getJSONObject("env") != null) {
JSONObject optEnv = obj.getJSONObject("env");
// obj.replace()
if (optEnv != null) {
JSONObject opts = optEnv.getJSONObject("options");
if (opts!= null) {
optEnv.remove("options");
Set<String> set = opts.keySet();
for(Iterator it = set.iterator(); it.hasNext();) {
String key = it.next().toString();
optEnv.put(key, opts.getString(key));
}
}
}
obj.remove("env");
obj.put("env", optEnv);
}
WXJSObject optionsObj = new WXJSObject(WXJSObject.JSON, obj.toString());
return optionsObj;
} catch (Throwable e) {
e.printStackTrace();
}
return opt;
}
/**
* check bundleType
* @param url
* @param temp
* @return
*/
public BundType getBundleType(String url, String temp) {
try {
if (url != null) {
Uri uri = Uri.parse(url);
String type = uri.getQueryParameter(BUNDLE_TYPE);
if ("Vue".equals(type) || "vue".equals(type)) {
return BundType.Vue;
} else if ("Rax".equals(type) || "rax".equals(type)) {
return BundType.Rax;
}
}
if (temp != null) {
final String FRAMEWORK="framework", VUE="vue", RAX="rax";
// Find the first line that starts with '//' and convert it to json
int bundleTypeStart = temp.indexOf("//");
int bundleTypeEnd = temp.indexOf("\n", bundleTypeStart);
JSONObject bundleType = JSONObject.parseObject(
temp.substring(bundleTypeStart+2, bundleTypeEnd));
String type = bundleType.getString(FRAMEWORK);
if(VUE.equalsIgnoreCase(type)){
return BundType.Vue;
}
else if(RAX.equalsIgnoreCase(type)){
return BundType.Rax;
}
else{
// '//{ "framework": "Vue"}' is not found.
String regEx = "(use)(\\s+)(weex:vue)";
Pattern pattern = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
if (pattern.matcher(temp).find()) {
return BundType.Vue;
}
regEx = "(use)(\\s+)(weex:rax)";
pattern = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
if (pattern.matcher(temp).find()) {
return BundType.Rax;
}
}
}
return BundType.Others;
} catch (Throwable e) {
e.printStackTrace();
return BundType.Others;
}
}
private void mock(String instanceId) {
}
public void destroyInstance(final String instanceId) {
if (mJSHandler == null
|| TextUtils.isEmpty(instanceId)) {
return;
}
if (mDestroyedInstanceId != null) {
mDestroyedInstanceId.add(instanceId);
}
// clear message with instanceId
mJSHandler.removeCallbacksAndMessages(instanceId);
post(new Runnable() {
@Override
public void run() {
removeTaskByInstance(instanceId);
invokeDestroyInstance(instanceId);
}
}, instanceId);
}
private void removeTaskByInstance(String instanceId) {
mNextTickTasks.removeFromMapAndStack(instanceId);
}
private void invokeDestroyInstance(String instanceId) {
try {
if (WXEnvironment.isApkDebugable() && BRIDGE_LOG_SWITCH) {
WXLogUtils.d("destroyInstance >>>> instanceId:" + instanceId);
}
WXJSObject instanceIdObj = new WXJSObject(WXJSObject.String,
instanceId);
WXJSObject[] args = {instanceIdObj};
if (isJSFrameworkInit()) {
invokeDestoryInstance(instanceId, null, METHOD_DESTROY_INSTANCE, args, true);
// invokeExecJS(instanceId, null, METHOD_DESTROY_INSTANCE, args);
}
} catch (Throwable e) {
String err = "[WXBridgeManager] invokeDestroyInstance " + e.getCause();
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_BRIDGE, "invokeDestroyInstance", err, null);
WXLogUtils.e(err);
}
}
@Override
public boolean handleMessage(Message msg) {
if (msg == null) {
return false;
}
int what = msg.what;
switch (what) {
case WXJSBridgeMsgType.INIT_FRAMEWORK:
invokeInitFramework(msg);
break;
case WXJSBridgeMsgType.CALL_JS_BATCH:
invokeCallJSBatch(msg);
break;
case WXJSBridgeMsgType.SET_TIMEOUT:
TimerInfo timerInfo = (TimerInfo) msg.obj;
if (timerInfo == null) {
break;
}
WXJSObject obj = new WXJSObject(WXJSObject.String, timerInfo.callbackId);
WXJSObject[] args = {obj};
invokeExecJS("", null, METHOD_SET_TIMEOUT, args);
break;
case WXJSBridgeMsgType.TAKE_HEAP_SNAPSHOT:
if (msg.obj != null) {
String filename = (String) msg.obj;
mWXBridge.takeHeapSnapshot(filename);
}
break;
default:
break;
}
return false;
}
private void invokeExecJS(String instanceId, String namespace, String function, WXJSObject[] args) {
invokeExecJS(instanceId, namespace, function, args, true);
}
public void invokeExecJS(String instanceId, String namespace, String function,
WXJSObject[] args, boolean logTaskDetail) {
if (WXEnvironment.isOpenDebugLog() && BRIDGE_LOG_SWITCH) {
mLodBuilder.append("callJS >>>> instanceId:").append(instanceId)
.append("function:").append(function);
if (logTaskDetail) {
mLodBuilder.append(" tasks:").append(argsToJSON(args));
}
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
}
final long start = System.currentTimeMillis();
mWXBridge.execJS(instanceId, namespace, function, args);
WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId);
if (null != instance){
long diff = System.currentTimeMillis()-start;
instance.getApmForInstance().updateFSDiffStats(WXInstanceApm.KEY_PAGE_STATS_FS_CALL_JS_NUM,1);
instance.getApmForInstance().updateFSDiffStats(WXInstanceApm.KEY_PAGE_STATS_FS_CALL_JS_TIME,diff);
instance.callJsTime(diff);
}
}
public int invokeCreateInstanceContext(String instanceId, String namespace, String function,
WXJSObject[] args, boolean logTaskDetail) {
WXLogUtils.d("invokeCreateInstanceContext instanceId:" + instanceId + " function:"
+ function + " isJSFrameworkInit:%d" + isJSFrameworkInit());
mLodBuilder.append("createInstanceContext >>>> instanceId:").append(instanceId)
.append("function:").append(function);
if (logTaskDetail)
mLodBuilder.append(" tasks:").append(WXJsonUtils.fromObjectToJSONString(args));
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
// }
return mWXBridge.createInstanceContext(instanceId, namespace, function, args);
}
public void invokeDestoryInstance(String instanceId, String namespace, String function,
WXJSObject[] args, boolean logTaskDetail) {
// if (WXEnvironment.isApkDebugable()) {
mLodBuilder.append("callJS >>>> instanceId:").append(instanceId)
.append("function:").append(function);
if (logTaskDetail)
mLodBuilder.append(" tasks:").append(WXJsonUtils.fromObjectToJSONString(args));
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
// }
mWXBridge.destoryInstance(instanceId, namespace, function, args);
}
private void execJSOnInstance(final EventResult eventCallback, final String instanceId, final String js, final int type) {
post(new Runnable() {
@Override
public void run() {
String ret = invokeExecJSOnInstance(instanceId, js, type);
eventCallback.onCallback(ret);
}
});
}
private String invokeExecJSOnInstance(String instanceId, String js, int type) {
// if (WXEnvironment.isApkDebugable()) {
mLodBuilder.append("execJSOnInstance >>>> instanceId:").append(instanceId);
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
// }
if (isJSFrameworkInit()) {
return mWXBridge.execJSOnInstance(instanceId, js, type);
}
return null;
}
private void invokeExecJSWithCallback(String instanceId, String namespace, String function,
WXJSObject[] args , ResultCallback callback, boolean logTaskDetail){
if (WXEnvironment.isOpenDebugLog() && BRIDGE_LOG_SWITCH) {
mLodBuilder.append("callJS >>>> instanceId:").append(instanceId)
.append("function:").append(function);
if(logTaskDetail) {
mLodBuilder.append(" tasks:").append(argsToJSON(args));
}
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
}
if (isJSFrameworkInit()) {
mWXBridge.execJSWithCallback(instanceId, namespace, function, args, callback);
}
}
public @NonNull static String argsToJSON(WXJSObject[] args) {
StringBuilder builder = new StringBuilder();
builder.append("[");
for(WXJSObject object : args){
builder.append(WXWsonJSONSwitch.fromObjectToJSONString(object));
builder.append(",");
}
builder.append("]");
return builder.toString();
}
private void invokeInitFramework(Message msg) {
String framework = "";
if (msg.obj != null) {
framework = (String) msg.obj;
}
if (WXUtils.getAvailMemory(WXEnvironment.getApplication()) > LOW_MEM_VALUE) {
initFramework(framework);
}
}
public static long sInitFrameWorkTimeOrigin;
public static StringBuilder sInitFrameWorkMsg = new StringBuilder();
private void initFramework(String framework) {
if (WXSDKEngine.isSoInitialized() && !isJSFrameworkInit()) {
sInitFrameWorkTimeOrigin = System.currentTimeMillis();
if (TextUtils.isEmpty(framework)) {
// if (WXEnvironment.isApkDebugable()) {
WXLogUtils.d("weex JS framework from assets");
// }
IWXJsFileLoaderAdapter wxJsFileLoaderAdapter = WXSDKEngine.getIWXJsFileLoaderAdapter();
if (!isSandBoxContext) {
if(wxJsFileLoaderAdapter != null) {
framework = wxJsFileLoaderAdapter.loadJsFramework();
}
if(TextUtils.isEmpty(framework)) {
framework = WXFileUtils.loadAsset("main.js", WXEnvironment.getApplication());
}
} else {
if(wxJsFileLoaderAdapter != null) {
framework = wxJsFileLoaderAdapter.loadJsFrameworkForSandBox();
}
if(TextUtils.isEmpty(framework)) {
framework = WXFileUtils.loadAsset("weex-main-jsfm.js", WXEnvironment.getApplication());
}
}
sInitFrameWorkMsg.append("| weex JS framework from assets, isSandBoxContext: ").append(isSandBoxContext);
}
if (TextUtils.isEmpty(framework)) {
setJSFrameworkInit(false);
sInitFrameWorkMsg.append("| framework isEmpty ");
WXExceptionUtils.commitCriticalExceptionRT(null, WXErrorCode.WX_ERR_JS_FRAMEWORK,
"initFramework", "framework is empty!! ", null);
return;
}
try {
if (WXSDKManager.getInstance().getWXStatisticsListener() != null) {
long start = System.currentTimeMillis();
WXSDKManager.getInstance().getWXStatisticsListener().onJsFrameworkStart();
WXEnvironment.sJSFMStartListenerTime = System.currentTimeMillis() - start;
try {
IWXUserTrackAdapter adapter = WXSDKManager.getInstance().getIWXUserTrackAdapter();
if (null != adapter){
Map<String,Serializable> params = new HashMap<>(1);
params.put("time",String.valueOf(WXEnvironment.sJSFMStartListenerTime));
adapter.commit(WXEnvironment.getApplication(),"sJSFMStartListener",IWXUserTrackAdapter.COUNTER,null,params);
}
}catch (Exception e){
e.printStackTrace();
}
}
long start = System.currentTimeMillis();
String crashFile = "";
try {
crashFile = WXEnvironment.getApplication().getApplicationContext().getCacheDir().getPath();
} catch (Exception e) {
e.printStackTrace();
}
boolean pieSupport = true;
try {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
pieSupport = false;
}
} catch (Exception e) {
e.printStackTrace();
}
sInitFrameWorkMsg.append(" | pieSupport:").append(pieSupport);
WXLogUtils.d("[WXBridgeManager] initFrameworkEnv crashFile:" + crashFile + " pieSupport:" + pieSupport);
// extends initFramework
if (mWXBridge.initFrameworkEnv(framework, assembleDefaultOptions(), crashFile, pieSupport) == INIT_FRAMEWORK_OK) {
WXEnvironment.sJSLibInitTime = System.currentTimeMillis() - start;
WXEnvironment.sSDKInitTime = System.currentTimeMillis() - WXEnvironment.sSDKInitStart;
setJSFrameworkInit(true);
if (WXSDKManager.getInstance().getWXStatisticsListener() != null) {
WXSDKManager.getInstance().getWXStatisticsListener().onJsFrameworkReady();
}
execRegisterFailTask();
WXEnvironment.JsFrameworkInit = true;
registerDomModule();
trackComponentAndModulesTime();
} else {
sInitFrameWorkMsg.append(" | ExecuteJavaScript fail, reInitCount").append(reInitCount);
if (reInitCount > 1) {
WXLogUtils.e("[WXBridgeManager] invokeReInitFramework ExecuteJavaScript fail");
} else {
WXLogUtils.e("[WXBridgeManager] invokeInitFramework ExecuteJavaScript fail");
}
}
} catch (Throwable e) {
sInitFrameWorkMsg.append(" | invokeInitFramework exception ").append(e.toString());
if (reInitCount > 1) {
WXLogUtils.e("[WXBridgeManager] invokeInitFramework ", e);
} else {
WXLogUtils.e("[WXBridgeManager] invokeInitFramework ", e);
}
}
}
}
private void trackComponentAndModulesTime() {
post(new Runnable() {
@Override
public void run() {
WXEnvironment.sComponentsAndModulesReadyTime = System.currentTimeMillis() - WXEnvironment.sSDKInitStart;
}
});
}
@SuppressWarnings("unchecked")
private void invokeCallJSBatch(Message message) {
if (mNextTickTasks.isEmpty() || !isJSFrameworkInit()) {
if (!isJSFrameworkInit()) {
WXLogUtils.e("[WXBridgeManager] invokeCallJSBatch: framework.js uninitialized!! message:" + message.toString());
}
return;
}
try {
Object instanceId = message.obj;
Object task = null;
Stack<String> instanceStack = mNextTickTasks.getInstanceStack();
int size = instanceStack.size();
for (int i = size - 1; i >= 0; i--) {
instanceId = instanceStack.get(i);
task = mNextTickTasks.remove(instanceId);
if (task != null && !((ArrayList) task).isEmpty()) {
break;
}
}
if (null != task){
task = ((ArrayList) task).toArray();
WXJSObject[] args = {
new WXJSObject(WXJSObject.String, instanceId),
WXWsonJSONSwitch.toWsonOrJsonWXJSObject(task)};
invokeExecJS(String.valueOf(instanceId), null, METHOD_CALL_JS, args);
}
} catch (Throwable e) {
WXLogUtils.e("WXBridgeManager", e);
String err = "invokeCallJSBatch#" + WXLogUtils.getStackTrace(e);
WXExceptionUtils.commitCriticalExceptionRT(null, WXErrorCode.WX_ERR_JS_FRAMEWORK,
"invokeCallJSBatch", err, null);
}
// If task is not empty, loop until it is empty
if (!mNextTickTasks.isEmpty()) {
mJSHandler.sendEmptyMessage(WXJSBridgeMsgType.CALL_JS_BATCH);
}
}
private WXParams assembleDefaultOptions() {
Map<String, String> config = WXEnvironment.getConfig();
WXParams wxParams = new WXParams();
wxParams.setPlatform(config.get(WXConfig.os));
wxParams.setCacheDir(config.get(WXConfig.cacheDir));
wxParams.setOsVersion(config.get(WXConfig.sysVersion));
wxParams.setAppVersion(config.get(WXConfig.appVersion));
wxParams.setWeexVersion(config.get(WXConfig.weexVersion));
wxParams.setDeviceModel(config.get(WXConfig.sysModel));
wxParams.setShouldInfoCollect(config.get("infoCollect"));
wxParams.setLogLevel(config.get(WXConfig.logLevel));
wxParams.setLayoutDirection(config.get(WXConfig.layoutDirection));
wxParams.setUseSingleProcess(isUseSingleProcess ? "true" : "false");
wxParams.setCrashFilePath(WXEnvironment.getCrashFilePath(WXEnvironment.getApplication().getApplicationContext()));
wxParams.setLibJssPath(WXEnvironment.getLibJssRealPath());
wxParams.setLibIcuPath(WXEnvironment.getLibJssIcuPath());
wxParams.setLibLdPath(WXEnvironment.getLibLdPath());
String libJScRealPath = WXEnvironment.getLibJScRealPath();
wxParams.setLibJscPath(TextUtils.isEmpty(libJScRealPath)? "" : new File(libJScRealPath).getParent());
String appName = config.get(WXConfig.appName);
if (!TextUtils.isEmpty(appName)) {
wxParams.setAppName(appName);
}
wxParams.setDeviceWidth(TextUtils.isEmpty(config.get("deviceWidth")) ? String.valueOf(WXViewUtils.getScreenWidth(WXEnvironment.sApplication)) : config.get("deviceWidth"));
wxParams.setDeviceHeight(TextUtils.isEmpty(config.get("deviceHeight")) ? String.valueOf(WXViewUtils.getScreenHeight(WXEnvironment.sApplication)) : config.get("deviceHeight"));
wxParams.setOptions(WXEnvironment.getCustomOptions());
wxParams.setNeedInitV8(WXSDKManager.getInstance().needInitV8());
mInitParams = wxParams;
return wxParams;
}
public WXParams getInitParams() {
return mInitParams;
}
private void execRegisterFailTask() {
if (mRegisterModuleFailList.size() > 0) {
List<Map<String, Object>> moduleReceiver = new ArrayList<>();
for (int i = 0, moduleCount = mRegisterModuleFailList.size(); i < moduleCount; ++i) {
invokeRegisterModules(mRegisterModuleFailList.get(i), moduleReceiver);
}
mRegisterModuleFailList.clear();
if (moduleReceiver.size() > 0) {
mRegisterModuleFailList.addAll(moduleReceiver);
}
}
if (mRegisterComponentFailList.size() > 0) {
List<Map<String, Object>> receiver = new ArrayList<>();
invokeRegisterComponents(mRegisterComponentFailList, receiver);
mRegisterComponentFailList.clear();
if (receiver.size() > 0) {
mRegisterComponentFailList.addAll(receiver);
}
}
if (mRegisterServiceFailList.size() > 0) {
List<String> receiver = new ArrayList<>();
for (String service : mRegisterServiceFailList) {
invokeExecJSService(service, receiver);
}
mRegisterServiceFailList.clear();
if (receiver.size() > 0) {
mRegisterServiceFailList.addAll(receiver);
}
}
}
/**
* Register Android module
*
* @param modules the format is like
* {'dom':['updateAttrs','updateStyle'],'event':['openUrl']}
*/
public void registerModules(final Map<String, Object> modules) {
if (modules != null && modules.size() != 0) {
if (isJSThread()) {
invokeRegisterModules(modules, mRegisterModuleFailList);
} else {
post(new Runnable() {
@Override
public void run() {
invokeRegisterModules(modules, mRegisterModuleFailList);
}
}, null);
}
}
}
/**
* Registered component
*/
public void registerComponents(final List<Map<String, Object>> components) {
if (mJSHandler == null || components == null
|| components.size() == 0) {
return;
}
Runnable runnable = new Runnable() {
@Override
public void run() {
invokeRegisterComponents(components, mRegisterComponentFailList);
}
};
if(isJSThread() && isJSFrameworkInit()){
runnable.run();
}else{
post(runnable, null);
}
}
public void execJSService(final String service) {
post(new Runnable() {
@Override
public void run() {
invokeExecJSService(service, mRegisterServiceFailList);
}
});
}
private void invokeExecJSService(String service, List<String> receiver) {
try {
if (!isJSFrameworkInit()) {
WXLogUtils.e("[WXBridgeManager] invoke execJSService: framework.js uninitialized.");
receiver.add(service);
return;
}
mWXBridge.execJSService(service);
} catch (Throwable e) {
WXLogUtils.e("[WXBridgeManager] invokeRegisterService:", e);
Map<String, String> data = new HashMap<String, String>();
data.put("inputParams",service + "||" + receiver.toString());
WXExceptionUtils.commitCriticalExceptionRT("invokeExecJSService",
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_JSSERVICE_EXECUTE,
"invokeExecJSService",
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_JSSERVICE_EXECUTE.getErrorMsg()
+ "[WXBridgeManager] invokeRegisterService:"
+ WXLogUtils.getStackTrace(e),
data);
}
}
public boolean isJSThread() {
return mJSThread != null && mJSThread.getId() == Thread.currentThread().getId();
}
private void invokeRegisterModules(Map<String, Object> modules, List<Map<String, Object>> failReceiver) {
if (modules == null || !isJSFrameworkInit()) {
if (!isJSFrameworkInit()) {
WXLogUtils.d("[WXinvokeRegisterModulesBridgeManager] invokeRegisterModules: framework.js uninitialized.");
}
failReceiver.add(modules);
return;
}
WXJSObject[] args = {WXWsonJSONSwitch.toWsonOrJsonWXJSObject(modules)};
String errorMsg = null;
try{
// TODO use a better way
if (mWXBridge instanceof WXBridge) {
((WXBridge) mWXBridge).registerModuleOnDataRenderNode(WXJsonUtils.fromObjectToJSONString(modules));
}
} catch (Throwable e){
WXLogUtils.e("Weex [data_render register err]", e);
}
try {
if(0 == mWXBridge.execJS("", null, METHOD_REGISTER_MODULES, args)) {
errorMsg = "execJS error";
}
try {
Iterator<String> iter = modules.keySet().iterator();
while (iter.hasNext()) {
String module = iter.next();
if (module != null) {
WXModuleManager.resetModuleState(module, true);
WXLogUtils.e("[WXBridgeManager]invokeRegisterModules METHOD_REGISTER_MODULES success module:" + module);
}
}
} catch (Throwable e) {
WXLogUtils.e("Weex [invokeRegisterModules]", e);
}
} catch (Throwable e) {
errorMsg = WXErrorCode.WX_KEY_EXCEPTION_INVOKE_REGISTER_MODULES.getErrorMsg() +
" \n " + e.getMessage() + modules.entrySet().toString();
}
if(!TextUtils.isEmpty(errorMsg)) {
WXLogUtils.e("[WXBridgeManager] invokeRegisterModules:", errorMsg);
WXExceptionUtils.commitCriticalExceptionRT(null,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_REGISTER_MODULES,
"invokeRegisterModules", errorMsg,
null );
}
}
private void invokeRegisterComponents(List<Map<String, Object>> components, List<Map<String, Object>> failReceiver) {
if (components == failReceiver) {
throw new RuntimeException("Fail receiver should not use source.");
}
if (!isJSFrameworkInit()) {
WXLogUtils.e("[WXBridgeManager] invokeRegisterComponents: framework.js uninitialized.");
for (Map<String, Object> comp : components) {
failReceiver.add(comp);
}
return;
}
if (components == null) {
return;
}
WXJSObject[] args = {WXWsonJSONSwitch.toWsonOrJsonWXJSObject(components)};
String errorMsg = null;
try {
if(0 == mWXBridge.execJS("", null, METHOD_REGISTER_COMPONENTS, args)) {
errorMsg = "execJS error";
}
} catch (Throwable e) {
errorMsg = WXErrorCode.WX_KEY_EXCEPTION_INVOKE_REGISTER_COMPONENT
+ args.toString()
+ WXLogUtils.getStackTrace(e);
}
if(!TextUtils.isEmpty(errorMsg)) {
WXLogUtils.e("[WXBridgeManager] invokeRegisterComponents ", errorMsg);
WXExceptionUtils.commitCriticalExceptionRT(null,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_REGISTER_COMPONENT,
METHOD_REGISTER_COMPONENTS, errorMsg,
null);
}
}
public void destroy() {
if (mJSThread != null) {
mJSThread.quit();
}
mBridgeManager = null;
if (mDestroyedInstanceId != null) {
mDestroyedInstanceId.clear();
}
}
/**
* Report JavaScript Exception
*/
public void reportJSException(String instanceId, String function,
String exception) {
WXLogUtils.e("reportJSException >>>> instanceId:" + instanceId
+ ", exception function:" + function + ", exception:"
+ exception);
WXSDKInstance instance = null;
WXErrorCode reportErrorCode = WXErrorCode.WX_ERR_JS_EXECUTE;
if (instanceId != null && (instance = WXSDKManager.getInstance().getSDKInstance(instanceId)) != null) {
instance.setHasException(true);
exception += "\n getTemplateInfo==" +instance.getTemplateInfo();//add network header info
if (METHOD_CREATE_INSTANCE.equals(function) || !instance.isContentMd5Match()) {
try {
if (isJSFrameworkInit() && (reInitCount > 1 && reInitCount < 10) && !instance.isNeedReLoad()) {
new ActionReloadPage(instanceId, true).executeAction();
instance.setNeedLoad(true);
return;
} else {
String errorMsg = new StringBuilder()
.append(WXErrorCode.WX_DEGRAD_ERR_INSTANCE_CREATE_FAILED.getErrorMsg())
.append(", reportJSException >>>> instanceId:").append(instanceId)
.append(", exception function:").append(function)
.append(", exception:").append(exception)
.append(", extInitTime:").append(System.currentTimeMillis()-WXBridgeManager.sInitFrameWorkTimeOrigin).append("ms")
.append(", extInitErrorMsg:").append(WXBridgeManager.sInitFrameWorkMsg.toString())
.toString();
instance.onRenderError(//DegradPassivity to H5
WXErrorCode.WX_DEGRAD_ERR_INSTANCE_CREATE_FAILED.getErrorCode(),
errorMsg
);
if (!WXEnvironment.sInAliWeex){
WXExceptionUtils.commitCriticalExceptionRT(instanceId,WXErrorCode.WX_RENDER_ERR_JS_CREATE_INSTANCE,function,exception,null);
}
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (METHOD_CREATE_INSTANCE.equals(function) && !instance.getApmForInstance().hasAddView){
reportErrorCode = WXErrorCode.WX_RENDER_ERR_JS_CREATE_INSTANCE;
}else if ( METHOD_CREATE_INSTANCE_CONTEXT.equals(function) && !instance.getApmForInstance().hasAddView){
reportErrorCode = WXErrorCode.WX_RENDER_ERR_JS_CREATE_INSTANCE_CONTEXT;
}
instance.onJSException(reportErrorCode.getErrorCode(), function, exception);
}
doReportJSException(instanceId,function,reportErrorCode,exception);
}
private void doReportJSException(String instanceId, String function,WXErrorCode reportCode, String exception){
WXSDKInstance instance = WXSDKManager.getInstance().getAllInstanceMap().get(instanceId);
IWXJSExceptionAdapter adapter = WXSDKManager.getInstance().getIWXJSExceptionAdapter();
if (adapter != null) {
String exceptionId = instanceId;
if (TextUtils.isEmpty(instanceId)) {
exceptionId = "instanceIdisNull";
}
if (instance == null) {
if (("initFramework").equals(function)) {
String exceptionExt = null;
try {
if (WXEnvironment.getApplication() != null) {
final String fileName = WXEnvironment.getApplication().getApplicationContext().getCacheDir().getPath() + INITLOGFILE;
try {
File file = new File(fileName);
if (file.exists()) {
if (file.length() > 0) {
StringBuilder result = new StringBuilder();
try {
InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8");
BufferedReader br = new BufferedReader(read);
String s = null;
while ((s = br.readLine()) != null) {
result.append(s + "\n");
}
exceptionExt = result.toString();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
file.delete();
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
} catch (Throwable e) {
e.printStackTrace();
}
exception += "\n" + exceptionExt;
WXLogUtils.e("reportJSException:" + exception);
}
}
WXExceptionUtils.commitCriticalExceptionRT(exceptionId, reportCode,
function,
reportCode.getErrorMsg() + exception,
null);
}
}
private void registerDomModule() throws WXException {
/** Tell Javascript Framework what methods you have. This is Required.**/
Map<String, Object> domMap = new HashMap<>();
domMap.put(WXDomModule.WXDOM, WXDomModule.METHODS);
registerModules(domMap);
}
//This method is deprecated because of performance issue.
@Deprecated
public void notifyTrimMemory() {
}
/**
* update js server global config, current support turn wson off
* by pass wson_off
* */
public static void updateGlobalConfig(String config) {
if(TextUtils.isEmpty(config)){
config = "none";
}
if(!TextUtils.equals(config, globalConfig)){
globalConfig = config;
WXEnvironment.addCustomOptions(GLOBAL_CONFIG_KEY, globalConfig);
Runnable runnable = new Runnable() {
@Override
public void run() {
if(mBridgeManager != null){
if(mBridgeManager.isJSFrameworkInit()){
if(mBridgeManager.mWXBridge instanceof WXBridge) {
final WXBridge bridge = (WXBridge) mBridgeManager.mWXBridge;
bridge.nativeUpdateGlobalConfig(globalConfig);
}
}
}
if(globalConfig.contains(WXWsonJSONSwitch.WSON_OFF)){
WXWsonJSONSwitch.USE_WSON = false;
}else{
WXWsonJSONSwitch.USE_WSON = true;
}
}
};
if(mBridgeManager != null && mBridgeManager.isJSFrameworkInit()){
mBridgeManager.post(runnable);
}else{
runnable.run();
}
}
}
public
@Nullable
Looper getJSLooper() {
Looper ret = null;
if (mJSThread != null) {
ret = mJSThread.getLooper();
}
return ret;
}
public void notifySerializeCodeCache() {
post(new Runnable() {
@Override
public void run() {
if (!isJSFrameworkInit())
return;
invokeExecJS("", null, METHOD_NOTIFY_SERIALIZE_CODE_CACHE, new WXJSObject[0]);
}
});
}
public void takeJSHeapSnapshot(String filename) {
Message msg = mJSHandler.obtainMessage();
msg.obj = filename;
msg.what = WXJSBridgeMsgType.TAKE_HEAP_SNAPSHOT;
msg.setTarget(mJSHandler);
msg.sendToTarget();
}
public static class TimerInfo {
public String callbackId;
public long time;
public String instanceId;
}
public int callCreateBody(String pageId, String componentType, String ref,
HashMap<String, String> styles, HashMap<String, String> attributes, HashSet<String> events,
float[] margins, float[] paddings, float[] borders) {
if (TextUtils.isEmpty(pageId) || TextUtils.isEmpty(componentType) || TextUtils.isEmpty(ref)) {
WXLogUtils.d("[WXBridgeManager] call callCreateBody arguments is null");
WXExceptionUtils.commitCriticalExceptionRT(pageId,
WXErrorCode.WX_RENDER_ERR_BRIDGE_ARG_NULL, "callCreateBody",
"arguments is empty, INSTANCE_RENDERING_ERROR will be set", null);
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
if (WXEnvironment.isApkDebugable() && BRIDGE_LOG_SWITCH) {
mLodBuilder.append("[WXBridgeManager] callCreateBody >>>> pageId:").append(pageId)
.append(", componentType:").append(componentType).append(", ref:").append(ref)
.append(", styles:").append(styles)
.append(", attributes:").append(attributes)
.append(", events:").append(events);
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
}
if (mDestroyedInstanceId != null && mDestroyedInstanceId.contains(pageId)) {
return IWXBridge.DESTROY_INSTANCE;
}
try {
WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(pageId);
if (instance != null) {
final BasicGraphicAction action = new GraphicActionCreateBody(instance, ref, componentType,
styles, attributes, events, margins, paddings, borders);
WXSDKManager.getInstance().getWXRenderManager().postGraphicAction(action.getPageId(), action);
}
} catch (Exception e) {
WXLogUtils.e("[WXBridgeManager] callCreateBody exception: ", e);
WXExceptionUtils.commitCriticalExceptionRT(pageId,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_BRIDGE, "callCreateBody",
WXLogUtils.getStackTrace(e), null);
}
return IWXBridge.INSTANCE_RENDERING;
}
public int callAddElement(String pageId, String componentType, String ref, int index, String parentRef,
HashMap<String, String> styles, HashMap<String, String> attributes, HashSet<String> events,
float[] margins, float[] paddings, float[] borders,boolean willLayout) {
if (TextUtils.isEmpty(pageId) || TextUtils.isEmpty(componentType) || TextUtils.isEmpty(ref)) {
if (WXEnvironment.isApkDebugable()){
WXLogUtils.d("[WXBridgeManager] call callAddElement arguments is null");
}
WXExceptionUtils.commitCriticalExceptionRT(pageId,
WXErrorCode.WX_RENDER_ERR_BRIDGE_ARG_NULL, "callAddElement",
"arguments is empty, INSTANCE_RENDERING_ERROR will be set", null);
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
if (WXEnvironment.isApkDebugable() && BRIDGE_LOG_SWITCH) {
mLodBuilder.append("[WXBridgeManager] callAddElement >>>> pageId:").append(pageId)
.append(", componentType:").append(componentType).append(", ref:").append(ref).append(", index:").append(index)
.append(", parentRef:").append(parentRef)
.append(", styles:").append(styles)
.append(", attributes:").append(attributes)
.append(", events:").append(events);
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
}
if (mDestroyedInstanceId != null && mDestroyedInstanceId.contains(pageId)) {
return IWXBridge.DESTROY_INSTANCE;
}
try {
WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(pageId);
if (instance != null) {
final GraphicActionAddElement action = new GraphicActionAddElement(instance, ref, componentType, parentRef, index,
styles, attributes, events, margins, paddings, borders);
if(willLayout) {
instance.addInActiveAddElementAction(ref, action);
}else{
WXSDKManager.getInstance().getWXRenderManager().postGraphicAction(pageId, action);
}
}
} catch (Exception e) {
WXLogUtils.e("[WXBridgeManager] callAddElement exception: ", e);
WXExceptionUtils.commitCriticalExceptionRT(pageId,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_BRIDGE, "callAddElement",
WXLogUtils.getStackTrace(e), null);
}
return IWXBridge.INSTANCE_RENDERING;
}
public int callRemoveElement(String instanceId, String ref) {
if (TextUtils.isEmpty(instanceId) || TextUtils.isEmpty(ref)) {
if (WXEnvironment.isApkDebugable()){
WXLogUtils.d("[WXBridgeManager] call callRemoveElement arguments is null");
}
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_RENDER_ERR_BRIDGE_ARG_NULL, "callRemoveElement",
"arguments is empty, INSTANCE_RENDERING_ERROR will be set", null);
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
if (WXEnvironment.isApkDebugable() && BRIDGE_LOG_SWITCH) {
mLodBuilder.append("[WXBridgeManager] callRemoveElement >>>> instanceId:").append(instanceId)
.append(", ref:").append(ref);
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
}
if (mDestroyedInstanceId != null && mDestroyedInstanceId.contains(instanceId)) {
return IWXBridge.DESTROY_INSTANCE;
}
try {
WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId);
if (instance != null) {
final BasicGraphicAction action = new GraphicActionRemoveElement(instance, ref);
if(instance.getInActiveAddElementAction(ref)!=null){
instance.removeInActiveAddElmentAction(ref);
}
else {
WXSDKManager.getInstance().getWXRenderManager()
.postGraphicAction(action.getPageId(), action);
}
}
} catch (Exception e) {
WXLogUtils.e("[WXBridgeManager] callRemoveElement exception: ", e);
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_BRIDGE, "callRemoveElement",
WXLogUtils.getStackTrace(e), null);
}
return IWXBridge.INSTANCE_RENDERING;
}
public int callMoveElement(String instanceId, String ref, String parentref, int index) {
if (TextUtils.isEmpty(instanceId) || TextUtils.isEmpty(ref) || TextUtils.isEmpty(parentref)) {
if (WXEnvironment.isApkDebugable()){
WXLogUtils.d("[WXBridgeManager] call callMoveElement arguments is null");
}
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_RENDER_ERR_BRIDGE_ARG_NULL, "callMoveElement",
"arguments is empty, INSTANCE_RENDERING_ERROR will be set", null);
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
if (WXEnvironment.isApkDebugable() && BRIDGE_LOG_SWITCH) {
mLodBuilder.append("[WXBridgeManager] callMoveElement >>>> instanceId:").append(instanceId)
.append(", parentref:").append(parentref)
.append(", index:").append(index)
.append(", ref:").append(ref);
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
}
if (mDestroyedInstanceId != null && mDestroyedInstanceId.contains(instanceId)) {
return IWXBridge.DESTROY_INSTANCE;
}
try {
WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId);
if (instance != null) {
final BasicGraphicAction action = new GraphicActionMoveElement(instance, ref, parentref, index);
WXSDKManager.getInstance().getWXRenderManager().postGraphicAction(action.getPageId(), action);
}
} catch (Exception e) {
WXLogUtils.e("[WXBridgeManager] callMoveElement exception: ", e);
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_BRIDGE, "callMoveElement",
WXLogUtils.getStackTrace(e), null);
}
return IWXBridge.INSTANCE_RENDERING;
}
public int callAddEvent(String instanceId, String ref, String event) {
if (TextUtils.isEmpty(instanceId) || TextUtils.isEmpty(ref) || TextUtils.isEmpty(event)) {
if (WXEnvironment.isApkDebugable()){
WXLogUtils.d("[WXBridgeManager] call callAddEvent arguments is null");
}
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_RENDER_ERR_BRIDGE_ARG_NULL, "callAddEvent",
"arguments is empty, INSTANCE_RENDERING_ERROR will be set", null);
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
if (WXEnvironment.isApkDebugable() && BRIDGE_LOG_SWITCH) {
mLodBuilder.append("[WXBridgeManager] callAddEvent >>>> instanceId:").append(instanceId)
.append(", ref:").append(ref)
.append(", event:").append(event);
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
}
if (mDestroyedInstanceId != null && mDestroyedInstanceId.contains(instanceId)) {
return IWXBridge.DESTROY_INSTANCE;
}
try {
WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId);
if (instance != null) {
new GraphicActionAddEvent(instance, ref, event).executeActionOnRender();
}
} catch (Exception e) {
WXLogUtils.e("[WXBridgeManager] callAddEvent exception: ", e);
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_BRIDGE, "callAddEvent",
WXLogUtils.getStackTrace(e), null);
}
// get next tick
getNextTick(instanceId);
return IWXBridge.INSTANCE_RENDERING;
}
public int callRemoveEvent(String instanceId, String ref, String event) {
if (TextUtils.isEmpty(instanceId) || TextUtils.isEmpty(ref) || TextUtils.isEmpty(event)) {
if (WXEnvironment.isApkDebugable()){
WXLogUtils.d("[WXBridgeManager] call callRemoveEvent arguments is null");
}
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_RENDER_ERR_BRIDGE_ARG_NULL, "callRemoveEvent",
"arguments is empty, INSTANCE_RENDERING_ERROR will be set", null);
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
if (WXEnvironment.isApkDebugable() && BRIDGE_LOG_SWITCH) {
mLodBuilder.append("[WXBridgeManager] callRemoveEvent >>>> instanceId:").append(instanceId)
.append(", ref:").append(ref)
.append(", event:").append(event);
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
}
if (mDestroyedInstanceId != null && mDestroyedInstanceId.contains(instanceId)) {
return IWXBridge.DESTROY_INSTANCE;
}
try {
WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId);
if (instance != null) {
new GraphicActionRemoveEvent(instance, ref, event).executeActionOnRender();
}
} catch (Exception e) {
WXLogUtils.e("[WXBridgeManager] callRemoveEvent exception: ", e);
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_BRIDGE, "callRemoveEvent",
WXLogUtils.getStackTrace(e), null);
}
// get next tick
getNextTick(instanceId);
return IWXBridge.INSTANCE_RENDERING;
}
public int callUpdateStyle(String instanceId, String ref, HashMap<String, Object> styles,
HashMap<String, String> paddings,
HashMap<String, String> margins,
HashMap<String, String> borders) {
if (TextUtils.isEmpty(instanceId) || TextUtils.isEmpty(ref)) {
if (WXEnvironment.isApkDebugable()){
WXLogUtils.d("[WXBridgeManager] call callUpdateStyle arguments is null");
}
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_RENDER_ERR_BRIDGE_ARG_NULL, "callUpdateStyle",
"arguments is empty, INSTANCE_RENDERING_ERROR will be set", null);
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
if (WXEnvironment.isApkDebugable() && BRIDGE_LOG_SWITCH) {
mLodBuilder.append("[WXBridgeManager] callUpdateStyle >>>> instanceId:").append(instanceId)
.append(", ref:").append(ref).append(", styles:").append(styles.toString())
.append(", paddings:").append(paddings.toString())
.append(", margins:").append(margins.toString())
.append(", borders:").append(borders.toString());
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
}
if (mDestroyedInstanceId != null && mDestroyedInstanceId.contains(instanceId)) {
return IWXBridge.DESTROY_INSTANCE;
}
try {
WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId);
if (instance != null) {
final BasicGraphicAction action = new GraphicActionUpdateStyle(instance, ref, styles, paddings, margins, borders);
WXSDKManager.getInstance().getWXRenderManager().postGraphicAction(action.getPageId(), action);
}
} catch (Exception e) {
WXLogUtils.e("[WXBridgeManager] callUpdateStyle exception: ", e);
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_BRIDGE, "callUpdateStyle",
WXLogUtils.getStackTrace(e), null);
}
return IWXBridge.INSTANCE_RENDERING;
}
public int callUpdateAttrs(String instanceId, String ref, HashMap<String, String> attrs) {
if (TextUtils.isEmpty(instanceId) || TextUtils.isEmpty(ref)) {
if (WXEnvironment.isApkDebugable()){
WXLogUtils.d("[WXBridgeManager] call callUpdateAttrs arguments is null");
}
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_RENDER_ERR_BRIDGE_ARG_NULL, "callUpdateAttrs",
"arguments is empty, INSTANCE_RENDERING_ERROR will be set", null);
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
if (WXEnvironment.isApkDebugable() && BRIDGE_LOG_SWITCH) {
mLodBuilder.append("[WXBridgeManager] callUpdateAttrs >>>> instanceId:").append(instanceId)
.append(", ref:").append(ref).append(", attrs:").append(attrs.toString());
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
}
if (mDestroyedInstanceId != null && mDestroyedInstanceId.contains(instanceId)) {
return IWXBridge.DESTROY_INSTANCE;
}
try {
WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId);
if (instance != null) {
final BasicGraphicAction action = new GraphicActionUpdateAttr(instance, ref, attrs);
WXSDKManager.getInstance().getWXRenderManager().postGraphicAction(action.getPageId(), action);
}
} catch (Exception e) {
WXLogUtils.e("[WXBridgeManager] callUpdateAttrs exception: ", e);
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_BRIDGE, "callUpdateAttrs",
WXLogUtils.getStackTrace(e), null);
}
return IWXBridge.INSTANCE_RENDERING;
}
public int callLayout(String pageId, String ref, int top, int bottom, int left, int right, int height, int width, boolean isRTL, int index) {
if (TextUtils.isEmpty(pageId) || TextUtils.isEmpty(ref)) {
if (WXEnvironment.isApkDebugable()){
WXLogUtils.d("[WXBridgeManager] call callLayout arguments is null");
}
WXExceptionUtils.commitCriticalExceptionRT(pageId,
WXErrorCode.WX_RENDER_ERR_BRIDGE_ARG_NULL, "callLayout",
"arguments is empty, INSTANCE_RENDERING_ERROR will be set", null);
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
if (WXEnvironment.isApkDebugable() && BRIDGE_LOG_SWITCH) {
mLodBuilder.append("[WXBridgeManager] callLayout >>>> instanceId:").append(pageId)
.append(", ref:").append(ref).append(", height:").append(height).append(", width:").append(width)
.append(", top:").append(top)
.append(", bottom:").append(bottom)
.append(", left:").append(left)
.append(", right:").append(right);
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
}
if (mDestroyedInstanceId != null && mDestroyedInstanceId.contains(pageId)) {
return IWXBridge.DESTROY_INSTANCE;
}
try {
WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(pageId);
if (instance != null) {
GraphicSize size = new GraphicSize(width, height);
GraphicPosition position = new GraphicPosition(left, top, right, bottom);
GraphicActionAddElement addAction = instance.getInActiveAddElementAction(ref);
if(addAction!=null) {
addAction.setRTL(isRTL);
addAction.setSize(size);
addAction.setPosition(position);
if(!TextUtils.equals(ref, WXComponent.ROOT)) {
addAction.setIndex(index);
}
WXSDKManager.getInstance().getWXRenderManager().postGraphicAction(pageId, addAction);
instance.removeInActiveAddElmentAction(ref);
}
else {
final BasicGraphicAction action = new GraphicActionLayout(instance, ref, position, size, isRTL);
WXSDKManager.getInstance().getWXRenderManager().postGraphicAction(action.getPageId(), action);
}
}
} catch (Exception e) {
WXLogUtils.e("[WXBridgeManager] callLayout exception: ", e);
WXExceptionUtils.commitCriticalExceptionRT(pageId,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_BRIDGE, "callLayout",
WXLogUtils.getStackTrace(e), null);
}
return IWXBridge.INSTANCE_RENDERING;
}
public int callAppendTreeCreateFinish(String instanceId, String ref) {
if (TextUtils.isEmpty(instanceId) || TextUtils.isEmpty(ref)) {
WXLogUtils.d("[WXBridgeManager] call callAppendTreeCreateFinish arguments is null");
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_RENDER_ERR_BRIDGE_ARG_NULL, "callAppendTreeCreateFinish",
"arguments is empty, INSTANCE_RENDERING_ERROR will be set", null);
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
if (WXEnvironment.isApkDebugable() && BRIDGE_LOG_SWITCH) {
mLodBuilder.append("[WXBridgeManager] callAppendTreeCreateFinish >>>> instanceId:").append(instanceId)
.append(", ref:").append(ref);
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
}
if (mDestroyedInstanceId != null && mDestroyedInstanceId.contains(instanceId)) {
return IWXBridge.DESTROY_INSTANCE;
}
try {
WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId);
GraphicActionAppendTreeCreateFinish action = new GraphicActionAppendTreeCreateFinish(instance, ref);
WXSDKManager.getInstance().getWXRenderManager().postGraphicAction(instanceId, action);
} catch (Exception e) {
WXLogUtils.e("[WXBridgeManager] callAppendTreeCreateFinish exception: ", e);
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_BRIDGE, "callAppendTreeCreateFinish",
WXLogUtils.getStackTrace(e), null);
}
return IWXBridge.INSTANCE_RENDERING;
}
public int callCreateFinish(String instanceId) {
if (TextUtils.isEmpty(instanceId)) {
WXLogUtils.d("[WXBridgeManager] call callCreateFinish arguments is null");
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_RENDER_ERR_BRIDGE_ARG_NULL, "callCreateFinish",
"arguments is empty, INSTANCE_RENDERING_ERROR will be set", null);
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
if (WXEnvironment.isApkDebugable() && BRIDGE_LOG_SWITCH) {
mLodBuilder.append("[WXBridgeManager] callCreateFinish >>>> instanceId:").append(instanceId);
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
}
if (mDestroyedInstanceId != null && mDestroyedInstanceId.contains(instanceId)) {
return IWXBridge.DESTROY_INSTANCE;
}
try {
long start = System.currentTimeMillis();
WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId);
if (instance != null) {
instance.firstScreenCreateInstanceTime(start);
GraphicActionCreateFinish action = new GraphicActionCreateFinish(instance);
WXSDKManager.getInstance().getWXRenderManager().postGraphicAction(instanceId, action);
}
} catch (Exception e) {
WXLogUtils.e("[WXBridgeManager] callCreateFinish exception: ", e);
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_BRIDGE, "callCreateFinish",
WXLogUtils.getStackTrace(e), null);
}
return IWXBridge.INSTANCE_RENDERING;
}
public int callRenderSuccess(String instanceId) {
if (TextUtils.isEmpty(instanceId)) {
WXLogUtils.d("[WXBridgeManager] call callRenderSuccess arguments is null");
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_RENDER_ERR_BRIDGE_ARG_NULL, "callRenderSuccess",
"arguments is empty, INSTANCE_RENDERING_ERROR will be set", null);
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
if (WXEnvironment.isApkDebugable() && BRIDGE_LOG_SWITCH) {
mLodBuilder.append("[WXBridgeManager] callRenderSuccess >>>> instanceId:").append(instanceId);
WXLogUtils.d(mLodBuilder.substring(0));
mLodBuilder.setLength(0);
}
if (mDestroyedInstanceId != null && mDestroyedInstanceId.contains(instanceId)) {
return IWXBridge.DESTROY_INSTANCE;
}
try {
WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId);
if (instance != null) {
GraphicActionRenderSuccess action = new GraphicActionRenderSuccess(instance);
WXSDKManager.getInstance().getWXRenderManager().postGraphicAction(instanceId, action);
}
} catch (Exception e) {
WXLogUtils.e("[WXBridgeManager] callRenderSuccess exception: ", e);
WXExceptionUtils.commitCriticalExceptionRT(instanceId,
WXErrorCode.WX_KEY_EXCEPTION_INVOKE_BRIDGE, "callRenderSuccess",
WXLogUtils.getStackTrace(e), null);
}
return IWXBridge.INSTANCE_RENDERING;
}
public ContentBoxMeasurement getMeasurementFunc(String instanceId, long renderObjectPtr) {
ContentBoxMeasurement contentBoxMeasurement = null;
WXSDKInstance instance = WXSDKManager.getInstance().getSDKInstance(instanceId);
if (instance != null) {
contentBoxMeasurement = instance.getContentBoxMeasurement(renderObjectPtr);
}
return contentBoxMeasurement;
}
public void bindMeasurementToRenderObject(long ptr){
if (isJSFrameworkInit()) {
mWXBridge.bindMeasurementToRenderObject(ptr);
}
}
/**
* Native: Layout
* @param instanceId
* @return
*/
@UiThread
public boolean notifyLayout(String instanceId) {
if (isJSFrameworkInit()) {
return mWXBridge.notifyLayout(instanceId);
}
return false;
}
@UiThread
public void forceLayout(String instanceId) {
if (isJSFrameworkInit()) {
mWXBridge.forceLayout(instanceId);
}
}
/**
* native: OnInstanceClose
* should be called on JSThread
* @param instanceId
*/
public void onInstanceClose(String instanceId) {
if (isJSFrameworkInit()) {
mWXBridge.onInstanceClose(instanceId);
}
}
/**
* native: SetDefaultHeightAndWidthIntoRootDom
* @param instanceId
* @param defaultWidth
* @param defaultHeight
*/
public void setDefaultRootSize(final String instanceId, final float defaultWidth, final float defaultHeight, final boolean isWidthWrapContent, final boolean isHeightWrapContent) {
if (isJSFrameworkInit()) {
mWXBridge.setDefaultHeightAndWidthIntoRootDom(instanceId, defaultWidth, defaultHeight, isWidthWrapContent, isHeightWrapContent);
}
}
public void setRenderContentWrapContentToCore(boolean wrap, final String instanceId) {
if (isJSFrameworkInit()) {
mWXBridge.setRenderContainerWrapContent(wrap, instanceId);
}
}
public void setStyleWidth(String instanceId, String ref, float value) {
if (isJSFrameworkInit()) {
mWXBridge.setStyleWidth(instanceId, ref, value);
}
}
public void setStyleHeight(String instanceId, String ref, float value) {
if (isJSFrameworkInit()) {
mWXBridge.setStyleHeight(instanceId, ref, value);
}
}
public long[] getFirstScreenRenderTime(String instanceId) {
if (isJSFrameworkInit()) {
return mWXBridge.getFirstScreenRenderTime(instanceId);
}
return new long[]{0, 0, 0};
}
public long[] getRenderFinishTime(String instanceId) {
if (isJSFrameworkInit()) {
return mWXBridge.getRenderFinishTime(instanceId);
}
return new long[]{0, 0, 0};
}
public void setMargin(String instanceId, String ref, CSSShorthand.EDGE edge, float value) {
if (isJSFrameworkInit()) {
mWXBridge.setMargin(instanceId, ref, edge, value);
}
}
public void setPadding(String instanceId, String ref, CSSShorthand.EDGE edge, float value) {
if (isJSFrameworkInit()) {
mWXBridge.setPadding(instanceId, ref, edge, value);
}
}
public void setPosition(String instanceId, String ref, CSSShorthand.EDGE edge, float value) {
if (isJSFrameworkInit()) {
mWXBridge.setPosition(instanceId, ref, edge, value);
}
}
public void markDirty(String instanceId, String ref, boolean dirty) {
if (isJSFrameworkInit()) {
mWXBridge.markDirty(instanceId, ref, dirty);
}
}
public int callHasTransitionPros(String instanceId, String ref, HashMap<String, String> styles) {
WXComponent component = WXSDKManager.getInstance().getWXRenderManager().getWXComponent(instanceId, ref);
if (null == component || null == component.getTransition() || null == component.getTransition().getProperties()) {
return IWXBridge.DESTROY_INSTANCE;
}
for(String property : component.getTransition().getProperties()){
if(styles.containsKey(property)){
return IWXBridge.INSTANCE_RENDERING;
}
}
return IWXBridge.INSTANCE_RENDERING_ERROR;
}
public void registerCoreEnv(String key, String value) {
if (isJSFrameworkInit())
mWXBridge.registerCoreEnv(key, value);
else
mWeexCoreEnvOptions.put(key, value);
}
private void onJsFrameWorkInitSuccees() {
for (Map.Entry<String, String> entry : mWeexCoreEnvOptions.entrySet()) {
mWXBridge.registerCoreEnv(entry.getKey(), entry.getValue());
}
mWeexCoreEnvOptions.clear();
}
}
|
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets 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 io.druid.sql.calcite.view;
import com.google.inject.Inject;
import io.druid.java.util.common.ISE;
import io.druid.sql.calcite.planner.PlannerFactory;
import org.apache.calcite.schema.TableMacro;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* View manager that stores all views in-process. Not meant for serious usage, since views are not saved nor
* are they shared across processes.
*/
public class InProcessViewManager implements ViewManager
{
private final ConcurrentMap<String, DruidViewMacro> views;
@Inject
public InProcessViewManager()
{
this.views = new ConcurrentHashMap<>();
}
public void createView(final PlannerFactory plannerFactory, final String viewName, final String viewSql)
{
final TableMacro oldValue = views.putIfAbsent(viewName, new DruidViewMacro(plannerFactory, viewSql));
if (oldValue != null) {
throw new ISE("View[%s] already exists", viewName);
}
}
public void alterView(final PlannerFactory plannerFactory, final String viewName, final String viewSql)
{
final TableMacro oldValue = views.replace(viewName, new DruidViewMacro(plannerFactory, viewSql));
if (oldValue != null) {
throw new ISE("View[%s] does not exist", viewName);
}
}
public void dropView(final String viewName)
{
final TableMacro oldValue = views.remove(viewName);
if (oldValue == null) {
throw new ISE("View[%s] does not exist", viewName);
}
}
@Override
public Map<String, DruidViewMacro> getViews()
{
return views;
}
}
|
/*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.cli;
import com.facebook.buck.core.cell.Cell;
import com.facebook.buck.core.config.BuckConfig;
import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.core.model.CanonicalCellName;
import com.facebook.buck.core.path.ForwardRelativePath;
import com.facebook.buck.parser.spec.BuildTargetMatcherTargetNodeParser;
import com.facebook.buck.parser.spec.TargetNodeSpec;
import com.facebook.buck.support.cli.args.BuckCellArg;
import com.facebook.buck.support.cli.config.AliasConfig;
import com.facebook.buck.support.cli.config.CliConfig;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Verify;
import com.google.common.collect.ImmutableSet;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
/**
* A helper wrapper over {@link BuildTargetMatcherTargetNodeParser} to normalize user input before
* parsing, resolve aliases and validate that base path exists
*/
public class CommandLineTargetNodeSpecParser {
private final String rootRelativePackage;
private final BuckConfig config;
private final BuildTargetMatcherTargetNodeParser parser;
private final boolean shouldRelativize;
public CommandLineTargetNodeSpecParser(
Cell rootCell,
Path absoluteClientWorkingDirectory,
BuckConfig config,
BuildTargetMatcherTargetNodeParser parser) {
this.rootRelativePackage = getRootRelativePackagePath(rootCell, absoluteClientWorkingDirectory);
this.config = config;
this.parser = parser;
this.shouldRelativize =
config.getView(CliConfig.class).getRelativizeTargetsToWorkingDirectory();
}
/**
* Get the package to use in build targets for a given path and cell
*
* <p>e.g. for a cell at "/foo/bar", and a path at "/foo/bar/baz/sub", "baz/sub" would be returned
*
* @param rootCell The cell to relativize to
* @param absolutePathUnderRootCell An absolute path underneath or equal to the {@code rootCell}'s
* root path
* @return The package path as a string, with '/' separating the path components, or empty if
* {@code absolutePathUnderRootCell} was equal to {@code rootCell}'s path
* @throws com.google.common.base.VerifyException if {@code absolutePathUnderRootCell} is not
* absolute, or isn't underneath {@code rootCell}
*/
static String getRootRelativePackagePath(Cell rootCell, Path absolutePathUnderRootCell) {
Verify.verify(
absolutePathUnderRootCell.isAbsolute(), "%s must be absolute", absolutePathUnderRootCell);
Verify.verify(
absolutePathUnderRootCell.startsWith(rootCell.getRoot()),
"%s must be under cell root %s",
absolutePathUnderRootCell,
rootCell.getRoot());
return Joiner.on("/")
.join(rootCell.getRoot().relativize(absolutePathUnderRootCell).normalize());
}
/**
* Prepends a package path to target strings from the command line that look like relative build
* targets.
*
* <p>Target strings of the following forms will be transformed (given the package "pre/fix":
*
* <p>foo/bar:baz -> pre/fix/foo/bar:baz foo:bar -> pre/fix/foo:bar foo -> pre/fix/foo :bar ->
* pre/fix:bar
*
* @param packagePath the package path to optionally prepend
* @param target the target string provided on the command line
* @return either a string prefixed with the package path, or the original target if a fully
* qualified target was specified.
*/
static String addPackagePathToRelativeBuildTarget(String packagePath, String target) {
if (!target.contains("//") && !packagePath.isEmpty()) {
String packageDelimiter = (target.startsWith(":") || target.isEmpty()) ? "" : "/";
return String.format("%s%s%s", packagePath, packageDelimiter, target);
}
return target;
}
@VisibleForTesting
protected String normalizeBuildTargetString(String target) {
if (shouldRelativize) {
target = addPackagePathToRelativeBuildTarget(rootRelativePackage, target);
}
// Check and save the cell name
BuckCellArg arg = BuckCellArg.of(target);
target = arg.getArg();
// Look up the section after the colon, if present, and strip it off.
int colonIndex = target.indexOf(':');
Optional<String> nameAfterColon = Optional.empty();
if (colonIndex != -1) {
nameAfterColon = Optional.of(target.substring(colonIndex + 1));
target = target.substring(0, colonIndex);
}
// Strip trailing slashes in the directory name part.
while (target.endsWith("/")) {
target = target.substring(0, target.length() - 1);
}
// If no colon was specified and we're not dealing with a trailing "...", we'll add in the
// missing colon and fill in the missing rule name with the basename of the directory.
if (!nameAfterColon.isPresent() && !target.endsWith("/...") && !target.equals("...")) {
int lastSlashIndex = target.lastIndexOf('/');
if (lastSlashIndex == -1) {
nameAfterColon = Optional.of(target);
} else {
nameAfterColon = Optional.of(target.substring(lastSlashIndex + 1));
}
}
// Now add in the name after the colon if there was one.
if (nameAfterColon.isPresent()) {
target += ":" + nameAfterColon.get();
}
return arg.getCellName().orElse("") + "//" + target;
}
/**
* Validates a {@code spec} and throws an exception for invalid ones.
*
* <p>Ideally validation should happen as part of spec creation and some of them actually happen,
* but others, especially those that require filesystem interactions, are too expensive to carry
* for every single build target.
*/
private void validateTargetSpec(TargetNodeSpec spec, String arg, Cell owningCell) {
CanonicalCellName cellName = spec.getBuildFileSpec().getCellRelativeBaseName().getCellName();
ForwardRelativePath basePath = spec.getBuildFileSpec().getCellRelativeBaseName().getPath();
Path basePathPath = basePath.toPath(owningCell.getFilesystem().getFileSystem());
Cell realCell = owningCell.getCellProvider().getCellByCanonicalCellName(cellName);
if (!realCell.getFilesystem().exists(basePathPath)) {
// If someone passes in bar:baz while in subdir foo, and foo/bar does not exist, BUT <root
// cell>/bar does, tell the user to fix their usage. We do not want to support too many
// extraneous build target patterns, so hard error, but at least try to help users along.
if (!rootRelativePackage.isEmpty() && owningCell.equals(realCell) && !arg.contains("//")) {
Path rootRelativePackagePath = Paths.get(rootRelativePackage);
if (basePathPath.startsWith(rootRelativePackagePath)
&& owningCell
.getFilesystem()
.exists(rootRelativePackagePath.relativize(basePathPath))) {
Path rootBasePath = rootRelativePackagePath.relativize(basePathPath);
String str =
"%s references a non-existent directory %s when run from %s\n"
+ "However, %s exists in your repository root (%s).\n"
+ "Non-absolute build targets are relative to your working directory.\n"
+ "Try either re-running your command the repository root, or re-running your "
+ " command with //%s instead of %s";
throw new HumanReadableException(
str,
arg,
basePath,
rootRelativePackage,
rootBasePath,
owningCell.getRoot(),
arg,
arg);
}
}
throw new HumanReadableException("%s references non-existent directory %s", arg, basePath);
}
}
/**
* Parse command line argument provided by user into a set of {@link TargetNodeSpec}s
*
* @param owningCell Cell that owns the resolution of a spec
* @param arg Unresolved command line argument, can be alias or target name or recursive spec
*/
public ImmutableSet<TargetNodeSpec> parse(Cell owningCell, String arg) {
ImmutableSet<String> resolvedArgs =
AliasConfig.from(config).getBuildTargetForAliasAsString(arg);
if (resolvedArgs.isEmpty()) {
resolvedArgs = ImmutableSet.of(arg);
}
ImmutableSet.Builder<TargetNodeSpec> specs = new ImmutableSet.Builder<>();
for (String resolvedArg : resolvedArgs) {
String buildTarget = normalizeBuildTargetString(resolvedArg);
TargetNodeSpec spec = parser.parse(owningCell.getCellPathResolver(), buildTarget);
validateTargetSpec(spec, resolvedArg, owningCell);
specs.add(spec);
}
return specs.build();
}
}
|
package com.graly.erp.inv.out.adjust.sell;
import org.apache.log4j.Logger;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.AuthorityToolItem;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.forms.widgets.Section;
import com.graly.erp.base.model.Constants;
import com.graly.erp.inv.model.MovementOut;
import com.graly.erp.inv.out.adjust.AdjustOutLineBlockDialog;
import com.graly.erp.inv.out.adjust.AdjustOutSection;
import com.graly.erp.inv.out.adjust.ByLotAdjustOutDialog;
import com.graly.erp.inv.out.adjust.ByLotAdjustOutSection;
import com.graly.erp.inv.receipt.NewReceiptDialog;
import com.graly.erp.inv.receipt.ReceiptSection;
import com.graly.erp.po.model.PurchaseOrder;
import com.graly.framework.activeentity.client.ADManager;
import com.graly.framework.activeentity.model.ADTable;
import com.graly.framework.base.entitymanager.editor.EntityTableManager;
import com.graly.framework.base.entitymanager.views.TableListManager;
import com.graly.framework.base.ui.util.Env;
import com.graly.framework.base.ui.util.Message;
import com.graly.framework.base.ui.util.SWTResourceCache;
import com.graly.framework.base.ui.util.UI;
import com.graly.framework.runtime.Framework;
public class SellAdjustSection extends AdjustOutSection{
private static final Logger logger = Logger.getLogger(SellAdjustSection.class);
protected ToolItem itemSellAll;
private ADTable adTable;
private static final String TABLE_NAME_SELL = "INVMovementOut";
protected TableListManager listTableManager;
int style = SWT.CHECK | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.HIDE_SELECTION;
public SellAdjustSection(EntityTableManager tableManager) {
super(tableManager);
// TODO Auto-generated constructor stub
}
@Override
protected void outByLotAdapter() {
SellAdjustDialog olbd = new SellAdjustDialog(UI.getActiveShell());
if(olbd.open() == Dialog.CANCEL) {
MovementOut out = ((ByLotAdjustOutSection)olbd.getLotMasterSection()).getMovementOut();
if(out != null && out.getObjectRrn() != null) {
this.selectedOut = out;
if(selectedOut != null && selectedOut.getObjectRrn() != null)
refreshAdd(selectedOut);
editAdapter();
}
}
}
@Override
public void createToolBar(Section section) {
ToolBar tBar = new ToolBar(section, SWT.FLAT | SWT.HORIZONTAL);
createToolItemSellAll(tBar);
createToolItemByLotOut(tBar);
new ToolItem(tBar, SWT.SEPARATOR);
//createToolItemNew(tBar);
createToolItemEditor(tBar);
new ToolItem(tBar, SWT.SEPARATOR);
createToolItemDelete(tBar);
new ToolItem(tBar, SWT.SEPARATOR);
createToolItemSearch(tBar);
createToolItemRefresh(tBar);
section.setTextClient(tBar);
}
protected void createToolItemSellAll(ToolBar tBar) {
itemSellAll = new AuthorityToolItem(tBar, SWT.PUSH, Constants.KEY_OOU_LOTOUT);
itemSellAll.setText(Message.getString("inv.adjust_sell"));
itemSellAll.setImage(SWTResourceCache.getImage("barcode"));
itemSellAll.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
allSellAdapter();
}
});
}
protected void allSellAdapter() {
String where = " docStatus='" + PurchaseOrder.STATUS_APPROVED +"'"+"AND docType='SOU'";
adTable = getADTableOfSellAdjust(TABLE_NAME_SELL);
listTableManager = new TableListManager(adTable);
SellAdjustInfoDialog poQueryDialog = new SellAdjustInfoDialog(listTableManager, null, where, style);
if (poQueryDialog.open() == Dialog.CANCEL) {
refreshSection();
}
refresh();
}
protected ADTable getADTableOfSellAdjust(String tableName) {
try {
ADManager entityManager = Framework.getService(ADManager.class);
adTable = entityManager.getADTable(0L, tableName);
adTable = entityManager.getADTableDeep(adTable.getObjectRrn());
return adTable;
} catch (Exception e) {
logger.error("SellAdjustSection : getADTableOfSellAdjust()", e);
}
return null;
}
}
|
package usuarios_factoryMethod;
/**
* @author kevin van Liebergen
*/
public class Alumno extends Usuario{
private String tipo;
public Alumno(){
tipo = "alumno";
}
public String getTipo() {
return tipo;
}
@Override
public String toString() {
return "\nNIF: "+getNif()+
", nombre completo: "+getNombreCompleto()+
",\ncategoria: "+tipo+
", fecha de inscripcion: "+getFechaInscripcion()+"\n";
}
}
|
/*
* Copyright 2014 Open Networking Laboratory
*
* 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.onosproject.net.intent;
import java.util.List;
/**
* Abstraction of an extensible intent service enabled for unit tests.
*/
public interface TestableIntentService extends IntentService, IntentExtensionService {
List<IntentException> getExceptions();
}
|
/*
* Copyright 2002-2011 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.springframework.core.env;
/**
* Interface representing the environment in which the current application is running.
* Models two key aspects of the application environment: <em>profiles</em> and
* <em>properties</em>. Methods related to property access are exposed via the
* {@link PropertyResolver} superinterface.
*
* <p>A <em>profile</em> is a named, logical group of bean definitions to be registered
* with the container only if the given profile is <em>active</em>. Beans may be assigned
* to a profile whether defined in XML or via annotations; see the spring-beans 3.1 schema
* or the {@link org.springframework.context.annotation.Profile @Profile} annotation for
* syntax details. The role of the {@code Environment} object with relation to profiles is
* in determining which profiles (if any) are currently {@linkplain #getActiveProfiles
* active}, and which profiles (if any) should be {@linkplain #getDefaultProfiles active
* by default}.
*
* <p><em>Properties</em> play an important role in almost all applications, and may
* originate from a variety of sources: properties files, JVM system properties, system
* environment variables, JNDI, servlet context parameters, ad-hoc Properties objects,
* Maps, and so on. The role of the environment object with relation to properties is to
* provide the user with a convenient service interface for configuring property sources
* and resolving properties from them.
*
* <p>Beans managed within an {@code ApplicationContext} may register to be {@link
* org.springframework.context.EnvironmentAware EnvironmentAware} or {@code @Inject} the
* {@code Environment} in order to query profile state or resolve properties directly.
*
* <p>In most cases, however, application-level beans should not need to interact with the
* {@code Environment} directly but instead may have to have <code>${...}</code> property
* values replaced by a property placeholder configurer such as
* {@link org.springframework.context.support.PropertySourcesPlaceholderConfigurer
* PropertySourcesPlaceholderConfigurer}, which itself is {@code EnvironmentAware} and
* as of Spring 3.1 is registered by default when using
* {@code <context:property-placeholder/>}.
*
* <p>Configuration of the environment object must be done through the
* {@code ConfigurableEnvironment} interface, returned from all
* {@code AbstractApplicationContext} subclass {@code getEnvironment()} methods. See
* {@link ConfigurableEnvironment} Javadoc for usage examples demonstrating manipulation
* of property sources prior to application context {@code refresh()}.
*
* @author Chris Beams
* @since 3.1
* @see PropertyResolver
* @see EnvironmentCapable
* @see ConfigurableEnvironment
* @see AbstractEnvironment
* @see StandardEnvironment
* @see org.springframework.context.EnvironmentAware
* @see org.springframework.context.ConfigurableApplicationContext#getEnvironment
* @see org.springframework.context.ConfigurableApplicationContext#setEnvironment
* @see org.springframework.context.support.AbstractApplicationContext#createEnvironment
*/
public interface Environment extends PropertyResolver {
/**
* Return the set of profiles explicitly made active for this environment. Profiles
* are used for creating logical groupings of bean definitions to be registered
* conditionally, for example based on deployment environment. Profiles can be
* activated by setting {@linkplain AbstractEnvironment#ACTIVE_PROFILES_PROPERTY_NAME
* "spring.profiles.active"} as a system property or by calling
* {@link ConfigurableEnvironment#setActiveProfiles(String...)}.
*
* <p>If no profiles have explicitly been specified as active, then any {@linkplain
* #getDefaultProfiles() default profiles} will automatically be activated.
*
* @see #getDefaultProfiles
* @see ConfigurableEnvironment#setActiveProfiles
* @see AbstractEnvironment#ACTIVE_PROFILES_PROPERTY_NAME
*/
String[] getActiveProfiles();
/**
* Return the set of profiles to be active by default when no active profiles have
* been set explicitly.
*
* @see #getActiveProfiles
* @see ConfigurableEnvironment#setDefaultProfiles
* @see AbstractEnvironment#DEFAULT_PROFILES_PROPERTY_NAME
*/
String[] getDefaultProfiles();
/**
* Return whether one or more of the given profiles is active or, in the case of no
* explicit active profiles, whether one or more of the given profiles is included in
* the set of default profiles
* @throws IllegalArgumentException if called with zero arguments
* @throws IllegalArgumentException if any profile is null, empty or whitespace-only
* @see #getActiveProfiles
* @see #getDefaultProfiles
*/
boolean acceptsProfiles(String... profiles);
}
|
/*
* Copyright 2004-2020 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.maculaframework.boot.security.web;
import org.maculaframework.boot.security.web.support.Menu;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.List;
/**
* <p>
* <b>TODO CustomSecurityService</b> 安全服务接口
* </p>
*
* @author Rain
* @since 2019-11-03
*/
public interface CustomSecurityService {
/**
* 查询菜单定义中包含URL正则的内容,主要给权限系统匹配每个URL对应的角色
* @param appName 应用名称
* @return
*/
List<Menu> findUrlRegexes(String appName);
/**
* 获取菜单资源,不含ACTION,主要给前端显示菜单
* @param root 根ID
* @param level 层数
* @return 满足条件的菜单信息
*/
List<Menu> findMenus(String appName, int root, int level);
/**
* 根据用户名获取用户信息
* @param username 用户名
* @return 返回用户信息
*/
UserDetails loadUserByUsername(String username);
/**
* 更新用户密码
* @param user
* @param newPassword
* @return 更新后的用户信息
*/
UserDetails updatePassword(UserDetails user, String newPassword);
}
|
/*
* Copyright (c) 2020 TurnOnline.biz 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 biz.turnonline.ecosystem.widget.shared.ui;
import gwt.material.design.client.data.DataSource;
import gwt.material.design.client.data.loader.LoadCallback;
import gwt.material.design.client.data.loader.LoadConfig;
/**
* @author <a href="mailto:pohorelec@turnonline.biz">Jozef Pohorelec</a>
*/
public abstract class RefreshableDataSource<T>
implements DataSource<T>
{
private LoadConfig<T> loadConfig;
private LoadCallback<T> callback;
@Override
public void load( LoadConfig<T> loadConfig, LoadCallback<T> callback )
{
this.loadConfig = loadConfig;
this.callback = callback;
}
public void refresh()
{
load( loadConfig, callback );
}
}
|
package com.ternsip.soil.graph.display;
import lombok.Getter;
import lombok.Setter;
import org.joml.Vector3f;
import org.joml.Vector3fc;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@Getter
@Setter
public class SoundRepository {
private final Set<Sound> sounds = Collections.newSetFromMap(new ConcurrentHashMap<>());
private final Vector3f orientationFront = new Vector3f(0);
private final Vector3f orientationUp = new Vector3f(0);
public float x, y;
public void setListenerPosition(float x, float y) {
this.x = x;
this.y = y;
}
public void setListenerOrientationFront(Vector3fc orient) {
getOrientationFront().set(orient.normalize(new Vector3f()));
}
public void setListenerOrientationUp(Vector3fc orient) {
getOrientationUp().set(orient.normalize(new Vector3f()));
}
public void register(Sound sound) {
getSounds().add(sound);
}
public void unregister(Sound sound) {
getSounds().remove(sound);
}
public void clear() {
getSounds().clear();
}
}
|
package api.client;
/**
* You must implement the SubscriptionListener interface. <br> The server will push any update to
* the client. if client get the update, the onReceive method will be called.
*
* @param <T> The type of received data.
*/
@FunctionalInterface
public interface SubscriptionListener<T> {
/**
* onReceive will be called when get the data sent by server.
*
* @param data The data send by server.
*/
void onReceive(T data) throws InterruptedException;
}
|
/*******************************************************************************
* Copyright (c) 2016 Julien Louette & Gaël Wittorski
*
* This file is part of Raspoid.
*
* Raspoid is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Raspoid 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 Raspoid. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package com.raspoid.brickpi.uart;
import static com.raspoid.brickpi.uart.message.MessageType.MSG_TYPE_VALUES;
import java.util.Map.Entry;
import com.raspoid.brickpi.Atmel;
import com.raspoid.brickpi.uart.message.AckMessage;
import com.raspoid.brickpi.uart.message.AckValuesMessage;
import com.raspoid.brickpi.uart.message.Message;
import com.raspoid.exceptions.RaspoidPacketFormatException;
/**
* Packet formatter utility class allowing to encode messages into bytes
* and decode bytes to messages.
*
* @author Julien Louette & Gaël Wittorski
* @version 1.0
*/
public class PacketFormatter {
/**
* Constructor is private, this is a utility class
*/
private PacketFormatter() {}
/**
* Encodes a message into bytes provided with the Atmel chip and the message
* @param chip the atmel chip
* @param message the message to be encoded
* @return a byte array with the encoded message
*/
public static byte[] encode(Atmel chip, Message message) {
return new Packet(chip.getAddress(), message).toBytes();
}
/**
* Decodes a pair value containing an Atmel chip and a byte array into an AckMessage
* @param recvPacket the received pair value with the atmel chip and byte array
* @return an AckMessage that was decoded
*/
public static AckMessage decode(Entry<Atmel, byte[]> recvPacket) {
byte[] bytesPacket = recvPacket.getValue();
// Check if at least the entire header was received
if (bytesPacket.length < 2) {
throw new RaspoidPacketFormatException("The header was not received properly");
}
byte receivedChecksum = bytesPacket[0];
byte byteCount = bytesPacket[1];
// Check the message length
if (byteCount != bytesPacket.length - 2) {
throw new RaspoidPacketFormatException("The length of the received message does not match the declared length");
}
AckMessage message;
byte byteMsgType = bytesPacket[2];
// If payload is empty, it is a ack message
if (byteCount == 1) {
message = new AckMessage(byteMsgType, recvPacket.getKey());
} // Otherwhise it can only be a values message
else if (byteMsgType == MSG_TYPE_VALUES.toByte()) {
byte[] messagePayload = new byte[byteCount - 1];
System.arraycopy(bytesPacket, 3, messagePayload, 0, byteCount - 1);
message = new AckValuesMessage(messagePayload, recvPacket.getKey());
} else {
throw new RaspoidPacketFormatException("The packet type is erroneous (expected Ack packet or Values packet)");
}
//Create the packet to validate the checksum
Packet packet = new Packet(message);
if (receivedChecksum != packet.getChecksum()) {
throw new RaspoidPacketFormatException("The packet checksum is erroneous (expected: " + packet.getChecksum() + ", received: " + receivedChecksum + ")");
}
return message;
}
}
|
// This file is auto-generated, don't edit it. Thanks.
package com.antgroup.antchain.openapi.bot.models;
import com.aliyun.tea.*;
public class UpdateProductkeyResponse extends TeaModel {
// 请求唯一ID,用于链路跟踪和问题排查
@NameInMap("req_msg_id")
public String reqMsgId;
// 结果码,一般OK表示调用成功
@NameInMap("result_code")
public String resultCode;
// 异常信息的文本描述
@NameInMap("result_msg")
public String resultMsg;
public static UpdateProductkeyResponse build(java.util.Map<String, ?> map) throws Exception {
UpdateProductkeyResponse self = new UpdateProductkeyResponse();
return TeaModel.build(map, self);
}
public UpdateProductkeyResponse setReqMsgId(String reqMsgId) {
this.reqMsgId = reqMsgId;
return this;
}
public String getReqMsgId() {
return this.reqMsgId;
}
public UpdateProductkeyResponse setResultCode(String resultCode) {
this.resultCode = resultCode;
return this;
}
public String getResultCode() {
return this.resultCode;
}
public UpdateProductkeyResponse setResultMsg(String resultMsg) {
this.resultMsg = resultMsg;
return this;
}
public String getResultMsg() {
return this.resultMsg;
}
}
|
//
// Este arquivo foi gerado pela Arquitetura JavaTM para Implementação de Referência (JAXB) de Bind XML, v2.2.8-b130911.1802
// Consulte <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Todas as modificações neste arquivo serão perdidas após a recompilação do esquema de origem.
// Gerado em: 2021.03.05 às 03:20:59 PM BRT
//
package br.jus.tst.esocial.esquemas.eventos.cat;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementRefs;
import javax.xml.bind.annotation.XmlType;
import org.w3c.dom.Element;
/**
* <p>Classe Java de PGPDataType complex type.
*
* <p>O seguinte fragmento do esquema especifica o conteúdo esperado contido dentro desta classe.
*
* <pre>
* <complexType name="PGPDataType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <choice>
* <sequence>
* <element name="PGPKeyID" type="{http://www.w3.org/2001/XMLSchema}base64Binary"/>
* <element name="PGPKeyPacket" type="{http://www.w3.org/2001/XMLSchema}base64Binary" minOccurs="0"/>
* <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <sequence>
* <element name="PGPKeyPacket" type="{http://www.w3.org/2001/XMLSchema}base64Binary"/>
* <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </choice>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PGPDataType", namespace = "http://www.w3.org/2000/09/xmldsig#", propOrder = {
"content"
})
public class PGPDataType {
@XmlElementRefs({
@XmlElementRef(name = "PGPKeyID", namespace = "http://www.w3.org/2000/09/xmldsig#", type = JAXBElement.class, required = false),
@XmlElementRef(name = "PGPKeyPacket", namespace = "http://www.w3.org/2000/09/xmldsig#", type = JAXBElement.class, required = false)
})
@XmlAnyElement(lax = true)
protected List<Object> content;
/**
* Obtém o restante do modelo do conteúdo.
*
* <p>
* Você está obtendo esta propriedade "catch-all" pelo seguinte motivo:
* O nome do campo "PGPKeyPacket" é usado por duas partes diferentes de um esquema. Consulte:
* linha 220 de file:/home/tiago/desenv/git/esocial/src/esocial-esquemas/src/main/resources/xsd/xmldsig-core-schema.xsd
* linha 215 de file:/home/tiago/desenv/git/esocial/src/esocial-esquemas/src/main/resources/xsd/xmldsig-core-schema.xsd
* <p>
* Para eliminar esta propriedade, aplique uma personalização de propriedade a uma
* das seguintes declarações, a fim de alterar seus nomes:
* Gets the value of the content 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 content property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getContent().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Object }
* {@link Element }
* {@link JAXBElement }{@code <}{@link byte[]}{@code >}
* {@link JAXBElement }{@code <}{@link byte[]}{@code >}
*
*
*/
public List<Object> getContent() {
if (content == null) {
content = new ArrayList<Object>();
}
return this.content;
}
}
|
package com.github.guikeller.jettyrunner.ui;
import com.github.guikeller.jettyrunner.model.JettyRunnerConfiguration;
import com.intellij.compiler.impl.ModuleCompileScope;
import com.intellij.notification.*;
import com.intellij.openapi.compiler.CompileTask;
import com.intellij.openapi.compiler.CompilerManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiFile;
import com.intellij.psi.search.PsiShortNamesCache;
import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
/**
* Controller - Jetty Runner Editor
* @see com.intellij.openapi.options.SettingsEditor
* @author Gui Keller
*/
public class JettyRunnerEditor extends SettingsEditor<JettyRunnerConfiguration> {
private JettyRunnerConfPanel configurationPanel;
private String mainOutputDirectory = "";
public JettyRunnerEditor(JettyRunnerConfiguration jettyRunnerConfiguration) {
this.configurationPanel = new JettyRunnerConfPanel();
super.resetFrom(jettyRunnerConfiguration);
}
/**
* This is invoked when the form is first loaded.
* The values may be stored in disk, if not, set some defaults
* @param jettyRunnerConfiguration jettyRunnerConfiguration
*/
@Override
protected void resetEditorFrom(JettyRunnerConfiguration jettyRunnerConfiguration) {
Project project = jettyRunnerConfiguration.getProject();
// WebApp Path
String webappPaths = jettyRunnerConfiguration.getWebappPaths();
if (webappPaths != null && !"".equals(webappPaths.trim())) {
this.configurationPanel.getPathField().setText(webappPaths);
} else {
String projectName = project.getName();
this.configurationPanel.getPathField().setText("/"+projectName);
}
// WebApp Folder (one level down to web.xml"
String webappFolders = jettyRunnerConfiguration.getWebappFolders();
if (webappFolders != null && !"".equals(webappFolders.trim())) {
this.configurationPanel.getWebappField().setText(webappFolders);
} else {
String webAppsFolder = getWebAppsFolder(project);
this.configurationPanel.getWebappField().setText(webAppsFolder);
}
// Classes directory
String classesDirectories = jettyRunnerConfiguration.getClassesDirectories();
if (classesDirectories != null && !"".equals(classesDirectories.trim())) {
this.configurationPanel.getClassesField().setText(classesDirectories);
} else {
String outputDirectory = getMainOutputDirectory(project, jettyRunnerConfiguration.getModules());
this.configurationPanel.getClassesField().setText(outputDirectory);
}
// Runs on port
String runningOnPort = jettyRunnerConfiguration.getRunningOnPort();
if (runningOnPort != null && !"".equals(runningOnPort)) {
this.configurationPanel.getRunOnPortField().setText(runningOnPort);
} else {
this.configurationPanel.getRunOnPortField().setText("8080");
}
// Choose modules (all modules default)
String selectedModuleName = jettyRunnerConfiguration.getSelectedModuleName();
final Module[] modules = ModuleManager.getInstance(project).getModules();
final String[] modulesNames = new String[modules.length + 1];
modulesNames[0] = "<all modules>";
int indexToSelect = 0;
for (int i = 0; i < modules.length; i++) {
final String currentModuleName = modules[i].getName();
modulesNames[i + 1] = currentModuleName;
if (currentModuleName.equals(selectedModuleName)) {
indexToSelect = i + 1;
}
}
this.configurationPanel.getModuleComboBox().setModel(new DefaultComboBoxModel<>(modulesNames));
this.configurationPanel.getModuleComboBox().setSelectedIndex(indexToSelect);
// Jetty XML (Optional)
this.configurationPanel.getXmlField().setText(jettyRunnerConfiguration.getJettyXml());
// Jetty Runner Path
this.configurationPanel.getJettyRunnerField().setText(jettyRunnerConfiguration.getJettyRunnerJarPath());
// Env Vars (Optional)
Map<String, String> environmentVariables = jettyRunnerConfiguration.getEnvironmentVariables();
if(environmentVariables != null && !environmentVariables.isEmpty()){
this.configurationPanel.getEnvironmentVariables().setEnvs(environmentVariables);
}
// Vm Args (Optional)
this.configurationPanel.getVmArgsField().setText(jettyRunnerConfiguration.getVmArgs());
}
/**
* This is invoked when the user fills the form and pushes apply/ok
* @param jettyRunnerConfiguration jettyRunnerConfiguration
* @throws ConfigurationException ex
*/
@Override
protected void applyEditorTo(JettyRunnerConfiguration jettyRunnerConfiguration) throws ConfigurationException {
JComboBox<String> moduleComboBox = this.configurationPanel.getModuleComboBox();
jettyRunnerConfiguration.setSelectedModuleName(moduleComboBox.getItemAt(moduleComboBox.getSelectedIndex()));
jettyRunnerConfiguration.setWebappPaths(this.configurationPanel.getPathField().getText());
jettyRunnerConfiguration.setWebappFolders(this.configurationPanel.getWebappField().getText());
jettyRunnerConfiguration.setClassesDirectories(this.configurationPanel.getClassesField().getText());
jettyRunnerConfiguration.setRunningOnPort(this.configurationPanel.getRunOnPortField().getText());
jettyRunnerConfiguration.setJettyXml(this.configurationPanel.getXmlField().getText());
jettyRunnerConfiguration.setJettyRunnerJarPath(this.configurationPanel.getJettyRunnerField().getText());
jettyRunnerConfiguration.setVmArgs(this.configurationPanel.getVmArgsField().getText());
jettyRunnerConfiguration.setPassParentEnvironmentVariables(this.configurationPanel.getEnvironmentVariables().isPassParentEnvs());
// Deals with adding / removing env vars before saving to the conf file
Map<String, String> envVars = this.configurationPanel.getEnvironmentVariables().getEnvs();
addOrRemoveEnvVar(jettyRunnerConfiguration.getEnvironmentVariables(), envVars);
jettyRunnerConfiguration.setEnvironmentVariables(envVars);
try {
// Not entirely sure if 'I have to' do this - the IntelliJ framework may do
jettyRunnerConfiguration.writeExternal(new Element(JettyRunnerConfiguration.PREFIX + UUID.randomUUID().toString()));
} catch (WriteExternalException e) {
throw new RuntimeException(e);
}
}
@NotNull
@Override
protected JComponent createEditor() {
return this.configurationPanel.getMainPanel();
}
// Helpers
/**
* Retrieves the output directory for the main module
* @param project Project
* @param modules Concerned modules array
* @return String value
*/
private String getMainOutputDirectory(final Project project, Module[] modules) {
// Preparing things up for a sneaky "CompileTask"
final CompilerManager compilerManager = CompilerManager.getInstance(project);
final ModuleCompileScope compileScope = new ModuleCompileScope(project, modules, false);
final Module mainModule = modules[0];
// Though a "CompileTask" I can get hold of the "CompileContext"
CompileTask compileTask = compileContext -> {
// Through the "CompileContext" I can get the output directory of the main module
VirtualFile mainOutputDirectory = compileContext.getModuleOutputDirectory(mainModule);
if(mainOutputDirectory != null) {
JettyRunnerEditor.this.mainOutputDirectory = mainOutputDirectory.getPresentableUrl();
} else {
// Project hasn't been compiled yet, so there is no output directory
NotificationGroup notificationGroup = new NotificationGroup("IDEA Jetty Runner", NotificationDisplayType.BALLOON, true);
Notification notification = notificationGroup.createNotification("Jetty Runner - Couldn't determine the classes folder:<br>Please compile / make your project before creating the conf.", NotificationType.ERROR);
Notifications.Bus.notify(notification, project);
}
return true;
};
// Executes the task (synchronously), which invokes that internal 'execute' method
compilerManager.executeTask(compileTask, compileScope, "JettyRunner-By-GuiKeller", null);
return this.mainOutputDirectory;
}
/**
* Returns the most probable WebApps folder
* @param project Project
* @return String value
*/
private String getWebAppsFolder(Project project) {
// Using the api to look for the web.xml
String webappsFolder = "";
PsiShortNamesCache namesCache = PsiShortNamesCache.getInstance(project);
PsiFile[] webXML = namesCache.getFilesByName("web.xml");
if (webXML != null && webXML.length > 0) {
// Grab the first one that the api found
PsiFile file = webXML[0];
// The parent folder is the "WEB-INF" folder
PsiDirectory webInfFolder = file.getParent();
if (webInfFolder != null) {
// The parent folder to "WEB-INF" is the WebApps folder
PsiDirectory webappFolder = webInfFolder.getParent();
if (webappFolder != null){
VirtualFile virtualFile = webappFolder.getVirtualFile();
webappsFolder = virtualFile.getPresentableUrl();
}
}
}
return webappsFolder;
}
/**
* Adds / removes variables to the System Environment Variables
* @param currentVars Map<String,String>
* @param newVars Map<String,String>
*/
private void addOrRemoveEnvVar(Map<String, String> currentVars, Map<String, String> newVars){
// Removes the current env vars
if(currentVars !=null && !currentVars.isEmpty()) {
Set<String> keys = currentVars.keySet();
for (String key : keys) {
System.clearProperty(key);
}
}
// Adds the new env vars
if(newVars != null && !newVars.isEmpty()){
Set<String> keys = newVars.keySet();
for(String key : keys) {
String value = newVars.get(key);
System.setProperty(key, value);
}
}
}
public void setConfigurationPanel(JettyRunnerConfPanel configurationPanel) {
this.configurationPanel = configurationPanel;
}
}
|
package mage.cards.c;
import java.util.UUID;
import mage.MageInt;
import mage.ObjectColor;
import mage.abilities.common.BeginningOfUpkeepTriggeredAbility;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.effects.common.CreateTokenEffect;
import mage.abilities.effects.common.continuous.BoostControlledEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.constants.Duration;
import mage.constants.TargetController;
import mage.constants.Zone;
import mage.filter.common.FilterCreaturePermanent;
import mage.filter.predicate.mageobject.ColorPredicate;
import mage.game.permanent.token.CreakwoodLiegeToken;
/**
*
* @author anonymous
*/
public final class CreakwoodLiege extends CardImpl {
private static final FilterCreaturePermanent filterBlackCreature = new FilterCreaturePermanent("black creatures");
private static final FilterCreaturePermanent filterGreenCreature = new FilterCreaturePermanent("green creatures");
static {
filterBlackCreature.add(new ColorPredicate(ObjectColor.BLACK));
filterGreenCreature.add(new ColorPredicate(ObjectColor.GREEN));
}
public CreakwoodLiege(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{B/G}{B/G}{B/G}");
this.subtype.add(SubType.HORROR);
this.power = new MageInt(2);
this.toughness = new MageInt(2);
// Other black creatures you control get +1/+1.
this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new BoostControlledEffect(1, 1, Duration.WhileOnBattlefield, filterBlackCreature, true)));
// Other green creatures you control get +1/+1.
this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new BoostControlledEffect(1, 1, Duration.WhileOnBattlefield, filterGreenCreature, true)));
// At the beginning of your upkeep, you may create a 1/1 black and green Worm creature token.
this.addAbility(new BeginningOfUpkeepTriggeredAbility(new CreateTokenEffect(new CreakwoodLiegeToken(), 1), TargetController.YOU, true));
}
public CreakwoodLiege(final CreakwoodLiege card) {
super(card);
}
@Override
public CreakwoodLiege copy() {
return new CreakwoodLiege(this);
}
}
|
package com.wuyr.pathviewtest;
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.*;
/**
* 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.getTargetContext();
assertEquals("com.wuyr.pathviewtest", appContext.getPackageName());
}
}
|
package sort;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MinHeap {
private List<Integer> tree = new ArrayList<>();
public static void main(String[] args) {
int[] nums = new int[] { 49, 38, 65, 97, 76, 13, 27, 49 };
MinHeap heap = new MinHeap();
for(int num : nums) {
heap.add(num);
}
for(int i=0; i<nums.length; i++) {
nums[i] = heap.remove();
}
System.out.println(Arrays.toString(nums));
}
public MinHeap() {
super();
}
public void clear() {
this.tree.clear();
}
public Integer peek() {
if(this.tree.size() == 0)
return null;
return this.tree.get(0);
}
public void add(Integer number) {
this.tree.add(number);
int currentIndex = this.tree.size() - 1;
int parentIndex = this.parentIndex(currentIndex);
while(this.tree.get(currentIndex) < this.tree.get(parentIndex)) {
this.swap(currentIndex, parentIndex);
currentIndex = parentIndex;
parentIndex = this.parentIndex(currentIndex);
}
return;
}
public Integer remove() {
if(this.tree.size() == 0)
return null;
if(this.tree.size() == 1)
return this.tree.remove(0);
this.swap(0, this.tree.size() - 1);
Integer min = this.tree.remove(this.tree.size() - 1);
heapify(0);
return min;
}
private void heapify(int index) {
int leftIndex = this.leftChildIndex(index);
Integer left = leftIndex > this.tree.size() - 1? Integer.MAX_VALUE : this.tree.get(leftIndex);
int rightIndex = this.rightChildIndex(index);
Integer right = rightIndex > this.tree.size() - 1? Integer.MAX_VALUE : this.tree.get(rightIndex);
int smallIndex;
Integer small;
if(left.compareTo(right) <= 0) {
smallIndex = leftIndex;
small = left;
} else {
smallIndex = rightIndex;
small = right;
}
if(this.tree.get(index).compareTo(small) <= 0)
return;
this.swap(index, smallIndex);
this.heapify(smallIndex);
return;
}
private int parentIndex(int childIndex) {
if(childIndex == 0)
return childIndex;
if(childIndex % 2 == 0)
return childIndex / 2 - 1;
else
return ( childIndex - 1 ) / 2;
}
private int leftChildIndex(int parentIndex) {
return 2 * parentIndex + 1;
}
private int rightChildIndex(int parentIndex) {
return 2 * parentIndex + 2;
}
private void swap(int a, int b) {
Integer tmp = this.tree.get(a);
this.tree.set(a, this.tree.get(b));
this.tree.set(b, tmp);
}
}
|
package reposense.model;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import reposense.parser.InvalidLocationException;
import reposense.report.ErrorSummary;
import reposense.util.StringsUtil;
import reposense.util.SystemUtil;
/**
* Represents a repository location.
*/
public class RepoLocation {
private static final String GIT_LINK_SUFFIX = ".git";
private static final String MESSAGE_INVALID_LOCATION = "%s is an invalid location.";
private static final Pattern GIT_REPOSITORY_LOCATION_PATTERN =
Pattern.compile("^https?://github.com/(?<org>.+?)/(?<repoName>.+?)\\.git$");
private final String location;
private final String repoName;
private String organization;
/**
* @throws InvalidLocationException if {@code location} cannot be represented by a {@code URL} or {@code Path}.
*/
public RepoLocation(String location) throws InvalidLocationException {
if (SystemUtil.isWindows()) {
location = StringsUtil.removeTrailingBackslash(location);
}
verifyLocation(location);
this.location = location;
Matcher matcher = GIT_REPOSITORY_LOCATION_PATTERN.matcher(location);
if (matcher.matches()) {
organization = matcher.group("org");
repoName = matcher.group("repoName");
} else {
repoName = Paths.get(location).getFileName().toString().replace(GIT_LINK_SUFFIX, "");
}
}
public boolean isEmpty() {
return location.isEmpty();
}
public String getRepoName() {
return repoName;
}
public String getOrganization() {
return organization;
}
/**
* Verifies {@code location} can be presented as a {@code URL} or {@code Path}.
* @throws InvalidLocationException if otherwise.
*/
private void verifyLocation(String location) throws InvalidLocationException {
boolean isValidPathLocation = false;
boolean isValidGitUrl = false;
try {
Path pathLocation = Paths.get(location);
isValidPathLocation = Files.exists(pathLocation);
} catch (InvalidPathException ipe) {
// Ignore exception
}
Matcher matcher = GIT_REPOSITORY_LOCATION_PATTERN.matcher(location);
isValidGitUrl = matcher.matches();
if (!isValidPathLocation && !isValidGitUrl) {
ErrorSummary.getInstance().addErrorMessage(location, String.format(MESSAGE_INVALID_LOCATION, location));
throw new InvalidLocationException(String.format(MESSAGE_INVALID_LOCATION, location));
}
}
@Override
public String toString() {
return location;
}
@Override
public boolean equals(Object other) {
// short circuit if same object
if (this == other) {
return true;
}
// instanceof handles null
if (!(other instanceof RepoLocation)) {
return false;
}
RepoLocation otherLocation = (RepoLocation) other;
return this.location.equals(otherLocation.location);
}
@Override
public int hashCode() {
return location.hashCode();
}
}
|
/*
* Copyright 2017 Confluent Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package io.confluent.ksql.planner.plan;
import static io.confluent.ksql.planner.plan.PlanTestUtil.MAPVALUES_NODE;
import static io.confluent.ksql.planner.plan.PlanTestUtil.SOURCE_NODE;
import static io.confluent.ksql.planner.plan.PlanTestUtil.TRANSFORM_NODE;
import static io.confluent.ksql.planner.plan.PlanTestUtil.getNodeByName;
import static io.confluent.ksql.planner.plan.PlanTestUtil.verifyProcessorNode;
import static org.easymock.EasyMock.eq;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.confluent.ksql.ddl.DdlConfig;
import io.confluent.ksql.function.InternalFunctionRegistry;
import io.confluent.ksql.metastore.KsqlStream;
import io.confluent.ksql.metastore.KsqlTable;
import io.confluent.ksql.metastore.KsqlTopic;
import io.confluent.ksql.schema.registry.MockSchemaRegistryClientFactory;
import io.confluent.ksql.serde.json.KsqlJsonTopicSerDe;
import io.confluent.ksql.structured.SchemaKStream;
import io.confluent.ksql.structured.SchemaKTable;
import io.confluent.ksql.util.KafkaTopicClient;
import io.confluent.ksql.util.KsqlConfig;
import io.confluent.ksql.util.timestamp.LongColumnTimestampExtractionPolicy;
import io.confluent.ksql.util.timestamp.MetadataTimestampExtractionPolicy;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.kafka.common.config.TopicConfig;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.connect.data.Field;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.data.SchemaBuilder;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.TopologyDescription;
import org.apache.kafka.streams.kstream.WindowedSerdes;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
public class KsqlStructuredDataOutputNodeTest {
private final KafkaTopicClient topicClient = EasyMock.createNiceMock(KafkaTopicClient.class);
private static final String MAPVALUES_OUTPUT_NODE = "KSTREAM-MAPVALUES-0000000003";
private static final String OUTPUT_NODE = "KSTREAM-SINK-0000000004";
private final Schema schema = SchemaBuilder.struct()
.field("field1", Schema.OPTIONAL_STRING_SCHEMA)
.field("field2", Schema.OPTIONAL_STRING_SCHEMA)
.field("field3", Schema.OPTIONAL_STRING_SCHEMA)
.field("timestamp", Schema.OPTIONAL_INT64_SCHEMA)
.field("key", Schema.OPTIONAL_STRING_SCHEMA)
.build();
private final KsqlStream dataSource = new KsqlStream<>("sqlExpression", "datasource",
schema,
schema.field("key"),
new LongColumnTimestampExtractionPolicy("timestamp"),
new KsqlTopic("input", "input",
new KsqlJsonTopicSerDe(), false), Serdes.String());
private final StructuredDataSourceNode sourceNode = new StructuredDataSourceNode(
new PlanNodeId("0"),
dataSource,
schema);
private final KsqlConfig ksqlConfig = new KsqlConfig(new HashMap<>());
private StreamsBuilder builder = new StreamsBuilder();
private KsqlStructuredDataOutputNode outputNode;
private SchemaKStream stream;
@Before
public void before() {
final Map<String, Object> props = new HashMap<>();
props.put(KsqlConfig.SINK_NUMBER_OF_PARTITIONS_PROPERTY, 4);
props.put(KsqlConfig.SINK_NUMBER_OF_REPLICAS_PROPERTY, (short)3);
createOutputNode(props);
topicClient.createTopic(eq("output"), eq(4), eq((short)3), eq(Collections.emptyMap()));
EasyMock.expectLastCall();
EasyMock.replay(topicClient);
stream = buildStream();
}
private void createOutputNode(final Map<String, Object> props) {
outputNode = new KsqlStructuredDataOutputNode(new PlanNodeId("0"),
sourceNode,
schema,
new LongColumnTimestampExtractionPolicy("timestamp"),
schema.field("key"),
new KsqlTopic("output", "output", new KsqlJsonTopicSerDe(), true),
"output",
props,
Optional.empty(),
true);
}
@Test
public void shouldBuildSourceNode() {
final TopologyDescription.Source node = (TopologyDescription.Source) getNodeByName(builder.build(), SOURCE_NODE);
final List<String> successors = node.successors().stream().map(TopologyDescription.Node::name).collect(Collectors.toList());
assertThat(node.predecessors(), equalTo(Collections.emptySet()));
assertThat(successors, equalTo(Collections.singletonList(MAPVALUES_NODE)));
assertThat(node.topicSet(), equalTo(ImmutableSet.of("input")));
}
@Test
public void shouldBuildMapNodePriorToOutput() {
verifyProcessorNode((TopologyDescription.Processor) getNodeByName(builder.build(), MAPVALUES_OUTPUT_NODE),
Collections.singletonList(TRANSFORM_NODE),
Collections.singletonList(OUTPUT_NODE));
}
@Test
public void shouldBuildOutputNode() {
final TopologyDescription.Sink sink = (TopologyDescription.Sink) getNodeByName(builder.build(), OUTPUT_NODE);
final List<String> predecessors = sink.predecessors().stream().map(TopologyDescription.Node::name).collect(Collectors.toList());
assertThat(sink.successors(), equalTo(Collections.emptySet()));
assertThat(predecessors, equalTo(Collections.singletonList(MAPVALUES_OUTPUT_NODE)));
assertThat(sink.topic(), equalTo("output"));
}
@Test
public void shouldSetOutputNodeOnStream() {
assertThat(stream.outputNode(), instanceOf(KsqlStructuredDataOutputNode.class));
}
@Test
public void shouldHaveCorrectOutputNodeSchema() {
final List<Field> expected = Arrays.asList(
new Field("ROWTIME", 0, Schema.OPTIONAL_INT64_SCHEMA),
new Field("ROWKEY", 1, Schema.OPTIONAL_STRING_SCHEMA),
new Field("field1", 2, Schema.OPTIONAL_STRING_SCHEMA),
new Field("field2", 3, Schema.OPTIONAL_STRING_SCHEMA),
new Field("field3", 4, Schema.OPTIONAL_STRING_SCHEMA),
new Field("timestamp", 5, Schema.OPTIONAL_INT64_SCHEMA),
new Field("key", 6, Schema.OPTIONAL_STRING_SCHEMA));
final List<Field> fields = stream.outputNode().getSchema().fields();
assertThat(fields, equalTo(expected));
}
@Test
public void shouldPartitionByFieldNameInPartitionByProperty() {
createOutputNode(Collections.singletonMap(DdlConfig.PARTITION_BY_PROPERTY, "field2"));
final SchemaKStream schemaKStream = buildStream();
final Field keyField = schemaKStream.getKeyField();
assertThat(keyField, equalTo(new Field("field2", 1, Schema.OPTIONAL_STRING_SCHEMA)));
assertThat(schemaKStream.getSchema().fields(), equalTo(schema.fields()));
}
@Test
public void shouldCreateSinkTopic() {
EasyMock.verify(topicClient);
}
private SchemaKStream buildStream() {
builder = new StreamsBuilder();
return outputNode.buildStream(builder,
ksqlConfig,
topicClient,
new InternalFunctionRegistry(),
new HashMap<>(), new MockSchemaRegistryClientFactory()::get);
}
@Test
public void shouldCreateSinkWithCorrectCleanupPolicyNonWindowedTable() {
final KafkaTopicClient topicClientForNonWindowTable = EasyMock.mock(KafkaTopicClient.class);
final KsqlStructuredDataOutputNode outputNode = getKsqlStructuredDataOutputNode(Serdes.String());
final StreamsBuilder streamsBuilder = new StreamsBuilder();
final Map<String, String> topicConfig = ImmutableMap.of(
TopicConfig.CLEANUP_POLICY_CONFIG, TopicConfig.CLEANUP_POLICY_COMPACT);
topicClientForNonWindowTable.createTopic("output", 4, (short) 3, topicConfig);
EasyMock.replay(topicClientForNonWindowTable);
final SchemaKStream schemaKStream = outputNode.buildStream(
streamsBuilder,
ksqlConfig,
topicClientForNonWindowTable,
new InternalFunctionRegistry(),
new HashMap<>(),
new MockSchemaRegistryClientFactory()::get);
assertThat(schemaKStream, instanceOf(SchemaKTable.class));
EasyMock.verify();
}
@Test
public void shouldCreateSinkWithCorrectCleanupPolicyWindowedTable() {
final KafkaTopicClient topicClientForWindowTable = EasyMock.mock(KafkaTopicClient.class);
final KsqlStructuredDataOutputNode outputNode = getKsqlStructuredDataOutputNode(
WindowedSerdes.timeWindowedSerdeFrom(String.class));
final StreamsBuilder streamsBuilder = new StreamsBuilder();
topicClientForWindowTable.createTopic("output", 4, (short) 3, Collections.emptyMap());
EasyMock.replay(topicClientForWindowTable);
final SchemaKStream schemaKStream = outputNode.buildStream(
streamsBuilder,
ksqlConfig,
topicClientForWindowTable,
new InternalFunctionRegistry(),
new HashMap<>(),
new MockSchemaRegistryClientFactory()::get);
assertThat(schemaKStream, instanceOf(SchemaKTable.class));
EasyMock.verify();
}
@Test
public void shouldCreateSinkWithCorrectCleanupPolicyStream() {
final KafkaTopicClient topicClientForWindowTable = EasyMock.mock(KafkaTopicClient.class);
final StreamsBuilder streamsBuilder = new StreamsBuilder();
topicClientForWindowTable.createTopic("output", 4, (short) 3, Collections.emptyMap());
EasyMock.replay(topicClientForWindowTable);
final SchemaKStream schemaKStream = outputNode.buildStream(
streamsBuilder,
ksqlConfig,
topicClientForWindowTable,
new InternalFunctionRegistry(),
new HashMap<>(),
new MockSchemaRegistryClientFactory()::get);
assertThat(schemaKStream, instanceOf(SchemaKStream.class));
EasyMock.verify();
}
private KsqlStructuredDataOutputNode getKsqlStructuredDataOutputNode(final Serde<?> keySerde) {
final Map<String, Object> props = new HashMap<>();
props.put(KsqlConfig.SINK_NUMBER_OF_PARTITIONS_PROPERTY, 4);
props.put(KsqlConfig.SINK_NUMBER_OF_REPLICAS_PROPERTY, (short)3);
final StructuredDataSourceNode tableSourceNode = new StructuredDataSourceNode(
new PlanNodeId("0"),
new KsqlTable<>(
"sqlExpression", "datasource",
schema,
schema.field("key"),
new MetadataTimestampExtractionPolicy(),
new KsqlTopic("input", "input", new KsqlJsonTopicSerDe(), false),
"TableStateStore",
keySerde),
schema);
return new KsqlStructuredDataOutputNode(
new PlanNodeId("0"),
tableSourceNode,
schema,
new MetadataTimestampExtractionPolicy(),
schema.field("key"),
new KsqlTopic("output", "output", new KsqlJsonTopicSerDe(), true),
"output",
props,
Optional.empty(),
true);
}
}
|
/*******************************************************************************
* Copyright (c) 2013-2015 Sierra Wireless and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.html.
*
* Contributors:
* Sierra Wireless - initial API and implementation
*******************************************************************************/
package org.eclipse.leshan.server.impl;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.eclipse.leshan.server.Startable;
import org.eclipse.leshan.server.Stoppable;
import org.eclipse.leshan.server.client.Client;
import org.eclipse.leshan.server.client.ClientRegistry;
import org.eclipse.leshan.server.client.ClientRegistryListener;
import org.eclipse.leshan.server.client.ClientUpdate;
import org.eclipse.leshan.util.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* In memory client registry
*/
public class ClientRegistryImpl implements ClientRegistry, Startable, Stoppable {
private static final Logger LOG = LoggerFactory.getLogger(ClientRegistryImpl.class);
private final Map<String /* end-point */, Client> clientsByEp = new ConcurrentHashMap<>();
private final List<ClientRegistryListener> listeners = new CopyOnWriteArrayList<>();
@Override
public void addListener(ClientRegistryListener listener) {
listeners.add(listener);
}
@Override
public void removeListener(ClientRegistryListener listener) {
listeners.remove(listener);
}
@Override
public Collection<Client> allClients() {
return Collections.unmodifiableCollection(clientsByEp.values());
}
@Override
public Client get(String endpoint) {
return clientsByEp.get(endpoint);
}
@Override
public boolean registerClient(Client client) {
Validate.notNull(client);
LOG.debug("Registering new client: {}", client);
Client previous = clientsByEp.put(client.getEndpoint(), client);
if (previous != null) {
for (ClientRegistryListener l : listeners) {
l.unregistered(previous);
}
}
for (ClientRegistryListener l : listeners) {
l.registered(client);
}
return true;
}
@Override
public Client updateClient(ClientUpdate update) {
Validate.notNull(update);
LOG.debug("Updating registration for client: {}", update);
Client client = findByRegistrationId(update.getRegistrationId());
if (client == null) {
return null;
} else {
Client clientUpdated = update.updateClient(client);
clientsByEp.put(clientUpdated.getEndpoint(), clientUpdated);
// notify listener
for (ClientRegistryListener l : listeners) {
l.updated(update, clientUpdated);
}
return clientUpdated;
}
}
@Override
public Client deregisterClient(String registrationId) {
Validate.notNull(registrationId);
LOG.debug("Deregistering client with registrationId: {}", registrationId);
Client toBeUnregistered = findByRegistrationId(registrationId);
if (toBeUnregistered == null) {
return null;
} else {
Client unregistered = clientsByEp.remove(toBeUnregistered.getEndpoint());
for (ClientRegistryListener l : listeners) {
l.unregistered(unregistered);
}
LOG.debug("Deregistered client: {}", unregistered);
return unregistered;
}
}
@Override
public Client findByRegistrationId(String id) {
Client result = null;
if (id != null) {
for (Client client : clientsByEp.values()) {
if (id.equals(client.getRegistrationId())) {
result = client;
break;
}
}
}
return result;
}
/**
* start the registration manager, will start regular cleanup of dead registrations.
*/
@Override
public void start() {
// every 2 seconds clean the registration list
// TODO re-consider clean-up interval: wouldn't 5 minutes do as well?
schedExecutor.scheduleAtFixedRate(new Cleaner(), 2, 2, TimeUnit.SECONDS);
}
/**
* Stop the underlying cleanup of the registrations.
*/
@Override
public void stop() {
schedExecutor.shutdownNow();
try {
schedExecutor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOG.warn("Clean up registration thread was interrupted.", e);
}
}
private final ScheduledExecutorService schedExecutor = Executors.newScheduledThreadPool(1);
private class Cleaner implements Runnable {
@Override
public void run() {
for (Client client : clientsByEp.values()) {
synchronized (client) {
if (!client.isAlive()) {
// force de-registration
deregisterClient(client.getRegistrationId());
}
}
}
}
}
}
|
package mage.cards.r;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.common.OnEventTriggeredAbility;
import mage.abilities.effects.common.ReturnToHandChosenControlledPermanentEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.filter.common.FilterControlledCreaturePermanent;
import mage.game.events.GameEvent.EventType;
/**
*
* @author North
*/
public final class RoaringPrimadox extends CardImpl {
public RoaringPrimadox(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{3}{G}");
this.subtype.add(SubType.BEAST);
this.power = new MageInt(4);
this.toughness = new MageInt(4);
// At the beginning of your upkeep, return a creature you control to its owner's hand.
this.addAbility(new OnEventTriggeredAbility(EventType.UPKEEP_STEP_PRE, "beginning of your upkeep", new ReturnToHandChosenControlledPermanentEffect(new FilterControlledCreaturePermanent())));
}
private RoaringPrimadox(final RoaringPrimadox card) {
super(card);
}
@Override
public RoaringPrimadox copy() {
return new RoaringPrimadox(this);
}
}
|
package com.baiyi.opscloud.datasource.business.serverGroup.factory;
import com.baiyi.opscloud.datasource.business.serverGroup.IServerGroup;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @Author baiyi
* @Date 2021/8/24 1:31 下午
* @Version 1.0
*/
public class ServerGroupHandlerFactory {
private ServerGroupHandlerFactory() {
}
private static final Map<String, IServerGroup> context = new ConcurrentHashMap<>();
public static IServerGroup getIServerGroupByInstanceType(String instanceType) {
return context.get(instanceType);
}
public static void register(IServerGroup bean) {
context.put(bean.getInstanceType(), bean);
}
public static Map<String, IServerGroup> getIServerGroupContainer() {
return context;
}
}
|
/**
* 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.
*/
/**
* Autogenerated by Thrift Compiler (0.9.3)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package org.apache.storm.generated;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.3)")
public class LSTopoHistory implements org.apache.thrift.TBase<LSTopoHistory, LSTopoHistory._Fields>, java.io.Serializable, Cloneable, Comparable<LSTopoHistory> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("LSTopoHistory");
private static final org.apache.thrift.protocol.TField TOPOLOGY_ID_FIELD_DESC = new org.apache.thrift.protocol.TField("topology_id", org.apache.thrift.protocol.TType.STRING, (short)1);
private static final org.apache.thrift.protocol.TField TIME_STAMP_FIELD_DESC = new org.apache.thrift.protocol.TField("time_stamp", org.apache.thrift.protocol.TType.I64, (short)2);
private static final org.apache.thrift.protocol.TField USERS_FIELD_DESC = new org.apache.thrift.protocol.TField("users", org.apache.thrift.protocol.TType.LIST, (short)3);
private static final org.apache.thrift.protocol.TField GROUPS_FIELD_DESC = new org.apache.thrift.protocol.TField("groups", org.apache.thrift.protocol.TType.LIST, (short)4);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new LSTopoHistoryStandardSchemeFactory());
schemes.put(TupleScheme.class, new LSTopoHistoryTupleSchemeFactory());
}
private String topology_id; // required
private long time_stamp; // required
private List<String> users; // required
private List<String> groups; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
TOPOLOGY_ID((short)1, "topology_id"),
TIME_STAMP((short)2, "time_stamp"),
USERS((short)3, "users"),
GROUPS((short)4, "groups");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // TOPOLOGY_ID
return TOPOLOGY_ID;
case 2: // TIME_STAMP
return TIME_STAMP;
case 3: // USERS
return USERS;
case 4: // GROUPS
return GROUPS;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __TIME_STAMP_ISSET_ID = 0;
private byte __isset_bitfield = 0;
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.TOPOLOGY_ID, new org.apache.thrift.meta_data.FieldMetaData("topology_id", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.TIME_STAMP, new org.apache.thrift.meta_data.FieldMetaData("time_stamp", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
tmpMap.put(_Fields.USERS, new org.apache.thrift.meta_data.FieldMetaData("users", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))));
tmpMap.put(_Fields.GROUPS, new org.apache.thrift.meta_data.FieldMetaData("groups", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(LSTopoHistory.class, metaDataMap);
}
public LSTopoHistory() {
}
public LSTopoHistory(
String topology_id,
long time_stamp,
List<String> users,
List<String> groups)
{
this();
this.topology_id = topology_id;
this.time_stamp = time_stamp;
set_time_stamp_isSet(true);
this.users = users;
this.groups = groups;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public LSTopoHistory(LSTopoHistory other) {
__isset_bitfield = other.__isset_bitfield;
if (other.is_set_topology_id()) {
this.topology_id = other.topology_id;
}
this.time_stamp = other.time_stamp;
if (other.is_set_users()) {
List<String> __this__users = new ArrayList<String>(other.users);
this.users = __this__users;
}
if (other.is_set_groups()) {
List<String> __this__groups = new ArrayList<String>(other.groups);
this.groups = __this__groups;
}
}
public LSTopoHistory deepCopy() {
return new LSTopoHistory(this);
}
@Override
public void clear() {
this.topology_id = null;
set_time_stamp_isSet(false);
this.time_stamp = 0;
this.users = null;
this.groups = null;
}
public String get_topology_id() {
return this.topology_id;
}
public void set_topology_id(String topology_id) {
this.topology_id = topology_id;
}
public void unset_topology_id() {
this.topology_id = null;
}
/** Returns true if field topology_id is set (has been assigned a value) and false otherwise */
public boolean is_set_topology_id() {
return this.topology_id != null;
}
public void set_topology_id_isSet(boolean value) {
if (!value) {
this.topology_id = null;
}
}
public long get_time_stamp() {
return this.time_stamp;
}
public void set_time_stamp(long time_stamp) {
this.time_stamp = time_stamp;
set_time_stamp_isSet(true);
}
public void unset_time_stamp() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __TIME_STAMP_ISSET_ID);
}
/** Returns true if field time_stamp is set (has been assigned a value) and false otherwise */
public boolean is_set_time_stamp() {
return EncodingUtils.testBit(__isset_bitfield, __TIME_STAMP_ISSET_ID);
}
public void set_time_stamp_isSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __TIME_STAMP_ISSET_ID, value);
}
public int get_users_size() {
return (this.users == null) ? 0 : this.users.size();
}
public java.util.Iterator<String> get_users_iterator() {
return (this.users == null) ? null : this.users.iterator();
}
public void add_to_users(String elem) {
if (this.users == null) {
this.users = new ArrayList<String>();
}
this.users.add(elem);
}
public List<String> get_users() {
return this.users;
}
public void set_users(List<String> users) {
this.users = users;
}
public void unset_users() {
this.users = null;
}
/** Returns true if field users is set (has been assigned a value) and false otherwise */
public boolean is_set_users() {
return this.users != null;
}
public void set_users_isSet(boolean value) {
if (!value) {
this.users = null;
}
}
public int get_groups_size() {
return (this.groups == null) ? 0 : this.groups.size();
}
public java.util.Iterator<String> get_groups_iterator() {
return (this.groups == null) ? null : this.groups.iterator();
}
public void add_to_groups(String elem) {
if (this.groups == null) {
this.groups = new ArrayList<String>();
}
this.groups.add(elem);
}
public List<String> get_groups() {
return this.groups;
}
public void set_groups(List<String> groups) {
this.groups = groups;
}
public void unset_groups() {
this.groups = null;
}
/** Returns true if field groups is set (has been assigned a value) and false otherwise */
public boolean is_set_groups() {
return this.groups != null;
}
public void set_groups_isSet(boolean value) {
if (!value) {
this.groups = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case TOPOLOGY_ID:
if (value == null) {
unset_topology_id();
} else {
set_topology_id((String)value);
}
break;
case TIME_STAMP:
if (value == null) {
unset_time_stamp();
} else {
set_time_stamp((Long)value);
}
break;
case USERS:
if (value == null) {
unset_users();
} else {
set_users((List<String>)value);
}
break;
case GROUPS:
if (value == null) {
unset_groups();
} else {
set_groups((List<String>)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case TOPOLOGY_ID:
return get_topology_id();
case TIME_STAMP:
return get_time_stamp();
case USERS:
return get_users();
case GROUPS:
return get_groups();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case TOPOLOGY_ID:
return is_set_topology_id();
case TIME_STAMP:
return is_set_time_stamp();
case USERS:
return is_set_users();
case GROUPS:
return is_set_groups();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof LSTopoHistory)
return this.equals((LSTopoHistory)that);
return false;
}
public boolean equals(LSTopoHistory that) {
if (that == null)
return false;
boolean this_present_topology_id = true && this.is_set_topology_id();
boolean that_present_topology_id = true && that.is_set_topology_id();
if (this_present_topology_id || that_present_topology_id) {
if (!(this_present_topology_id && that_present_topology_id))
return false;
if (!this.topology_id.equals(that.topology_id))
return false;
}
boolean this_present_time_stamp = true;
boolean that_present_time_stamp = true;
if (this_present_time_stamp || that_present_time_stamp) {
if (!(this_present_time_stamp && that_present_time_stamp))
return false;
if (this.time_stamp != that.time_stamp)
return false;
}
boolean this_present_users = true && this.is_set_users();
boolean that_present_users = true && that.is_set_users();
if (this_present_users || that_present_users) {
if (!(this_present_users && that_present_users))
return false;
if (!this.users.equals(that.users))
return false;
}
boolean this_present_groups = true && this.is_set_groups();
boolean that_present_groups = true && that.is_set_groups();
if (this_present_groups || that_present_groups) {
if (!(this_present_groups && that_present_groups))
return false;
if (!this.groups.equals(that.groups))
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_topology_id = true && (is_set_topology_id());
list.add(present_topology_id);
if (present_topology_id)
list.add(topology_id);
boolean present_time_stamp = true;
list.add(present_time_stamp);
if (present_time_stamp)
list.add(time_stamp);
boolean present_users = true && (is_set_users());
list.add(present_users);
if (present_users)
list.add(users);
boolean present_groups = true && (is_set_groups());
list.add(present_groups);
if (present_groups)
list.add(groups);
return list.hashCode();
}
@Override
public int compareTo(LSTopoHistory other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(is_set_topology_id()).compareTo(other.is_set_topology_id());
if (lastComparison != 0) {
return lastComparison;
}
if (is_set_topology_id()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.topology_id, other.topology_id);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(is_set_time_stamp()).compareTo(other.is_set_time_stamp());
if (lastComparison != 0) {
return lastComparison;
}
if (is_set_time_stamp()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.time_stamp, other.time_stamp);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(is_set_users()).compareTo(other.is_set_users());
if (lastComparison != 0) {
return lastComparison;
}
if (is_set_users()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.users, other.users);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(is_set_groups()).compareTo(other.is_set_groups());
if (lastComparison != 0) {
return lastComparison;
}
if (is_set_groups()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.groups, other.groups);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("LSTopoHistory(");
boolean first = true;
sb.append("topology_id:");
if (this.topology_id == null) {
sb.append("null");
} else {
sb.append(this.topology_id);
}
first = false;
if (!first) sb.append(", ");
sb.append("time_stamp:");
sb.append(this.time_stamp);
first = false;
if (!first) sb.append(", ");
sb.append("users:");
if (this.users == null) {
sb.append("null");
} else {
sb.append(this.users);
}
first = false;
if (!first) sb.append(", ");
sb.append("groups:");
if (this.groups == null) {
sb.append("null");
} else {
sb.append(this.groups);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
if (!is_set_topology_id()) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'topology_id' is unset! Struct:" + toString());
}
if (!is_set_time_stamp()) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'time_stamp' is unset! Struct:" + toString());
}
if (!is_set_users()) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'users' is unset! Struct:" + toString());
}
if (!is_set_groups()) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'groups' is unset! Struct:" + toString());
}
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class LSTopoHistoryStandardSchemeFactory implements SchemeFactory {
public LSTopoHistoryStandardScheme getScheme() {
return new LSTopoHistoryStandardScheme();
}
}
private static class LSTopoHistoryStandardScheme extends StandardScheme<LSTopoHistory> {
public void read(org.apache.thrift.protocol.TProtocol iprot, LSTopoHistory struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // TOPOLOGY_ID
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.topology_id = iprot.readString();
struct.set_topology_id_isSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // TIME_STAMP
if (schemeField.type == org.apache.thrift.protocol.TType.I64) {
struct.time_stamp = iprot.readI64();
struct.set_time_stamp_isSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 3: // USERS
if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
{
org.apache.thrift.protocol.TList _list750 = iprot.readListBegin();
struct.users = new ArrayList<String>(_list750.size);
String _elem751;
for (int _i752 = 0; _i752 < _list750.size; ++_i752)
{
_elem751 = iprot.readString();
struct.users.add(_elem751);
}
iprot.readListEnd();
}
struct.set_users_isSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 4: // GROUPS
if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
{
org.apache.thrift.protocol.TList _list753 = iprot.readListBegin();
struct.groups = new ArrayList<String>(_list753.size);
String _elem754;
for (int _i755 = 0; _i755 < _list753.size; ++_i755)
{
_elem754 = iprot.readString();
struct.groups.add(_elem754);
}
iprot.readListEnd();
}
struct.set_groups_isSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, LSTopoHistory struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.topology_id != null) {
oprot.writeFieldBegin(TOPOLOGY_ID_FIELD_DESC);
oprot.writeString(struct.topology_id);
oprot.writeFieldEnd();
}
oprot.writeFieldBegin(TIME_STAMP_FIELD_DESC);
oprot.writeI64(struct.time_stamp);
oprot.writeFieldEnd();
if (struct.users != null) {
oprot.writeFieldBegin(USERS_FIELD_DESC);
{
oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, struct.users.size()));
for (String _iter756 : struct.users)
{
oprot.writeString(_iter756);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
if (struct.groups != null) {
oprot.writeFieldBegin(GROUPS_FIELD_DESC);
{
oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, struct.groups.size()));
for (String _iter757 : struct.groups)
{
oprot.writeString(_iter757);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class LSTopoHistoryTupleSchemeFactory implements SchemeFactory {
public LSTopoHistoryTupleScheme getScheme() {
return new LSTopoHistoryTupleScheme();
}
}
private static class LSTopoHistoryTupleScheme extends TupleScheme<LSTopoHistory> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, LSTopoHistory struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
oprot.writeString(struct.topology_id);
oprot.writeI64(struct.time_stamp);
{
oprot.writeI32(struct.users.size());
for (String _iter758 : struct.users)
{
oprot.writeString(_iter758);
}
}
{
oprot.writeI32(struct.groups.size());
for (String _iter759 : struct.groups)
{
oprot.writeString(_iter759);
}
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, LSTopoHistory struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
struct.topology_id = iprot.readString();
struct.set_topology_id_isSet(true);
struct.time_stamp = iprot.readI64();
struct.set_time_stamp_isSet(true);
{
org.apache.thrift.protocol.TList _list760 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, iprot.readI32());
struct.users = new ArrayList<String>(_list760.size);
String _elem761;
for (int _i762 = 0; _i762 < _list760.size; ++_i762)
{
_elem761 = iprot.readString();
struct.users.add(_elem761);
}
}
struct.set_users_isSet(true);
{
org.apache.thrift.protocol.TList _list763 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, iprot.readI32());
struct.groups = new ArrayList<String>(_list763.size);
String _elem764;
for (int _i765 = 0; _i765 < _list763.size; ++_i765)
{
_elem764 = iprot.readString();
struct.groups.add(_elem764);
}
}
struct.set_groups_isSet(true);
}
}
}
|
/*
* Copyright 2015-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.store.meter.impl;
import com.google.common.collect.Collections2;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang.math.RandomUtils;
import org.onlab.util.KryoNamespace;
import org.onosproject.cluster.ClusterService;
import org.onosproject.cluster.NodeId;
import org.onosproject.mastership.MastershipService;
import org.onosproject.net.DeviceId;
import org.onosproject.net.behaviour.MeterQuery;
import org.onosproject.net.driver.DriverHandler;
import org.onosproject.net.driver.DriverService;
import org.onosproject.net.meter.Band;
import org.onosproject.net.meter.DefaultBand;
import org.onosproject.net.meter.DefaultMeter;
import org.onosproject.net.meter.DefaultMeterFeatures;
import org.onosproject.net.meter.Meter;
import org.onosproject.net.meter.MeterEvent;
import org.onosproject.net.meter.MeterFailReason;
import org.onosproject.net.meter.MeterFeatures;
import org.onosproject.net.meter.MeterFeaturesFlag;
import org.onosproject.net.meter.MeterFeaturesKey;
import org.onosproject.net.meter.MeterId;
import org.onosproject.net.meter.MeterKey;
import org.onosproject.net.meter.MeterOperation;
import org.onosproject.net.meter.MeterState;
import org.onosproject.net.meter.MeterStore;
import org.onosproject.net.meter.MeterStoreDelegate;
import org.onosproject.net.meter.MeterStoreResult;
import org.onosproject.store.AbstractStore;
import org.onosproject.store.primitives.DefaultDistributedSet;
import org.onosproject.store.serializers.KryoNamespaces;
import org.onosproject.store.service.AtomicCounterMap;
import org.onosproject.store.service.ConsistentMap;
import org.onosproject.store.service.DistributedPrimitive;
import org.onosproject.store.service.DistributedSet;
import org.onosproject.store.service.MapEvent;
import org.onosproject.store.service.MapEventListener;
import org.onosproject.store.service.Serializer;
import org.onosproject.store.service.StorageException;
import org.onosproject.store.service.StorageService;
import org.onosproject.store.service.Versioned;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.slf4j.Logger;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import static org.onosproject.store.meter.impl.DistributedMeterStore.ReuseStrategy.FIRST_FIT;
import static org.onosproject.net.meter.MeterFailReason.TIMEOUT;
import static org.slf4j.LoggerFactory.getLogger;
/**
* A distributed meter store implementation. Meters are stored consistently
* across the cluster.
*/
@Component(immediate = true, service = MeterStore.class)
public class DistributedMeterStore extends AbstractStore<MeterEvent, MeterStoreDelegate>
implements MeterStore {
private Logger log = getLogger(getClass());
private static final String METERSTORE = "onos-meter-store";
private static final String METERFEATURESSTORE = "onos-meter-features-store";
private static final String AVAILABLEMETERIDSTORE = "onos-meters-available-store";
private static final String METERIDSTORE = "onos-meters-id-store";
private static final KryoNamespace.Builder APP_KRYO_BUILDER = KryoNamespace.newBuilder()
.register(KryoNamespaces.API)
.register(MeterKey.class)
.register(MeterData.class)
.register(DefaultMeter.class)
.register(DefaultBand.class)
.register(Band.Type.class)
.register(MeterState.class)
.register(Meter.Unit.class);
private Serializer serializer = Serializer.using(Lists.newArrayList(APP_KRYO_BUILDER.build()));
@Reference(cardinality = ReferenceCardinality.MANDATORY)
private StorageService storageService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
private MastershipService mastershipService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
private ClusterService clusterService;
@Reference(cardinality = ReferenceCardinality.MANDATORY)
protected DriverService driverService;
private ConsistentMap<MeterKey, MeterData> meters;
private NodeId local;
private ConsistentMap<MeterFeaturesKey, MeterFeatures> meterFeatures;
private MapEventListener<MeterKey, MeterData> mapListener = new InternalMapEventListener();
private Map<MeterKey, CompletableFuture<MeterStoreResult>> futures =
Maps.newConcurrentMap();
// Available meter identifiers
private DistributedSet<MeterKey> availableMeterIds;
// Atomic counter map for generation of new identifiers;
private AtomicCounterMap<DeviceId> meterIdGenerators;
/**
* Defines possible selection strategies to reuse meter ids.
*/
enum ReuseStrategy {
/**
* Select randomly an available id.
*/
RANDOM,
/**
* Select the first one.
*/
FIRST_FIT
}
private ReuseStrategy reuseStrategy = FIRST_FIT;
@Activate
public void activate() {
local = clusterService.getLocalNode().id();
meters = storageService.<MeterKey, MeterData>consistentMapBuilder()
.withName(METERSTORE)
.withSerializer(serializer).build();
meters.addListener(mapListener);
meterFeatures = storageService.<MeterFeaturesKey, MeterFeatures>consistentMapBuilder()
.withName(METERFEATURESSTORE)
.withSerializer(Serializer.using(KryoNamespaces.API,
MeterFeaturesKey.class,
MeterFeatures.class,
DefaultMeterFeatures.class,
Band.Type.class,
Meter.Unit.class,
MeterFailReason.class,
MeterFeaturesFlag.class)).build();
// Init the set of the available ids
availableMeterIds = new DefaultDistributedSet<>(storageService.<MeterKey>setBuilder()
.withName(AVAILABLEMETERIDSTORE)
.withSerializer(Serializer.using(KryoNamespaces.API,
MeterKey.class)).build(),
DistributedPrimitive.DEFAULT_OPERATION_TIMEOUT_MILLIS);
// Init atomic map counters
meterIdGenerators = storageService.<DeviceId>atomicCounterMapBuilder()
.withName(METERIDSTORE)
.withSerializer(Serializer.using(KryoNamespaces.API)).build();
log.info("Started");
}
@Deactivate
public void deactivate() {
meters.removeListener(mapListener);
log.info("Stopped");
}
@Override
public CompletableFuture<MeterStoreResult> storeMeter(Meter meter) {
// Init steps
CompletableFuture<MeterStoreResult> future = new CompletableFuture<>();
MeterKey key = MeterKey.key(meter.deviceId(), meter.id());
// Store the future related to the operation
futures.put(key, future);
// Store the meter data
MeterData data = new MeterData(meter, null, local);
try {
meters.put(key, data);
} catch (StorageException e) {
futures.remove(key);
future.completeExceptionally(e);
}
// Done, return the future
return future;
}
@Override
public CompletableFuture<MeterStoreResult> deleteMeter(Meter meter) {
// Init steps
CompletableFuture<MeterStoreResult> future = new CompletableFuture<>();
MeterKey key = MeterKey.key(meter.deviceId(), meter.id());
// Store the future related to the operation
futures.put(key, future);
// Create the meter data
MeterData data = new MeterData(meter, null, local);
// Update the state of the meter. It will be pruned by observing
// that it has been removed from the dataplane.
try {
// If it does not exist in the system
if (meters.computeIfPresent(key, (k, v) -> data) == null) {
// Complete immediately
future.complete(MeterStoreResult.success());
}
} catch (StorageException e) {
futures.remove(key);
future.completeExceptionally(e);
}
// Done, return the future
return future;
}
@Override
public MeterStoreResult storeMeterFeatures(MeterFeatures meterfeatures) {
MeterStoreResult result = MeterStoreResult.success();
MeterFeaturesKey key = MeterFeaturesKey.key(meterfeatures.deviceId());
try {
meterFeatures.putIfAbsent(key, meterfeatures);
} catch (StorageException e) {
result = MeterStoreResult.fail(TIMEOUT);
}
return result;
}
@Override
public MeterStoreResult deleteMeterFeatures(DeviceId deviceId) {
MeterStoreResult result = MeterStoreResult.success();
MeterFeaturesKey key = MeterFeaturesKey.key(deviceId);
try {
meterFeatures.remove(key);
} catch (StorageException e) {
result = MeterStoreResult.fail(TIMEOUT);
}
return result;
}
@Override
public CompletableFuture<MeterStoreResult> updateMeter(Meter meter) {
CompletableFuture<MeterStoreResult> future = new CompletableFuture<>();
MeterKey key = MeterKey.key(meter.deviceId(), meter.id());
futures.put(key, future);
MeterData data = new MeterData(meter, null, local);
try {
if (meters.computeIfPresent(key, (k, v) -> data) == null) {
future.complete(MeterStoreResult.fail(MeterFailReason.INVALID_METER));
}
} catch (StorageException e) {
futures.remove(key);
future.completeExceptionally(e);
}
return future;
}
@Override
public void updateMeterState(Meter meter) {
MeterKey key = MeterKey.key(meter.deviceId(), meter.id());
meters.computeIfPresent(key, (k, v) -> {
DefaultMeter m = (DefaultMeter) v.meter();
m.setState(meter.state());
m.setProcessedPackets(meter.packetsSeen());
m.setProcessedBytes(meter.bytesSeen());
m.setLife(meter.life());
// TODO: Prune if drops to zero.
m.setReferenceCount(meter.referenceCount());
if (meter.referenceCount() == 0) {
notifyDelegate(new MeterEvent(MeterEvent.Type.METER_REFERENCE_COUNT_ZERO, m));
}
return new MeterData(m, null, v.origin());
});
}
@Override
public Meter getMeter(MeterKey key) {
MeterData data = Versioned.valueOrElse(meters.get(key), null);
return data == null ? null : data.meter();
}
@Override
public Collection<Meter> getAllMeters() {
return Collections2.transform(meters.asJavaMap().values(),
MeterData::meter);
}
@Override
public Collection<Meter> getAllMeters(DeviceId deviceId) {
return Collections2.transform(
Collections2.filter(meters.asJavaMap().values(),
(MeterData m) -> m.meter().deviceId().equals(deviceId)),
MeterData::meter);
}
@Override
public void failedMeter(MeterOperation op, MeterFailReason reason) {
MeterKey key = MeterKey.key(op.meter().deviceId(), op.meter().id());
meters.computeIfPresent(key, (k, v) ->
new MeterData(v.meter(), reason, v.origin()));
}
@Override
public void deleteMeterNow(Meter m) {
// Create the key
MeterKey key = MeterKey.key(m.deviceId(), m.id());
// Remove the future
futures.remove(key);
// Remove the meter
meters.remove(key);
// Free the id
freeMeterId(m.deviceId(), m.id());
// Finally notify the delegate
notifyDelegate(new MeterEvent(MeterEvent.Type.METER_REMOVED, m));
}
@Override
public long getMaxMeters(MeterFeaturesKey key) {
MeterFeatures features = Versioned.valueOrElse(meterFeatures.get(key), null);
return features == null ? 0L : features.maxMeter();
}
// queryMaxMeters is implemented in FullMetersAvailable behaviour.
private long queryMaxMeters(DeviceId device) {
// Get driver handler for this device
DriverHandler handler = driverService.createHandler(device);
// If creation failed or the device does not have this behavior
if (handler == null || !handler.hasBehaviour(MeterQuery.class)) {
// We cannot know max meter
return 0L;
}
// Get the behavior
MeterQuery query = handler.behaviour(MeterQuery.class);
// Return as max meter the result of the query
return query.getMaxMeters();
}
private boolean updateMeterIdAvailability(DeviceId deviceId, MeterId id,
boolean available) {
// According to available, make available or unavailable a meter key
return available ? availableMeterIds.add(MeterKey.key(deviceId, id)) :
availableMeterIds.remove(MeterKey.key(deviceId, id));
}
private MeterId getNextAvailableId(Set<MeterId> availableIds) {
// If there are no available ids
if (availableIds.isEmpty()) {
// Just end the cycle
return null;
}
// If it is the first fit
if (reuseStrategy == FIRST_FIT || availableIds.size() == 1) {
return availableIds.iterator().next();
}
// If it is random, get the size
int size = availableIds.size();
// Return a random element
return Iterables.get(availableIds, RandomUtils.nextInt(size));
}
// Implements reuse strategy
private MeterId firstReusableMeterId(DeviceId deviceId) {
// Filter key related to device id, and reduce to meter ids
Set<MeterId> localAvailableMeterIds = availableMeterIds.stream()
.filter(meterKey -> meterKey.deviceId().equals(deviceId))
.map(MeterKey::meterId)
.collect(Collectors.toSet());
// Get next available id
MeterId meterId = getNextAvailableId(localAvailableMeterIds);
// Iterate until there are items
while (meterId != null) {
// If we are able to reserve the id
if (updateMeterIdAvailability(deviceId, meterId, false)) {
// Just end
return meterId;
}
// Update the set
localAvailableMeterIds.remove(meterId);
// Try another time
meterId = getNextAvailableId(localAvailableMeterIds);
}
// No reusable ids
return null;
}
@Override
public MeterId allocateMeterId(DeviceId deviceId) {
// Init steps
MeterId meterId;
long id;
// Try to reuse meter id
meterId = firstReusableMeterId(deviceId);
// We found a reusable id, return
if (meterId != null) {
return meterId;
}
// If there was no reusable MeterId we have to generate a new value
// using maxMeters as upper limit.
long maxMeters = getMaxMeters(MeterFeaturesKey.key(deviceId));
// If the device does not give us MeterFeatures
if (maxMeters == 0L) {
// MeterFeatures couldn't be retrieved, fallback to queryMeters.
maxMeters = queryMaxMeters(deviceId);
}
// If we don't know the max, cannot proceed
if (maxMeters == 0L) {
return null;
}
// Get a new value
id = meterIdGenerators.incrementAndGet(deviceId);
// Check with the max, and if the value is bigger, cannot proceed
if (id >= maxMeters) {
return null;
}
// Done, return the value
return MeterId.meterId(id);
}
@Override
public void freeMeterId(DeviceId deviceId, MeterId meterId) {
// Avoid to free meter not allocated
if (meterIdGenerators.get(deviceId) < meterId.id()) {
return;
}
// Update the availability
updateMeterIdAvailability(deviceId, meterId, true);
}
private class InternalMapEventListener implements MapEventListener<MeterKey, MeterData> {
@Override
public void event(MapEvent<MeterKey, MeterData> event) {
MeterKey key = event.key();
Versioned<MeterData> value = event.type() == MapEvent.Type.REMOVE ? event.oldValue() : event.newValue();
MeterData data = value.value();
NodeId master = mastershipService.getMasterFor(data.meter().deviceId());
switch (event.type()) {
case INSERT:
case UPDATE:
switch (data.meter().state()) {
case PENDING_ADD:
case PENDING_REMOVE:
if (!data.reason().isPresent() && local.equals(master)) {
notifyDelegate(
new MeterEvent(data.meter().state() == MeterState.PENDING_ADD ?
MeterEvent.Type.METER_ADD_REQ : MeterEvent.Type.METER_REM_REQ,
data.meter()));
} else if (data.reason().isPresent() && local.equals(data.origin())) {
MeterStoreResult msr = MeterStoreResult.fail(data.reason().get());
//TODO: No future -> no friend
futures.get(key).complete(msr);
}
break;
case ADDED:
if (local.equals(data.origin()) &&
(data.meter().state() == MeterState.PENDING_ADD
|| data.meter().state() == MeterState.ADDED)) {
futures.computeIfPresent(key, (k, v) -> {
v.complete(MeterStoreResult.success());
notifyDelegate(
new MeterEvent(MeterEvent.Type.METER_ADDED, data.meter()));
return null;
});
}
break;
case REMOVED:
if (local.equals(data.origin()) && data.meter().state() == MeterState.PENDING_REMOVE) {
futures.remove(key).complete(MeterStoreResult.success());
}
break;
default:
log.warn("Unknown meter state type {}", data.meter().state());
}
break;
case REMOVE:
//Only happens at origin so we do not need to care.
break;
default:
log.warn("Unknown Map event type {}", event.type());
}
}
}
}
|
package codechicken.enderstorage;
import codechicken.enderstorage.config.EnderStorageConfig;
import codechicken.enderstorage.init.ClientInit;
import codechicken.enderstorage.init.EnderStorageModContent;
import codechicken.enderstorage.manager.EnderStorageManager;
import codechicken.enderstorage.network.EnderStorageNetwork;
import codechicken.enderstorage.network.TankSynchroniser;
import codechicken.enderstorage.plugin.EnderItemStoragePlugin;
import codechicken.enderstorage.plugin.EnderLiquidStoragePlugin;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.DistExecutor;
import net.minecraftforge.fml.common.Mod;
import static codechicken.enderstorage.EnderStorage.MOD_ID;
@Mod (MOD_ID)
public class EnderStorage {
public static final String MOD_ID = "enderstorage";
public EnderStorage() {
EnderStorageConfig.load();
EnderStorageModContent.init();
DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> ClientInit::init);
EnderStorageNetwork.init();
EnderStorageManager.init();
EnderStorageManager.registerPlugin(new EnderItemStoragePlugin());
EnderStorageManager.registerPlugin(new EnderLiquidStoragePlugin());
MinecraftForge.EVENT_BUS.register(new EnderStorageManager.EnderStorageSaveHandler());
MinecraftForge.EVENT_BUS.register(new TankSynchroniser());
}
// @Mod.EventHandler
// public void serverStarting(FMLServerStartingEvent event) {
// event.registerServerCommand(new EnderStorageCommand());
// }
}
|
package burlap.domain.singleagent.tabularized;
import java.util.ArrayList;
import java.util.List;
import burlap.behavior.singleagent.auxiliary.StateEnumerator;
import burlap.oomdp.singleagent.FullActionModel;
import burlap.oomdp.singleagent.GroundedAction;
import burlap.oomdp.statehashing.HashableStateFactory;
import burlap.oomdp.auxiliary.DomainGenerator;
import burlap.oomdp.core.Attribute;
import burlap.oomdp.core.Attribute.AttributeType;
import burlap.oomdp.core.Domain;
import burlap.oomdp.core.ObjectClass;
import burlap.oomdp.core.objects.ObjectInstance;
import burlap.oomdp.core.states.State;
import burlap.oomdp.core.TransitionProbability;
import burlap.oomdp.core.objects.MutableObjectInstance;
import burlap.oomdp.core.states.MutableState;
import burlap.oomdp.singleagent.Action;
import burlap.oomdp.singleagent.SADomain;
/**
* In general, it is suggested algorithms be designed to work with either factored state representations or the BURLAP State Hashing. However,
* some algorithms may be limited to working with states that have explicit enumerated values and with an entire state space already defined. In particular,
* if you are interfacing with code external to BURLAP this may be required. This domain generator can take any input domain and turns it
* into a domain in which states are represented by a single int attribute and are fully enumerated.
* The state space used must be enumerated before calling the {@link #generateDomain()} method and is performed
* using a BURLAP state enumerator. In particular, seed states must be passed to this object and it will find all reachable states from the seed state
* and enumerate them.
* @author James MacGlashan
*
*/
public class TabulatedDomainWrapper implements DomainGenerator {
/**
* The single attribute name for identifying states
*/
public static final String ATTSTATE = "state";
/**
* The single class name that holds the state attribute
*/
public static final String CLASSSTATE = "state";
/**
* The input domain that is to be wrapped into a tabularized domain
*/
protected Domain inputDomain;
/**
* The output tabularied domain
*/
protected Domain tabDomain;
/**
* The state enumerator used for enumerating (or tabulating) all states
*/
protected StateEnumerator enumerator;
/**
* Constructs.
* @param inputDomain the input domain to be wrapped
* @param hashingFactory the hashing factory used to enumerate states from the input domain
*/
public TabulatedDomainWrapper(Domain inputDomain, HashableStateFactory hashingFactory){
this.inputDomain = inputDomain;
this.enumerator = new StateEnumerator(this.inputDomain, hashingFactory);
}
/**
* Enumerates all reachable states from the input state to include in this tabularized domain's state space.
* @param from the souce state from which to find and enumerate all reachable states
*/
public void addReachableStatesFrom(State from){
this.enumerator.findReachableStatesAndEnumerate(from);
}
@Override
public Domain generateDomain() {
this.tabDomain = new SADomain();
Attribute att = new Attribute(this.tabDomain, ATTSTATE, AttributeType.INT);
att.setLims(0, this.enumerator.numStatesEnumerated()-1);
ObjectClass oc = new ObjectClass(this.tabDomain, CLASSSTATE);
oc.addAttribute(att);
for(Action srcAction : this.inputDomain.getActions()){
new ActionWrapper(tabDomain, srcAction);
}
return tabDomain;
}
/**
* Returns the state id for a state beloning to the input source domain
* @param s the source domain state
* @return the state id
*/
public int getStateId(State s){
return s.getFirstObjectOfClass(CLASSSTATE).getIntValForAttribute(ATTSTATE);
}
/**
* Returns the source domain state associated with the tabularized state
* @param s the tabularized state
* @return the source domain state
*/
public State getSourceDomainState(State s){
int id = this.getStateId(s);
return this.enumerator.getStateForEnumerationId(id);
}
/**
* Returns a tabularized state for a source domain state
* @param s the source domain state
* @return the tabularized state
*/
public State getTabularizedState(State s){
int id = this.enumerator.getEnumeratedID(s);
State ts = new MutableState();
ObjectInstance o = new MutableObjectInstance(this.tabDomain.getObjectClass(CLASSSTATE), "state");
o.setValue(ATTSTATE, id);
ts.addObject(o);
return ts;
}
/**
* An action wrapper that coverts a tabularized state into the source domain state, perform the corresponding source domain action on it getting the
* resulting source domain state and returns the tabularized version of the resulting source domain state. Also wraps the preconditions and transition
* dynamics of the source domain action in similar ways.
* @author James MacGlashan
*
*/
public class ActionWrapper extends Action implements FullActionModel{
protected Action srcAction;
/**
* Constructs
* @param domain the tabularized domain
* @param action the source domain action to be wrapped
*/
public ActionWrapper(Domain domain, Action action){
super(action.getName(), domain);
this.srcAction = action;
}
@Override
public boolean applicableInState(State s, GroundedAction groundedAction){
return srcAction.applicableInState(TabulatedDomainWrapper.this.getSourceDomainState(s), groundedAction);
}
@Override
protected State performActionHelper(State s, GroundedAction groundedAction) {
State srcState = TabulatedDomainWrapper.this.getSourceDomainState(s);
State srcNextState = srcAction.performAction(srcState, groundedAction);
State tabState = TabulatedDomainWrapper.this.getTabularizedState(srcNextState);
return tabState;
}
@Override
public List<TransitionProbability> getTransitions(State s, GroundedAction groundedAction){
if(!(srcAction instanceof FullActionModel)){
throw new RuntimeException("Cannot return the transitions for " + srcAction.getName() + " because it does not implement FullActionModel");
}
State srcState = TabulatedDomainWrapper.this.getSourceDomainState(s);
List<TransitionProbability> srcTPs = ((FullActionModel)this.srcAction).getTransitions(srcState, groundedAction);
List<TransitionProbability> tabTPs = new ArrayList<TransitionProbability>(srcTPs.size());
for(TransitionProbability stp : srcTPs){
TransitionProbability ttp = new TransitionProbability(TabulatedDomainWrapper.this.getTabularizedState(stp.s), stp.p);
tabTPs.add(ttp);
}
return tabTPs;
}
@Override
public boolean isPrimitive() {
return srcAction.isPrimitive();
}
@Override
public boolean isParameterized() {
return srcAction.isParameterized();
}
@Override
public GroundedAction getAssociatedGroundedAction() {
GroundedAction ga = srcAction.getAssociatedGroundedAction();
ga.action = this;
return ga;
}
@Override
public List<GroundedAction> getAllApplicableGroundedActions(State s) {
List<GroundedAction> sourceSet = srcAction.getAllApplicableGroundedActions(s);
//adjust pointer to this action wrapper
for(GroundedAction ga : sourceSet){
ga.action = this;
}
return sourceSet;
}
}
}
|
/*
* 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.geode.internal.memcached;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;
import org.apache.geode.annotations.Immutable;
import org.apache.geode.internal.memcached.commands.AbstractCommand;
import org.apache.geode.internal.memcached.commands.ClientError;
import org.apache.geode.memcached.GemFireMemcachedServer.Protocol;
/**
* Reads the first line from the request and interprets the {@link Command} from the memcached
* client
*
*
*/
public class RequestReader {
@Immutable
private static final Charset charsetASCII = StandardCharsets.US_ASCII;
private static final ThreadLocal<CharsetDecoder> asciiDecoder =
new ThreadLocal<CharsetDecoder>() {
@Override
protected CharsetDecoder initialValue() {
return charsetASCII.newDecoder();
}
};
private ByteBuffer buffer;
private ByteBuffer response;
private static final int RESPONSE_HEADER_LENGTH = 24;
private static final byte RESPONSE_MAGIC = (byte) 0x81;
private static final int HEADER_LENGTH = 24;
private static final byte REQUEST_MAGIC = (byte) 0x80;
private static final int POSITION_OPCODE = 1;
private static final int POSITION_OPAQUE = 12;
private final Socket socket;
private final Protocol protocol;
private final CharBuffer commandBuffer = CharBuffer.allocate(11); // no command exceeds 9 chars
public RequestReader(Socket socket, Protocol protocol) {
buffer = ByteBuffer.allocate(getBufferSize(socket.getChannel()));
// set position to limit so that first read attempt
// returns hasRemaining() false
buffer.position(buffer.limit());
this.socket = socket;
this.protocol = protocol;
}
public Command readCommand() throws IOException {
if (protocol == Protocol.ASCII) {
return readAsciiCommand();
}
return readBinaryCommand();
}
private Command readBinaryCommand() throws IOException {
SocketChannel channel = socket.getChannel();
if (channel == null || !channel.isOpen()) {
throw new IllegalStateException("cannot read from channel");
}
Command cmd = null;
boolean done = false;
boolean read = false;
while (!done) {
if (!buffer.hasRemaining()) {
buffer.clear();
read = true;
} else if (!read) {
// compact is meant for partial writes, but we want to use
// it partial reads, so the new limit should be the position
// after the compact operation and we want to start reading
// from the beginning
buffer.compact();
buffer.limit(buffer.position());
buffer.position(0);
}
if (read) {
int bytesRead = channel.read(buffer);
if (bytesRead == -1) {
throw new IOException("EOF");
}
buffer.flip();
}
// read again if we did not read enough bytes
if (buffer.limit() < HEADER_LENGTH) {
buffer.compact();
read = true;
continue;
}
int requestLength = buffer.remaining();
byte magic = buffer.get();
if (magic != REQUEST_MAGIC) {
throw new IllegalStateException("Not a valid request, magic byte incorrect");
}
byte opCode = buffer.get();
if (ConnectionHandler.getLogger().finerEnabled()) {
String str = Command.buffertoString(buffer);
ConnectionHandler.getLogger().finer("Request:" + buffer + str);
}
int bodyLength = buffer.getInt(AbstractCommand.TOTAL_BODY_LENGTH_INDEX);
if ((HEADER_LENGTH + bodyLength) > requestLength) {
// set the position back to the start of the request
buffer.position(buffer.position() - 2 /* since we read two bytes */);
buffer.compact();
// ensure that the buffer is big enough
if (buffer.capacity() < (HEADER_LENGTH + bodyLength)) {
// allocate bigger buffer and copy the bytes to the bigger buffer
ByteBuffer oldBuffer = buffer;
oldBuffer.position(0);
buffer = ByteBuffer.allocate(HEADER_LENGTH + bodyLength);
buffer.put(oldBuffer);
}
read = true;
continue;
}
cmd = Command.getCommandFromOpCode(opCode);
done = true;
}
if (ConnectionHandler.getLogger().fineEnabled()) {
ConnectionHandler.getLogger().fine("read command " + cmd);
}
return cmd;
}
private Command readAsciiCommand() throws IOException {
SocketChannel channel = socket.getChannel();
if (channel == null || !channel.isOpen()) {
throw new IllegalStateException("cannot read from channel");
}
buffer.clear();
int bytesRead = channel.read(buffer);
if (bytesRead == -1) {
throw new IOException("EOF");
}
buffer.flip();
return Command.valueOf(readCommand(buffer));
}
private String readCommand(ByteBuffer buffer) throws CharacterCodingException {
commandBuffer.clear();
asciiDecoder.get().decode(buffer, commandBuffer, false);
commandBuffer.flip();
return trimCommand(commandBuffer.toString()).toUpperCase();
}
private String trimCommand(String str) {
int indexOfSpace = str.indexOf(' ');
String retVal = str;
if (indexOfSpace != -1) {
retVal = str.substring(0, indexOfSpace);
}
int indexOfR = retVal.indexOf("\r");
if (indexOfR != -1) {
retVal = retVal.substring(0, indexOfR);
}
if (retVal.equals("")) {
if (ConnectionHandler.getLogger().infoEnabled()) {
// TODO i18n
ConnectionHandler.getLogger().info("Unknown command. ensure client protocol is ASCII");
}
throw new IllegalArgumentException("Unknown command. ensure client protocol is ASCII");
}
return retVal;
}
private int getBufferSize(SocketChannel channel) {
int size = 1024;
try {
size = channel.socket().getReceiveBufferSize();
} catch (SocketException e) {
// use default size
}
return size;
}
public ByteBuffer getRequest() {
buffer.rewind();
return buffer;
}
public ByteBuffer getResponse() {
return getResponse(RESPONSE_HEADER_LENGTH);
}
/**
* Returns an initialized byteBuffer for sending the reply
*
* @param size size of ByteBuffer
* @return the initialized response buffer
*/
public ByteBuffer getResponse(int size) {
if (response == null || response.capacity() < size) {
response = ByteBuffer.allocate(size);
}
clear(response);
response.put(RESPONSE_MAGIC);
response.rewind();
response.limit(size);
return response;
}
private void clear(ByteBuffer response) {
response.position(0);
response.limit(response.capacity());
response.put(getCleanByteArray());
while (response.remaining() > getCleanByteArray().length) {
response.put(getCleanByteArray());
}
while (response.remaining() > 0) {
response.put((byte) 0);
}
response.clear();
}
@Immutable
private static final byte[] cleanByteArray = createCleanByteArray();
private static byte[] createCleanByteArray() {
byte[] cleanByteArray = new byte[RESPONSE_HEADER_LENGTH];
for (int i = 0; i < cleanByteArray.length; i++) {
cleanByteArray[i] = 0;
}
return cleanByteArray;
}
private byte[] getCleanByteArray() {
return cleanByteArray;
}
public void sendReply(ByteBuffer reply) throws IOException {
// for binary set the response opCode
if (protocol == Protocol.BINARY) {
reply.rewind();
reply.put(POSITION_OPCODE, buffer.get(POSITION_OPCODE));
reply.putInt(POSITION_OPAQUE, buffer.getInt(POSITION_OPAQUE));
if (ConnectionHandler.getLogger().finerEnabled()) {
ConnectionHandler.getLogger()
.finer("sending reply:" + reply + " " + Command.buffertoString(reply));
}
}
SocketChannel channel = socket.getChannel();
if (channel == null || !channel.isOpen()) {
throw new IllegalStateException("cannot write to channel");
}
channel.write(reply);
}
public void sendException(Exception e) {
SocketChannel channel = socket.getChannel();
if (channel == null || !channel.isOpen()) {
throw new IllegalStateException("cannot write to channel");
}
try {
if (e instanceof ClientError) {
channel.write(charsetASCII.encode(Reply.CLIENT_ERROR.toString()));
} else {
channel.write(charsetASCII.encode(Reply.ERROR.toString()));
}
} catch (IOException ignored) {
}
}
}
|
package com.zcwfeng.sourcestudy.androidsourcestudystudio.mprogressbar;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.PointF;
import android.os.Build;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.BounceInterpolator;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.zcwfeng.sourcestudy.androidsourcestudystudio.R;
import java.util.ArrayList;
import java.util.List;
/**
* Created by liangfeizc on 6/28/15.
*/
public class RubberIndicator extends RelativeLayout {
private static final String TAG = "RubberIndicator";
private static final int SMALL_CIRCLE_COLOR = 0xFFDF8D81;
private static final int LARGE_CIRCLE_COLOR = 0xFFAF3854;
private static final int OUTER_CIRCLE_COLOR = 0xFF533456;
private static final int SMALL_CIRCLE_RADIUS = 20;
private static final int LARGE_CIRCLE_RADIUS = 25;
private static final int OUTER_CIRCLE_RADIUS = 50;
private static final int BEZIER_CURVE_ANCHOR_DISTANCE = 30;
private static final int CIRCLE_TYPE_SMALL = 0x00;
private static final int CIRCLE_TYPE_LARGE = 0x01;
private static final int CIRCLE_TYPE_OUTER = 0x02;
/**
* colors
*/
private int mSmallCircleColor;
private int mLargeCircleColor;
private int mOuterCircleColor;
/**
* coordinate values
*/
private int mSmallCircleRadius;
private int mLargeCircleRadius;
private int mOuterCircleRadius;
/**
* views
*/
private LinearLayout mContainer;
private CircleView mLargeCircle;
private CircleView mSmallCircle;
private CircleView mOuterCircle;
private List<CircleView> mCircleViews;
/**
* animations
*/
private AnimatorSet mAnim;
private PropertyValuesHolder mPvhScaleX;
private PropertyValuesHolder mPvhScaleY;
private PropertyValuesHolder mPvhScale;
private PropertyValuesHolder mPvhRotation;
/**
* Movement Path
*/
private Path mSmallCirclePath;
/**
* Indicator movement listener
*/
private OnMoveListener mOnMoveListener;
/**
* Helper values
*/
private int mFocusPosition = -1;
private int mBezierCurveAnchorDistance = dp2px(BEZIER_CURVE_ANCHOR_DISTANCE);
public RubberIndicator(Context context) {
super(context);
init();
}
public RubberIndicator(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
/** Initialize views */
View rootView = inflate(getContext(), R.layout.rubber_indicator, this);
mContainer = (LinearLayout) rootView.findViewById(R.id.container);
mOuterCircle = (CircleView) rootView.findViewById(R.id.outer_circle);
/** values */
mSmallCircleColor = SMALL_CIRCLE_COLOR;
mLargeCircleColor = LARGE_CIRCLE_COLOR;
mOuterCircleColor = OUTER_CIRCLE_COLOR;
mSmallCircleRadius = dp2px(SMALL_CIRCLE_RADIUS);
mLargeCircleRadius = dp2px(LARGE_CIRCLE_RADIUS);
mOuterCircleRadius = dp2px(OUTER_CIRCLE_RADIUS);
/** animators */
mPvhScaleX = PropertyValuesHolder.ofFloat("scaleX", 1, 0.8f, 1);
mPvhScaleY = PropertyValuesHolder.ofFloat("scaleY", 1, 0.8f, 1);
mPvhScale = PropertyValuesHolder.ofFloat("scaleY", 1, 0.5f, 1);
mPvhRotation = PropertyValuesHolder.ofFloat("rotation", 0);
mSmallCirclePath = new Path();
/** circle view list */
mCircleViews = new ArrayList<>();
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
mOuterCircle.setCenter(mLargeCircle.getCenter());
}
public void setCount(int count) {
if (mFocusPosition == -1) {
mFocusPosition = 0;
}
setCount(count, mFocusPosition);
}
/**
* This method must be called before {@link #setCount(int)}, otherwise the focus position will
* be set to the default value - zero.
* @param pos the focus position
*/
public void setFocusPosition(final int pos) {
mFocusPosition = pos;
}
public void setCount(int count, int focusPos) {
if (count < 2) {
throw new IllegalArgumentException("count must be greater than 2");
}
if (focusPos >= count) {
throw new IllegalArgumentException("focus position must be less than count");
}
int i = 0;
for (; i < focusPos; i++) {
addSmallCircle();
}
addLargeCircle();
for (i = focusPos + 1; i < count; i++) {
addSmallCircle();
}
mFocusPosition = focusPos;
}
public int getFocusPosition() {
return mFocusPosition;
}
public void moveToLeft() {
if (mAnim != null && mAnim.isRunning()) return;
move(false);
}
public void moveToRight() {
if (mAnim != null && mAnim.isRunning()) return;
move(true);
}
public void setOnMoveListener(final OnMoveListener moveListener) {
mOnMoveListener = moveListener;
}
private void addSmallCircle() {
CircleView smallCircle = createCircleView(CIRCLE_TYPE_SMALL);
mCircleViews.add(smallCircle);
mContainer.addView(smallCircle);
}
private void addLargeCircle() {
mLargeCircle = createCircleView(CIRCLE_TYPE_LARGE);
mCircleViews.add(mLargeCircle);
mContainer.addView(mLargeCircle);
}
private CircleView createCircleView(int type) {
CircleView circleView = new CircleView(getContext());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.weight = 1;
params.gravity = Gravity.CENTER_VERTICAL;
switch (type) {
case CIRCLE_TYPE_SMALL:
params.height = params.width = mSmallCircleRadius << 1;
circleView.setColor(mSmallCircleColor);
break;
case CIRCLE_TYPE_LARGE:
params.height = params.width = mLargeCircleRadius << 1;
circleView.setColor(mLargeCircleColor);
break;
case CIRCLE_TYPE_OUTER:
params.height = params.width = mOuterCircleRadius << 1;
circleView.setColor(mOuterCircleColor);
break;
}
circleView.setLayoutParams(params);
return circleView;
}
private int getNextPosition(boolean toRight) {
int nextPos = mFocusPosition + (toRight ? 1 : -1);
if (nextPos < 0 || nextPos >= mCircleViews.size()) return -1;
return nextPos;
}
private void swapCircles(int currentPos, int nextPos) {
CircleView circleView = mCircleViews.get(currentPos);
mCircleViews.set(currentPos, mCircleViews.get(nextPos));
mCircleViews.set(nextPos, circleView);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void move(final boolean toRight) {
final int nextPos = getNextPosition(toRight);
if (nextPos == -1) return;
mSmallCircle = mCircleViews.get(nextPos);
// Calculate the new x coordinate for circles.
float smallCircleX = toRight ? mLargeCircle.getX()
: mLargeCircle.getX() + mLargeCircle.getWidth() - mSmallCircle.getWidth();
float largeCircleX = toRight ?
mSmallCircle.getX() + mSmallCircle.getWidth() - mLargeCircle.getWidth() : mSmallCircle.getX();
float outerCircleX = mOuterCircle.getX() + largeCircleX - mLargeCircle.getX();
// animations for large circle and outer circle.
PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("x", mLargeCircle.getX(), largeCircleX);
ObjectAnimator largeCircleAnim = ObjectAnimator.ofPropertyValuesHolder(
mLargeCircle, pvhX, mPvhScaleX, mPvhScaleY);
pvhX = PropertyValuesHolder.ofFloat("x", mOuterCircle.getX(), outerCircleX);
ObjectAnimator outerCircleAnim = ObjectAnimator.ofPropertyValuesHolder(
mOuterCircle, pvhX, mPvhScaleX, mPvhScaleY);
// Animations for small circle
PointF smallCircleCenter = mSmallCircle.getCenter();
PointF smallCircleEndCenter = new PointF(
smallCircleCenter.x - (mSmallCircle.getX() - smallCircleX), smallCircleCenter.y);
// Create motion anim for small circle.
mSmallCirclePath.reset();
mSmallCirclePath.moveTo(smallCircleCenter.x, smallCircleCenter.y);
mSmallCirclePath.quadTo(smallCircleCenter.x, smallCircleCenter.y,
(smallCircleCenter.x + smallCircleEndCenter.x) / 2,
(smallCircleCenter.y + smallCircleEndCenter.y) / 2 + mBezierCurveAnchorDistance);
mSmallCirclePath.lineTo(smallCircleEndCenter.x, smallCircleEndCenter.y);
ValueAnimator smallCircleAnim;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
smallCircleAnim = ObjectAnimator.ofObject(mSmallCircle, "center", null, mSmallCirclePath);
} else {
final PathMeasure pathMeasure = new PathMeasure(mSmallCirclePath, false);
final float[] point = new float[2];
smallCircleAnim = ValueAnimator.ofFloat(0.0f, 1.0f);
smallCircleAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
pathMeasure.getPosTan(
pathMeasure.getLength() * animation.getAnimatedFraction(), point, null);
mSmallCircle.setCenter(new PointF(point[0], point[1]));
}
});
}
mPvhRotation.setFloatValues(0, toRight ? -30f : 30f, 0, toRight ? 30f : -30f, 0);
ObjectAnimator otherAnim = ObjectAnimator.ofPropertyValuesHolder(mSmallCircle, mPvhRotation, mPvhScale);
mAnim = new AnimatorSet();
mAnim.play(smallCircleAnim)
.with(otherAnim).with(largeCircleAnim).with(outerCircleAnim);
mAnim.setInterpolator(new AccelerateDecelerateInterpolator());
mAnim.setDuration(500);
mAnim.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) { }
@Override
public void onAnimationEnd(Animator animation) {
swapCircles(mFocusPosition, nextPos);
mFocusPosition = nextPos;
if (mOnMoveListener != null) {
if (toRight) {
mOnMoveListener.onMovedToRight();
} else {
mOnMoveListener.onMovedToLeft();
}
}
}
@Override
public void onAnimationCancel(Animator animation) { }
@Override
public void onAnimationRepeat(Animator animation) { }
});
mAnim.start();
}
private int dp2px(int dpValue) {
return (int) getContext().getResources().getDisplayMetrics().density * dpValue;
}
public interface OnMoveListener {
void onMovedToLeft();
void onMovedToRight();
}
}
|
package org.kohsuke.github.extras.okhttp3;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.kohsuke.github.AbstractGitHubWireMockTest;
import org.kohsuke.github.GHRateLimit;
import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GitHub;
import java.io.File;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;
/**
* Test showing the behavior of OkHttpConnector with and without cache.
* <p>
* Key take aways:
*
* <ul>
* <li>These tests are artificial and intended to highlight the differences in behavior between scenarios. However, the
* differences they indicate are stark.</li>
* <li>Caching reduces rate limit consumption by at least a factor of two in even the simplest case.</li>
* <li>The OkHttp cache is pretty smart and will often connect read and write requests made on the same client and
* invalidate caches.</li>
* <li>Changes made outside the current client cause the OkHttp cache to return stale data. This is expected and correct
* behavior.</li>
* <li>"max-age=0" addresses the problem of external changes by revalidating caches for each request. This produces the
* same number of requests as OkHttp without caching, but those requests only count towards the GitHub rate limit if
* data has changes.</li>
* </ul>
*
* @author Liam Newman
*/
public class OkHttpConnectorTest extends AbstractGitHubWireMockTest {
public OkHttpConnectorTest() {
useDefaultGitHub = false;
}
private static int defaultRateLimitUsed = 17;
private static int okhttpRateLimitUsed = 17;
private static int maxAgeZeroRateLimitUsed = 7;
private static int maxAgeThreeRateLimitUsed = 7;
private static int maxAgeNoneRateLimitUsed = 4;
private static int userRequestCount = 0;
private static int defaultNetworkRequestCount = 16;
private static int okhttpNetworkRequestCount = 16;
private static int maxAgeZeroNetworkRequestCount = 16;
private static int maxAgeThreeNetworkRequestCount = 9;
private static int maxAgeNoneNetworkRequestCount = 5;
private static int maxAgeZeroHitCount = 10;
private static int maxAgeThreeHitCount = 10;
private static int maxAgeNoneHitCount = 11;
private GHRateLimit rateLimitBefore;
private Cache cache = null;
@Override
protected WireMockConfiguration getWireMockOptions() {
return super.getWireMockOptions()
// Use the same data files as the 2.x test
.usingFilesUnderDirectory(baseRecordPath.replace("/okhttp3/", "/"))
.extensions(templating.newResponseTransformer());
}
@Before
public void setupRepo() throws Exception {
if (mockGitHub.isUseProxy()) {
GHRepository repo = getRepository(getNonRecordingGitHub());
repo.setDescription("Resetting");
// Let things settle a bit between tests when working against the live site
Thread.sleep(5000);
userRequestCount = 1;
}
}
@After
public void deleteCache() throws IOException {
if (cache != null) {
cache.delete();
}
}
@Test
public void DefaultConnector() throws Exception {
this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()).build();
doTestActions();
// Testing behavior after change
// Uncached connection gets updated correctly but at cost of rate limit
assertThat(getRepository(gitHub).getDescription(), is("Tricky"));
checkRequestAndLimit(defaultNetworkRequestCount, defaultRateLimitUsed);
}
@Test
public void OkHttpConnector_NoCache() throws Exception {
OkHttpClient client = createClient(false);
OkHttpConnector connector = new OkHttpConnector(client);
this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl())
.withConnector(connector)
.build();
doTestActions();
// Testing behavior after change
// Uncached okhttp connection gets updated correctly but at cost of rate limit
assertThat(getRepository(gitHub).getDescription(), is("Tricky"));
checkRequestAndLimit(okhttpNetworkRequestCount, okhttpRateLimitUsed);
assertThat("Cache", cache, is(nullValue()));
}
@Test
public void OkHttpConnector_Cache_MaxAgeNone() throws Exception {
// The responses were recorded from github, but the Date headers
// have been templated to make caching behavior work as expected.
// This is reasonable as long as the number of network requests matches up.
snapshotNotAllowed();
OkHttpClient client = createClient(true);
OkHttpConnector connector = new OkHttpConnector(client, -1);
this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl())
.withConnector(connector)
.build();
doTestActions();
// Testing behavior after change
// NOTE: this is wrong! The live data changed!
// Due to max-age (default 60 from response) the cache returns the old data.
assertThat(getRepository(gitHub).getDescription(), is(mockGitHub.getMethodName()));
checkRequestAndLimit(maxAgeNoneNetworkRequestCount, maxAgeNoneRateLimitUsed);
// NOTE: this is actually bad.
// This elevated hit count is the stale requests returning bad data took longer to detect a change.
assertThat("getHitCount", cache.hitCount(), is(maxAgeNoneHitCount));
}
@Test
public void OkHttpConnector_Cache_MaxAge_Three() throws Exception {
// NOTE: This test is very timing sensitive.
// It can be run locally to verify behavior but snapshot data is to touchy
assumeFalse("Test only valid when not taking a snapshot", mockGitHub.isTakeSnapshot());
assumeTrue("Test only valid when proxying (-Dtest.github.useProxy to enable)", mockGitHub.isUseProxy());
OkHttpClient client = createClient(true);
OkHttpConnector connector = new OkHttpConnector(client, 3);
this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl())
.withConnector(connector)
.build();
doTestActions();
// Due to max-age=3 this eventually checks the site and gets updated information. Yay?
assertThat(getRepository(gitHub).getDescription(), is("Tricky"));
checkRequestAndLimit(maxAgeThreeNetworkRequestCount, maxAgeThreeRateLimitUsed);
assertThat("getHitCount", cache.hitCount(), is(maxAgeThreeHitCount));
}
@Test
public void OkHttpConnector_Cache_MaxAgeDefault_Zero() throws Exception {
// The responses were recorded from github, but the Date headers
// have been templated to make caching behavior work as expected.
// This is reasonable as long as the number of network requests matches up.
snapshotNotAllowed();
OkHttpClient client = createClient(true);
OkHttpConnector connector = new OkHttpConnector(client);
this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl())
.withConnector(connector)
.build();
doTestActions();
// Testing behavior after change
// NOTE: max-age=0 produces the same result at uncached without added rate-limit use.
assertThat(getRepository(gitHub).getDescription(), is("Tricky"));
checkRequestAndLimit(maxAgeZeroNetworkRequestCount, maxAgeZeroRateLimitUsed);
assertThat("getHitCount", cache.hitCount(), is(maxAgeZeroHitCount));
}
private void checkRequestAndLimit(int networkRequestCount, int rateLimitUsed) throws IOException {
GHRateLimit rateLimitAfter = gitHub.rateLimit();
assertThat("Request Count", getRequestCount(), is(networkRequestCount + userRequestCount));
// Rate limit must be under this value, but if it wiggles we don't care
assertThat("Rate Limit Change",
rateLimitBefore.remaining - rateLimitAfter.remaining,
is(lessThanOrEqualTo(rateLimitUsed + userRequestCount)));
}
private int getRequestCount() {
return mockGitHub.apiServer().countRequestsMatching(RequestPatternBuilder.allRequests().build()).getCount();
}
private OkHttpClient createClient(boolean useCache) throws IOException {
OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
if (useCache) {
File cacheDir = new File("target/cache/" + baseFilesClassPath + "/" + mockGitHub.getMethodName());
cacheDir.mkdirs();
FileUtils.cleanDirectory(cacheDir);
cache = new Cache(cacheDir, 100 * 1024L * 1024L);
builder.cache(cache);
}
return builder.build();
}
/**
* This is a standard set of actions to be performed with each connector
*
* @throws Exception
*/
private void doTestActions() throws Exception {
rateLimitBefore = gitHub.getRateLimit();
String name = mockGitHub.getMethodName();
GHRepository repo = getRepository(gitHub);
// Testing behavior when nothing has changed.
pollForChange("Resetting");
assertThat(getRepository(gitHub).getDescription(), is("Resetting"));
repo.setDescription(name);
pollForChange(name);
// Test behavior after change
assertThat(getRepository(gitHub).getDescription(), is(name));
// Get Tricky - make a change via a different client
if (mockGitHub.isUseProxy()) {
GHRepository altRepo = getRepository(getNonRecordingGitHub());
altRepo.setDescription("Tricky");
}
// Testing behavior after change
pollForChange("Tricky");
}
private void pollForChange(String name) throws IOException, InterruptedException {
getRepository(gitHub).getDescription();
Thread.sleep(500);
getRepository(gitHub).getDescription();
// This is only interesting when running the max-age=3 test which currently only runs with proxy
// Disabled to speed up the tests
if (mockGitHub.isUseProxy()) {
Thread.sleep(1000);
}
getRepository(gitHub).getDescription();
// This is only interesting when running the max-age=3 test which currently only runs with proxy
// Disabled to speed up the tests
if (mockGitHub.isUseProxy()) {
Thread.sleep(4000);
}
}
private static GHRepository getRepository(GitHub gitHub) throws IOException {
return gitHub.getOrganization("hub4j-test-org").getRepository("github-api");
}
}
|
/*
* Copyright 2017 - 2020 Roman Borris (pcfreak9000), Paul Hagedorn (Panzer1119)
*
* 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 de.omnikryptec.libapi.openal;
import java.lang.reflect.Field;
import javax.sound.sampled.AudioFormat;
import org.lwjgl.openal.AL10;
import org.lwjgl.openal.AL11;
import de.omnikryptec.libapi.exposed.LibAPIManager;
import de.omnikryptec.util.Logger;
/**
*
* @author Panzer1119 & pcfreak9000
*/
public class OpenALUtil {
private static final Logger logger = Logger.getLogger(OpenALUtil.class);
public static final int MONO = 1;
public static final int STEREO = 2;
public static final int audioFormatToOpenALFormat(AudioFormat audioFormat) {
return audioFormatToOpenALFormat(audioFormat.getChannels(), audioFormat.getSampleSizeInBits());
}
public static final int audioFormatToOpenALFormat(int channels, int sampleSizeInBits) {
int openALFormat = -1;
switch (channels) {
case MONO:
switch (sampleSizeInBits) {
case 8:
openALFormat = AL10.AL_FORMAT_MONO8;
break;
case 16:
openALFormat = AL10.AL_FORMAT_MONO16;
break;
}
break;
case STEREO:
switch (sampleSizeInBits) {
case 8:
openALFormat = AL10.AL_FORMAT_STEREO8;
break;
case 16:
openALFormat = AL10.AL_FORMAT_STEREO16;
break;
}
break;
}
return openALFormat;
}
public static int booleanToOpenAL(boolean b) {
return b ? AL10.AL_TRUE : AL10.AL_FALSE;
}
public static void flushErrors() {
int e = 0;
int found = 0;
while ((e = AL10.alGetError()) != AL10.AL_NO_ERROR) {
logger.error("OpenAL error: " + (LibAPIManager.debug() ? searchConstants(e) : e));
found++;
}
if (found != 0) {
throw new RuntimeException("Found " + found + " OpenAL error(s)");
}
if (found == 0) {
logger.debug("No OpenAL errors found!");
}
}
private static final Class<?>[] constantsClasses = { AL10.class, AL11.class };
private static String searchConstants(final int i) {
for (final Class<?> c : constantsClasses) {
final Field[] fields = c.getFields();
for (final Field f : fields) {
try {
if (i == f.getInt(null)) {
return f.getName();
}
} catch (final IllegalArgumentException e) {
} catch (final IllegalAccessException e) {
}
}
}
throw new IllegalArgumentException("Constant with value '" + i + "' not found");
}
}
|
package ru.job4j.chess.exceptions;
public class ImpossibleMoveException extends RuntimeException {
public ImpossibleMoveException() {
}
}
|
package br.com.zupacademy.fpsaraiva.casadocodigo.compartilhado;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = ValorUnicoValidator.class)
public @interface ValorUnico {
String message() default "Valor inválido.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String fieldName();
Class<?> domainClass();
}
|
/*
* Copyright 1999-2017 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.druid.bvt.sql.sqlserver.select;
import java.util.List;
import junit.framework.TestCase;
import org.junit.Assert;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.statement.SQLSelect;
import com.alibaba.druid.sql.ast.statement.SQLSelectStatement;
import com.alibaba.druid.sql.dialect.sqlserver.ast.SQLServerSelectQueryBlock;
import com.alibaba.druid.sql.dialect.sqlserver.parser.SQLServerStatementParser;
import com.alibaba.druid.sql.dialect.sqlserver.visitor.SQLServerSchemaStatVisitor;
import com.alibaba.druid.util.JdbcUtils;
public class SQLServerSelectTest_cross_apply extends TestCase {
public void test_0() throws Exception {
String sql = "SELECT DeptID, DeptName, DeptMgrID, EmpID, EmpLastName, EmpSalary FROM Departments d CROSS APPLY dbo.GetReports(d.DeptMgrID)";
SQLServerStatementParser parser = new SQLServerStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
SQLSelectStatement selectStmt = (SQLSelectStatement) stmt;
SQLSelect select = selectStmt.getSelect();
Assert.assertNotNull(select.getQuery());
SQLServerSelectQueryBlock queryBlock = (SQLServerSelectQueryBlock) select.getQuery();
Assert.assertNull(queryBlock.getGroupBy());
String fomatSQL = SQLUtils.toSQLString(statementList, JdbcUtils.SQL_SERVER);
// System.out.println(fomatSQL);
Assert.assertEquals(1, statementList.size());
SQLServerSchemaStatVisitor visitor = new SQLServerSchemaStatVisitor();
stmt.accept(visitor);
// System.out.println("Tables : " + visitor.getTables());
// System.out.println("fields : " + visitor.getColumns());
// System.out.println("coditions : " + visitor.getConditions());
// System.out.println("orderBy : " + visitor.getOrderByColumns());
Assert.assertEquals(1, visitor.getTables().size());
Assert.assertEquals(7, visitor.getColumns().size());
Assert.assertEquals(0, visitor.getConditions().size());
Assert.assertEquals(0, visitor.getOrderByColumns().size());
String expected = "SELECT DeptID, DeptName, DeptMgrID, EmpID, EmpLastName"//
+ "\n\t, EmpSalary"//
+ "\nFROM Departments d" //
+ "\n\tCROSS APPLY dbo.GetReports(d.DeptMgrID)";
Assert.assertEquals(expected, fomatSQL);
}
}
|
/*
* Copyright (c) 2005-2022 Xceptance Software Technologies GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.xceptance.xlt.report;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.function.Predicate;
import org.junit.Test;
import com.xceptance.xlt.common.XltConstants;
public class DataRecordReaderTest
{
/**
* Ensures that the filter catches the valid timer file names only.
*/
@Test
public void timerFilter()
{
final Predicate<String> p = s -> XltConstants.TIMER_FILENAME_PATTERNS.stream().anyMatch(r -> r.asPredicate().test(s));
assertTrue(p.test("timers.csv"));
assertTrue(p.test("timers.csv.gz"));
assertTrue(p.test("timers.csv.2012-01-01"));
assertTrue(p.test("timers.csv.2012-01-01.gz"));
assertFalse(p.test("timer-wd-57362576329865634278.csv"));
assertFalse(p.test("timer-wd-57362576329865634278.csv.gz"));
assertFalse(p.test("atimers.csv"));
assertFalse(p.test("timers.gz"));
assertFalse(p.test("timers.2020.csv"));
assertFalse(p.test("Timers.csv"));
}
/**
* Ensures that the filter catches the valid CPT timer file names only.
*/
@Test
public void timerWDFilter()
{
final Predicate<String> p = s -> XltConstants.CPT_TIMER_FILENAME_PATTERNS.stream().anyMatch(r -> r.asPredicate().test(s));
assertTrue(p.test("timer-wd-57362576329865634278.csv"));
assertTrue(p.test("timer-wd-57362576329865634278.csv.gz"));
assertFalse(p.test("timers.csv"));
assertFalse(p.test("timers.csv.gz"));
assertFalse(p.test("timers.csv.2012-01-01"));
assertFalse(p.test("timers.csv.2012-01-01.gz"));
assertFalse(p.test("timer-wd.csv"));
assertFalse(p.test("timer-wd.csv.gz"));
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.client;
import static org.apache.hadoop.hbase.TableName.META_TABLE_NAME;
import static org.apache.hadoop.hbase.util.FutureUtils.addListener;
import static org.apache.hadoop.hbase.util.FutureUtils.unwrapCompletionException;
import com.google.protobuf.Message;
import com.google.protobuf.RpcChannel;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.AsyncMetaTableAccessor;
import org.apache.hadoop.hbase.CacheEvictionStats;
import org.apache.hadoop.hbase.CacheEvictionStatsAggregator;
import org.apache.hadoop.hbase.ClusterMetrics;
import org.apache.hadoop.hbase.ClusterMetrics.Option;
import org.apache.hadoop.hbase.ClusterMetricsBuilder;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.MetaTableAccessor;
import org.apache.hadoop.hbase.MetaTableAccessor.QueryType;
import org.apache.hadoop.hbase.NamespaceDescriptor;
import org.apache.hadoop.hbase.RegionLocations;
import org.apache.hadoop.hbase.RegionMetrics;
import org.apache.hadoop.hbase.RegionMetricsBuilder;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.TableExistsException;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.TableNotDisabledException;
import org.apache.hadoop.hbase.TableNotEnabledException;
import org.apache.hadoop.hbase.TableNotFoundException;
import org.apache.hadoop.hbase.UnknownRegionException;
import org.apache.hadoop.hbase.client.AsyncRpcRetryingCallerFactory.AdminRequestCallerBuilder;
import org.apache.hadoop.hbase.client.AsyncRpcRetryingCallerFactory.MasterRequestCallerBuilder;
import org.apache.hadoop.hbase.client.AsyncRpcRetryingCallerFactory.ServerRequestCallerBuilder;
import org.apache.hadoop.hbase.client.Scan.ReadType;
import org.apache.hadoop.hbase.client.replication.ReplicationPeerConfigUtil;
import org.apache.hadoop.hbase.client.replication.TableCFs;
import org.apache.hadoop.hbase.client.security.SecurityCapability;
import org.apache.hadoop.hbase.exceptions.DeserializationException;
import org.apache.hadoop.hbase.ipc.HBaseRpcController;
import org.apache.hadoop.hbase.quotas.QuotaFilter;
import org.apache.hadoop.hbase.quotas.QuotaSettings;
import org.apache.hadoop.hbase.quotas.QuotaTableUtil;
import org.apache.hadoop.hbase.replication.ReplicationException;
import org.apache.hadoop.hbase.replication.ReplicationPeerConfig;
import org.apache.hadoop.hbase.replication.ReplicationPeerDescription;
import org.apache.hadoop.hbase.snapshot.ClientSnapshotDescriptionUtils;
import org.apache.hadoop.hbase.snapshot.RestoreSnapshotException;
import org.apache.hadoop.hbase.snapshot.SnapshotCreationException;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
import org.apache.hadoop.hbase.util.ForeignExceptionUtil;
import org.apache.yetus.audience.InterfaceAudience;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
import org.apache.hbase.thirdparty.com.google.common.base.Preconditions;
import org.apache.hbase.thirdparty.com.google.protobuf.RpcCallback;
import org.apache.hbase.thirdparty.io.netty.util.HashedWheelTimer;
import org.apache.hbase.thirdparty.io.netty.util.Timeout;
import org.apache.hbase.thirdparty.io.netty.util.TimerTask;
import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
import org.apache.hadoop.hbase.shaded.protobuf.RequestConverter;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.AdminService;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ClearCompactionQueuesRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ClearCompactionQueuesResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ClearRegionBlockCacheRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ClearRegionBlockCacheResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.CompactRegionRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.CompactRegionResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.FlushRegionRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.FlushRegionResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetOnlineRegionRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetOnlineRegionResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetRegionInfoRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetRegionInfoResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetRegionLoadRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetRegionLoadResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.RollWALWriterRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.RollWALWriterResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.StopServerRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.StopServerResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.UpdateConfigurationRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.UpdateConfigurationResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.ProcedureDescription;
import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.RegionSpecifier.RegionSpecifierType;
import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.TableSchema;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.AbortProcedureRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.AbortProcedureResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.AddColumnRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.AddColumnResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.AssignRegionRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.AssignRegionResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.BalanceRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.BalanceResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ClearDeadServersRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ClearDeadServersResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.CreateNamespaceRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.CreateNamespaceResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.CreateTableRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.CreateTableResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DecommissionRegionServersRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DecommissionRegionServersResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteColumnRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteColumnResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteNamespaceRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteNamespaceResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteSnapshotRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteSnapshotResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteTableRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DeleteTableResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DisableTableRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.DisableTableResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.EnableCatalogJanitorRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.EnableCatalogJanitorResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.EnableTableRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.EnableTableResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ExecProcedureRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ExecProcedureResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetClusterStatusRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetClusterStatusResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetCompletedSnapshotsRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetCompletedSnapshotsResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetLocksRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetLocksResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetNamespaceDescriptorRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetNamespaceDescriptorResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetProcedureResultRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetProcedureResultResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetProceduresRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetProceduresResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetTableDescriptorsRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetTableDescriptorsResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetTableNamesRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetTableNamesResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsBalancerEnabledRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsBalancerEnabledResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsCatalogJanitorEnabledRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsCatalogJanitorEnabledResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsCleanerChoreEnabledRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsCleanerChoreEnabledResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsInMaintenanceModeRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsInMaintenanceModeResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsNormalizerEnabledRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsNormalizerEnabledResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsProcedureDoneRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsProcedureDoneResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsSnapshotDoneRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsSnapshotDoneResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsSplitOrMergeEnabledRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.IsSplitOrMergeEnabledResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListDecommissionedRegionServersRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListDecommissionedRegionServersResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListNamespaceDescriptorsRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListNamespaceDescriptorsResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListTableDescriptorsByNamespaceRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListTableDescriptorsByNamespaceResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListTableNamesByNamespaceRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListTableNamesByNamespaceResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MajorCompactionTimestampForRegionRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MajorCompactionTimestampRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MajorCompactionTimestampResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MasterService;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MergeTableRegionsRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MergeTableRegionsResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ModifyColumnRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ModifyColumnResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ModifyNamespaceRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ModifyNamespaceResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ModifyTableRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ModifyTableResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MoveRegionRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MoveRegionResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.NormalizeRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.NormalizeResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.OfflineRegionRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.OfflineRegionResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.RecommissionRegionServerRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.RecommissionRegionServerResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.RestoreSnapshotRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.RestoreSnapshotResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.RunCatalogScanRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.RunCatalogScanResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.RunCleanerChoreRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.RunCleanerChoreResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SecurityCapabilitiesRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SecurityCapabilitiesResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetBalancerRunningRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetBalancerRunningResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetCleanerChoreRunningRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetCleanerChoreRunningResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetNormalizerRunningRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetNormalizerRunningResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetQuotaRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetQuotaResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetSplitOrMergeEnabledRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SetSplitOrMergeEnabledResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ShutdownRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ShutdownResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SnapshotRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SnapshotResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SplitTableRegionRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.SplitTableRegionResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.StopMasterRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.StopMasterResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.TruncateTableRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.TruncateTableResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.UnassignRegionRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.UnassignRegionResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.AddReplicationPeerRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.AddReplicationPeerResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.DisableReplicationPeerRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.DisableReplicationPeerResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.EnableReplicationPeerRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.EnableReplicationPeerResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.GetReplicationPeerConfigRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.GetReplicationPeerConfigResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.ListReplicationPeersRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.ListReplicationPeersResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.RemoveReplicationPeerRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.RemoveReplicationPeerResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.UpdateReplicationPeerConfigRequest;
import org.apache.hadoop.hbase.shaded.protobuf.generated.ReplicationProtos.UpdateReplicationPeerConfigResponse;
import org.apache.hadoop.hbase.shaded.protobuf.generated.SnapshotProtos;
/**
* The implementation of AsyncAdmin.
* <p>
* The word 'Raw' means that this is a low level class. The returned {@link CompletableFuture} will
* be finished inside the rpc framework thread, which means that the callbacks registered to the
* {@link CompletableFuture} will also be executed inside the rpc framework thread. So users who use
* this class should not try to do time consuming tasks in the callbacks.
* @since 2.0.0
* @see AsyncHBaseAdmin
* @see AsyncConnection#getAdmin()
* @see AsyncConnection#getAdminBuilder()
*/
@InterfaceAudience.Private
class RawAsyncHBaseAdmin implements AsyncAdmin {
public static final String FLUSH_TABLE_PROCEDURE_SIGNATURE = "flush-table-proc";
private static final Logger LOG = LoggerFactory.getLogger(AsyncHBaseAdmin.class);
private final AsyncConnectionImpl connection;
private final HashedWheelTimer retryTimer;
private final AsyncTable<AdvancedScanResultConsumer> metaTable;
private final long rpcTimeoutNs;
private final long operationTimeoutNs;
private final long pauseNs;
private final int maxAttempts;
private final int startLogErrorsCnt;
private final NonceGenerator ng;
RawAsyncHBaseAdmin(AsyncConnectionImpl connection, HashedWheelTimer retryTimer,
AsyncAdminBuilderBase builder) {
this.connection = connection;
this.retryTimer = retryTimer;
this.metaTable = connection.getTable(META_TABLE_NAME);
this.rpcTimeoutNs = builder.rpcTimeoutNs;
this.operationTimeoutNs = builder.operationTimeoutNs;
this.pauseNs = builder.pauseNs;
this.maxAttempts = builder.maxAttempts;
this.startLogErrorsCnt = builder.startLogErrorsCnt;
this.ng = connection.getNonceGenerator();
}
private <T> MasterRequestCallerBuilder<T> newMasterCaller() {
return this.connection.callerFactory.<T> masterRequest()
.rpcTimeout(rpcTimeoutNs, TimeUnit.NANOSECONDS)
.operationTimeout(operationTimeoutNs, TimeUnit.NANOSECONDS)
.pause(pauseNs, TimeUnit.NANOSECONDS).maxAttempts(maxAttempts)
.startLogErrorsCnt(startLogErrorsCnt);
}
private <T> AdminRequestCallerBuilder<T> newAdminCaller() {
return this.connection.callerFactory.<T> adminRequest()
.rpcTimeout(rpcTimeoutNs, TimeUnit.NANOSECONDS)
.operationTimeout(operationTimeoutNs, TimeUnit.NANOSECONDS)
.pause(pauseNs, TimeUnit.NANOSECONDS).maxAttempts(maxAttempts)
.startLogErrorsCnt(startLogErrorsCnt);
}
@FunctionalInterface
private interface MasterRpcCall<RESP, REQ> {
void call(MasterService.Interface stub, HBaseRpcController controller, REQ req,
RpcCallback<RESP> done);
}
@FunctionalInterface
private interface AdminRpcCall<RESP, REQ> {
void call(AdminService.Interface stub, HBaseRpcController controller, REQ req,
RpcCallback<RESP> done);
}
@FunctionalInterface
private interface Converter<D, S> {
D convert(S src) throws IOException;
}
private <PREQ, PRESP, RESP> CompletableFuture<RESP> call(HBaseRpcController controller,
MasterService.Interface stub, PREQ preq, MasterRpcCall<PRESP, PREQ> rpcCall,
Converter<RESP, PRESP> respConverter) {
CompletableFuture<RESP> future = new CompletableFuture<>();
rpcCall.call(stub, controller, preq, new RpcCallback<PRESP>() {
@Override
public void run(PRESP resp) {
if (controller.failed()) {
future.completeExceptionally(controller.getFailed());
} else {
try {
future.complete(respConverter.convert(resp));
} catch (IOException e) {
future.completeExceptionally(e);
}
}
}
});
return future;
}
private <PREQ, PRESP, RESP> CompletableFuture<RESP> adminCall(HBaseRpcController controller,
AdminService.Interface stub, PREQ preq, AdminRpcCall<PRESP, PREQ> rpcCall,
Converter<RESP, PRESP> respConverter) {
CompletableFuture<RESP> future = new CompletableFuture<>();
rpcCall.call(stub, controller, preq, new RpcCallback<PRESP>() {
@Override
public void run(PRESP resp) {
if (controller.failed()) {
future.completeExceptionally(controller.getFailed());
} else {
try {
future.complete(respConverter.convert(resp));
} catch (IOException e) {
future.completeExceptionally(e);
}
}
}
});
return future;
}
private <PREQ, PRESP> CompletableFuture<Void> procedureCall(PREQ preq,
MasterRpcCall<PRESP, PREQ> rpcCall, Converter<Long, PRESP> respConverter,
ProcedureBiConsumer consumer) {
CompletableFuture<Long> procFuture =
this.<Long> newMasterCaller().action((controller, stub) -> this
.<PREQ, PRESP, Long> call(controller, stub, preq, rpcCall, respConverter)).call();
CompletableFuture<Void> future = waitProcedureResult(procFuture);
addListener(future, consumer);
return future;
}
@FunctionalInterface
private interface TableOperator {
CompletableFuture<Void> operate(TableName table);
}
@Override
public CompletableFuture<Boolean> tableExists(TableName tableName) {
if (TableName.isMetaTableName(tableName)) {
return CompletableFuture.completedFuture(true);
}
return AsyncMetaTableAccessor.tableExists(metaTable, tableName);
}
@Override
public CompletableFuture<List<TableDescriptor>> listTableDescriptors(boolean includeSysTables) {
return getTableDescriptors(RequestConverter.buildGetTableDescriptorsRequest(null,
includeSysTables));
}
/**
* {@link #listTableDescriptors(boolean)}
*/
@Override
public CompletableFuture<List<TableDescriptor>> listTableDescriptors(Pattern pattern,
boolean includeSysTables) {
Preconditions.checkNotNull(pattern,
"pattern is null. If you don't specify a pattern, use listTables(boolean) instead");
return getTableDescriptors(RequestConverter.buildGetTableDescriptorsRequest(pattern,
includeSysTables));
}
private CompletableFuture<List<TableDescriptor>>
getTableDescriptors(GetTableDescriptorsRequest request) {
return this.<List<TableDescriptor>> newMasterCaller()
.action((controller, stub) -> this
.<GetTableDescriptorsRequest, GetTableDescriptorsResponse, List<TableDescriptor>> call(
controller, stub, request, (s, c, req, done) -> s.getTableDescriptors(c, req, done),
(resp) -> ProtobufUtil.toTableDescriptorList(resp)))
.call();
}
@Override
public CompletableFuture<List<TableName>> listTableNames(boolean includeSysTables) {
return getTableNames(RequestConverter.buildGetTableNamesRequest(null, includeSysTables));
}
@Override
public CompletableFuture<List<TableName>>
listTableNames(Pattern pattern, boolean includeSysTables) {
Preconditions.checkNotNull(pattern,
"pattern is null. If you don't specify a pattern, use listTableNames(boolean) instead");
return getTableNames(RequestConverter.buildGetTableNamesRequest(pattern, includeSysTables));
}
private CompletableFuture<List<TableName>> getTableNames(GetTableNamesRequest request) {
return this
.<List<TableName>> newMasterCaller()
.action(
(controller, stub) -> this
.<GetTableNamesRequest, GetTableNamesResponse, List<TableName>> call(controller,
stub, request, (s, c, req, done) -> s.getTableNames(c, req, done),
(resp) -> ProtobufUtil.toTableNameList(resp.getTableNamesList()))).call();
}
@Override
public CompletableFuture<List<TableDescriptor>> listTableDescriptorsByNamespace(String name) {
return this.<List<TableDescriptor>> newMasterCaller().action((controller, stub) -> this
.<ListTableDescriptorsByNamespaceRequest, ListTableDescriptorsByNamespaceResponse,
List<TableDescriptor>> call(
controller, stub,
ListTableDescriptorsByNamespaceRequest.newBuilder().setNamespaceName(name).build(),
(s, c, req, done) -> s.listTableDescriptorsByNamespace(c, req, done),
(resp) -> ProtobufUtil.toTableDescriptorList(resp)))
.call();
}
@Override
public CompletableFuture<List<TableName>> listTableNamesByNamespace(String name) {
return this.<List<TableName>> newMasterCaller().action((controller, stub) -> this
.<ListTableNamesByNamespaceRequest, ListTableNamesByNamespaceResponse,
List<TableName>> call(
controller, stub,
ListTableNamesByNamespaceRequest.newBuilder().setNamespaceName(name).build(),
(s, c, req, done) -> s.listTableNamesByNamespace(c, req, done),
(resp) -> ProtobufUtil.toTableNameList(resp.getTableNameList())))
.call();
}
@Override
public CompletableFuture<TableDescriptor> getDescriptor(TableName tableName) {
CompletableFuture<TableDescriptor> future = new CompletableFuture<>();
addListener(this.<List<TableSchema>> newMasterCaller()
.action((controller, stub) -> this
.<GetTableDescriptorsRequest, GetTableDescriptorsResponse, List<TableSchema>> call(
controller, stub, RequestConverter.buildGetTableDescriptorsRequest(tableName),
(s, c, req, done) -> s.getTableDescriptors(c, req, done),
(resp) -> resp.getTableSchemaList()))
.call(), (tableSchemas, error) -> {
if (error != null) {
future.completeExceptionally(error);
return;
}
if (!tableSchemas.isEmpty()) {
future.complete(ProtobufUtil.toTableDescriptor(tableSchemas.get(0)));
} else {
future.completeExceptionally(new TableNotFoundException(tableName.getNameAsString()));
}
});
return future;
}
@Override
public CompletableFuture<Void> createTable(TableDescriptor desc) {
return createTable(desc.getTableName(),
RequestConverter.buildCreateTableRequest(desc, null, ng.getNonceGroup(), ng.newNonce()));
}
@Override
public CompletableFuture<Void> createTable(TableDescriptor desc, byte[] startKey, byte[] endKey,
int numRegions) {
try {
return createTable(desc, getSplitKeys(startKey, endKey, numRegions));
} catch (IllegalArgumentException e) {
return failedFuture(e);
}
}
@Override
public CompletableFuture<Void> createTable(TableDescriptor desc, byte[][] splitKeys) {
Preconditions.checkNotNull(splitKeys, "splitKeys is null. If you don't specify splitKeys,"
+ " use createTable(TableDescriptor) instead");
try {
verifySplitKeys(splitKeys);
return createTable(desc.getTableName(), RequestConverter.buildCreateTableRequest(desc,
splitKeys, ng.getNonceGroup(), ng.newNonce()));
} catch (IllegalArgumentException e) {
return failedFuture(e);
}
}
private CompletableFuture<Void> createTable(TableName tableName, CreateTableRequest request) {
Preconditions.checkNotNull(tableName, "table name is null");
return this.<CreateTableRequest, CreateTableResponse> procedureCall(request,
(s, c, req, done) -> s.createTable(c, req, done), (resp) -> resp.getProcId(),
new CreateTableProcedureBiConsumer(tableName));
}
@Override
public CompletableFuture<Void> modifyTable(TableDescriptor desc) {
return this.<ModifyTableRequest, ModifyTableResponse> procedureCall(
RequestConverter.buildModifyTableRequest(desc.getTableName(), desc, ng.getNonceGroup(),
ng.newNonce()), (s, c, req, done) -> s.modifyTable(c, req, done),
(resp) -> resp.getProcId(), new ModifyTableProcedureBiConsumer(this, desc.getTableName()));
}
@Override
public CompletableFuture<Void> deleteTable(TableName tableName) {
return this.<DeleteTableRequest, DeleteTableResponse> procedureCall(RequestConverter
.buildDeleteTableRequest(tableName, ng.getNonceGroup(), ng.newNonce()),
(s, c, req, done) -> s.deleteTable(c, req, done), (resp) -> resp.getProcId(),
new DeleteTableProcedureBiConsumer(tableName));
}
@Override
public CompletableFuture<Void> truncateTable(TableName tableName, boolean preserveSplits) {
return this.<TruncateTableRequest, TruncateTableResponse> procedureCall(
RequestConverter.buildTruncateTableRequest(tableName, preserveSplits, ng.getNonceGroup(),
ng.newNonce()), (s, c, req, done) -> s.truncateTable(c, req, done),
(resp) -> resp.getProcId(), new TruncateTableProcedureBiConsumer(tableName));
}
@Override
public CompletableFuture<Void> enableTable(TableName tableName) {
return this.<EnableTableRequest, EnableTableResponse> procedureCall(RequestConverter
.buildEnableTableRequest(tableName, ng.getNonceGroup(), ng.newNonce()),
(s, c, req, done) -> s.enableTable(c, req, done), (resp) -> resp.getProcId(),
new EnableTableProcedureBiConsumer(tableName));
}
@Override
public CompletableFuture<Void> disableTable(TableName tableName) {
return this.<DisableTableRequest, DisableTableResponse> procedureCall(RequestConverter
.buildDisableTableRequest(tableName, ng.getNonceGroup(), ng.newNonce()),
(s, c, req, done) -> s.disableTable(c, req, done), (resp) -> resp.getProcId(),
new DisableTableProcedureBiConsumer(tableName));
}
@Override
public CompletableFuture<Boolean> isTableEnabled(TableName tableName) {
if (TableName.isMetaTableName(tableName)) {
return CompletableFuture.completedFuture(true);
}
CompletableFuture<Boolean> future = new CompletableFuture<>();
addListener(AsyncMetaTableAccessor.getTableState(metaTable, tableName), (state, error) -> {
if (error != null) {
future.completeExceptionally(error);
return;
}
if (state.isPresent()) {
future.complete(state.get().inStates(TableState.State.ENABLED));
} else {
future.completeExceptionally(new TableNotFoundException(tableName));
}
});
return future;
}
@Override
public CompletableFuture<Boolean> isTableDisabled(TableName tableName) {
if (TableName.isMetaTableName(tableName)) {
return CompletableFuture.completedFuture(false);
}
CompletableFuture<Boolean> future = new CompletableFuture<>();
addListener(AsyncMetaTableAccessor.getTableState(metaTable, tableName), (state, error) -> {
if (error != null) {
future.completeExceptionally(error);
return;
}
if (state.isPresent()) {
future.complete(state.get().inStates(TableState.State.DISABLED));
} else {
future.completeExceptionally(new TableNotFoundException(tableName));
}
});
return future;
}
@Override
public CompletableFuture<Boolean> isTableAvailable(TableName tableName) {
return isTableAvailable(tableName, Optional.empty());
}
@Override
public CompletableFuture<Boolean> isTableAvailable(TableName tableName, byte[][] splitKeys) {
Preconditions.checkNotNull(splitKeys, "splitKeys is null. If you don't specify splitKeys,"
+ " use isTableAvailable(TableName) instead");
return isTableAvailable(tableName, Optional.of(splitKeys));
}
private CompletableFuture<Boolean> isTableAvailable(TableName tableName,
Optional<byte[][]> splitKeys) {
if (TableName.isMetaTableName(tableName)) {
return connection.registry.getMetaRegionLocation().thenApply(locs -> Stream
.of(locs.getRegionLocations()).allMatch(loc -> loc != null && loc.getServerName() != null));
}
CompletableFuture<Boolean> future = new CompletableFuture<>();
addListener(isTableEnabled(tableName), (enabled, error) -> {
if (error != null) {
if (error instanceof TableNotFoundException) {
future.complete(false);
} else {
future.completeExceptionally(error);
}
return;
}
if (!enabled) {
future.complete(false);
} else {
addListener(
AsyncMetaTableAccessor.getTableHRegionLocations(metaTable, Optional.of(tableName)),
(locations, error1) -> {
if (error1 != null) {
future.completeExceptionally(error1);
return;
}
List<HRegionLocation> notDeployedRegions = locations.stream()
.filter(loc -> loc.getServerName() == null).collect(Collectors.toList());
if (notDeployedRegions.size() > 0) {
if (LOG.isDebugEnabled()) {
LOG.debug("Table " + tableName + " has " + notDeployedRegions.size() + " regions");
}
future.complete(false);
return;
}
Optional<Boolean> available =
splitKeys.map(keys -> compareRegionsWithSplitKeys(locations, keys));
future.complete(available.orElse(true));
});
}
});
return future;
}
private boolean compareRegionsWithSplitKeys(List<HRegionLocation> locations, byte[][] splitKeys) {
int regionCount = 0;
for (HRegionLocation location : locations) {
RegionInfo info = location.getRegion();
if (Bytes.equals(info.getStartKey(), HConstants.EMPTY_BYTE_ARRAY)) {
regionCount++;
continue;
}
for (byte[] splitKey : splitKeys) {
// Just check if the splitkey is available
if (Bytes.equals(info.getStartKey(), splitKey)) {
regionCount++;
break;
}
}
}
return regionCount == splitKeys.length + 1;
}
@Override
public CompletableFuture<Void> addColumnFamily(TableName tableName, ColumnFamilyDescriptor columnFamily) {
return this.<AddColumnRequest, AddColumnResponse> procedureCall(
RequestConverter.buildAddColumnRequest(tableName, columnFamily, ng.getNonceGroup(),
ng.newNonce()), (s, c, req, done) -> s.addColumn(c, req, done), (resp) -> resp.getProcId(),
new AddColumnFamilyProcedureBiConsumer(tableName));
}
@Override
public CompletableFuture<Void> deleteColumnFamily(TableName tableName, byte[] columnFamily) {
return this.<DeleteColumnRequest, DeleteColumnResponse> procedureCall(
RequestConverter.buildDeleteColumnRequest(tableName, columnFamily, ng.getNonceGroup(),
ng.newNonce()), (s, c, req, done) -> s.deleteColumn(c, req, done),
(resp) -> resp.getProcId(), new DeleteColumnFamilyProcedureBiConsumer(tableName));
}
@Override
public CompletableFuture<Void> modifyColumnFamily(TableName tableName,
ColumnFamilyDescriptor columnFamily) {
return this.<ModifyColumnRequest, ModifyColumnResponse> procedureCall(
RequestConverter.buildModifyColumnRequest(tableName, columnFamily, ng.getNonceGroup(),
ng.newNonce()), (s, c, req, done) -> s.modifyColumn(c, req, done),
(resp) -> resp.getProcId(), new ModifyColumnFamilyProcedureBiConsumer(tableName));
}
@Override
public CompletableFuture<Void> createNamespace(NamespaceDescriptor descriptor) {
return this.<CreateNamespaceRequest, CreateNamespaceResponse> procedureCall(
RequestConverter.buildCreateNamespaceRequest(descriptor),
(s, c, req, done) -> s.createNamespace(c, req, done), (resp) -> resp.getProcId(),
new CreateNamespaceProcedureBiConsumer(descriptor.getName()));
}
@Override
public CompletableFuture<Void> modifyNamespace(NamespaceDescriptor descriptor) {
return this.<ModifyNamespaceRequest, ModifyNamespaceResponse> procedureCall(
RequestConverter.buildModifyNamespaceRequest(descriptor),
(s, c, req, done) -> s.modifyNamespace(c, req, done), (resp) -> resp.getProcId(),
new ModifyNamespaceProcedureBiConsumer(descriptor.getName()));
}
@Override
public CompletableFuture<Void> deleteNamespace(String name) {
return this.<DeleteNamespaceRequest, DeleteNamespaceResponse> procedureCall(
RequestConverter.buildDeleteNamespaceRequest(name),
(s, c, req, done) -> s.deleteNamespace(c, req, done), (resp) -> resp.getProcId(),
new DeleteNamespaceProcedureBiConsumer(name));
}
@Override
public CompletableFuture<NamespaceDescriptor> getNamespaceDescriptor(String name) {
return this
.<NamespaceDescriptor> newMasterCaller()
.action(
(controller, stub) -> this
.<GetNamespaceDescriptorRequest, GetNamespaceDescriptorResponse, NamespaceDescriptor> call(
controller, stub, RequestConverter.buildGetNamespaceDescriptorRequest(name), (s, c,
req, done) -> s.getNamespaceDescriptor(c, req, done), (resp) -> ProtobufUtil
.toNamespaceDescriptor(resp.getNamespaceDescriptor()))).call();
}
@Override
public CompletableFuture<List<NamespaceDescriptor>> listNamespaceDescriptors() {
return this
.<List<NamespaceDescriptor>> newMasterCaller()
.action(
(controller, stub) -> this
.<ListNamespaceDescriptorsRequest, ListNamespaceDescriptorsResponse, List<NamespaceDescriptor>> call(
controller, stub, ListNamespaceDescriptorsRequest.newBuilder().build(), (s, c, req,
done) -> s.listNamespaceDescriptors(c, req, done), (resp) -> ProtobufUtil
.toNamespaceDescriptorList(resp))).call();
}
@Override
public CompletableFuture<List<RegionInfo>> getRegions(ServerName serverName) {
return this.<List<RegionInfo>> newAdminCaller()
.action((controller, stub) -> this
.<GetOnlineRegionRequest, GetOnlineRegionResponse, List<RegionInfo>> adminCall(
controller, stub, RequestConverter.buildGetOnlineRegionRequest(),
(s, c, req, done) -> s.getOnlineRegion(c, req, done),
resp -> ProtobufUtil.getRegionInfos(resp)))
.serverName(serverName).call();
}
@Override
public CompletableFuture<List<RegionInfo>> getRegions(TableName tableName) {
if (tableName.equals(META_TABLE_NAME)) {
return connection.getLocator().getRegionLocation(tableName, null, null, operationTimeoutNs)
.thenApply(loc -> Collections.singletonList(loc.getRegion()));
} else {
return AsyncMetaTableAccessor.getTableHRegionLocations(metaTable, Optional.of(tableName))
.thenApply(
locs -> locs.stream().map(loc -> loc.getRegion()).collect(Collectors.toList()));
}
}
@Override
public CompletableFuture<Void> flush(TableName tableName) {
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(tableExists(tableName), (exists, err) -> {
if (err != null) {
future.completeExceptionally(err);
} else if (!exists) {
future.completeExceptionally(new TableNotFoundException(tableName));
} else {
addListener(isTableEnabled(tableName), (tableEnabled, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else if (!tableEnabled) {
future.completeExceptionally(new TableNotEnabledException(tableName));
} else {
addListener(execProcedure(FLUSH_TABLE_PROCEDURE_SIGNATURE, tableName.getNameAsString(),
new HashMap<>()), (ret, err3) -> {
if (err3 != null) {
future.completeExceptionally(err3);
} else {
future.complete(ret);
}
});
}
});
}
});
return future;
}
@Override
public CompletableFuture<Void> flushRegion(byte[] regionName) {
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(getRegionLocation(regionName), (location, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
ServerName serverName = location.getServerName();
if (serverName == null) {
future
.completeExceptionally(new NoServerForRegionException(Bytes.toStringBinary(regionName)));
return;
}
addListener(flush(serverName, location.getRegion()), (ret, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
future.complete(ret);
}
});
});
return future;
}
private CompletableFuture<Void> flush(final ServerName serverName, final RegionInfo regionInfo) {
return this.<Void> newAdminCaller()
.serverName(serverName)
.action(
(controller, stub) -> this.<FlushRegionRequest, FlushRegionResponse, Void> adminCall(
controller, stub, RequestConverter.buildFlushRegionRequest(regionInfo
.getRegionName()), (s, c, req, done) -> s.flushRegion(c, req, done),
resp -> null))
.call();
}
@Override
public CompletableFuture<Void> flushRegionServer(ServerName sn) {
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(getRegions(sn), (hRegionInfos, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
List<CompletableFuture<Void>> compactFutures = new ArrayList<>();
if (hRegionInfos != null) {
hRegionInfos.forEach(region -> compactFutures.add(flush(sn, region)));
}
addListener(CompletableFuture.allOf(
compactFutures.toArray(new CompletableFuture<?>[compactFutures.size()])), (ret, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
future.complete(ret);
}
});
});
return future;
}
@Override
public CompletableFuture<Void> compact(TableName tableName, CompactType compactType) {
return compact(tableName, null, false, compactType);
}
@Override
public CompletableFuture<Void> compact(TableName tableName, byte[] columnFamily,
CompactType compactType) {
Preconditions.checkNotNull(columnFamily, "columnFamily is null. "
+ "If you don't specify a columnFamily, use compact(TableName) instead");
return compact(tableName, columnFamily, false, compactType);
}
@Override
public CompletableFuture<Void> compactRegion(byte[] regionName) {
return compactRegion(regionName, null, false);
}
@Override
public CompletableFuture<Void> compactRegion(byte[] regionName, byte[] columnFamily) {
Preconditions.checkNotNull(columnFamily, "columnFamily is null."
+ " If you don't specify a columnFamily, use compactRegion(regionName) instead");
return compactRegion(regionName, columnFamily, false);
}
@Override
public CompletableFuture<Void> majorCompact(TableName tableName, CompactType compactType) {
return compact(tableName, null, true, compactType);
}
@Override
public CompletableFuture<Void> majorCompact(TableName tableName, byte[] columnFamily,
CompactType compactType) {
Preconditions.checkNotNull(columnFamily, "columnFamily is null."
+ "If you don't specify a columnFamily, use compact(TableName) instead");
return compact(tableName, columnFamily, true, compactType);
}
@Override
public CompletableFuture<Void> majorCompactRegion(byte[] regionName) {
return compactRegion(regionName, null, true);
}
@Override
public CompletableFuture<Void> majorCompactRegion(byte[] regionName, byte[] columnFamily) {
Preconditions.checkNotNull(columnFamily, "columnFamily is null."
+ " If you don't specify a columnFamily, use majorCompactRegion(regionName) instead");
return compactRegion(regionName, columnFamily, true);
}
@Override
public CompletableFuture<Void> compactRegionServer(ServerName sn) {
return compactRegionServer(sn, false);
}
@Override
public CompletableFuture<Void> majorCompactRegionServer(ServerName sn) {
return compactRegionServer(sn, true);
}
private CompletableFuture<Void> compactRegionServer(ServerName sn, boolean major) {
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(getRegions(sn), (hRegionInfos, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
List<CompletableFuture<Void>> compactFutures = new ArrayList<>();
if (hRegionInfos != null) {
hRegionInfos.forEach(region -> compactFutures.add(compact(sn, region, major, null)));
}
addListener(CompletableFuture.allOf(
compactFutures.toArray(new CompletableFuture<?>[compactFutures.size()])), (ret, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
future.complete(ret);
}
});
});
return future;
}
private CompletableFuture<Void> compactRegion(byte[] regionName, byte[] columnFamily,
boolean major) {
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(getRegionLocation(regionName), (location, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
ServerName serverName = location.getServerName();
if (serverName == null) {
future
.completeExceptionally(new NoServerForRegionException(Bytes.toStringBinary(regionName)));
return;
}
addListener(compact(location.getServerName(), location.getRegion(), major, columnFamily),
(ret, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
future.complete(ret);
}
});
});
return future;
}
/**
* List all region locations for the specific table.
*/
private CompletableFuture<List<HRegionLocation>> getTableHRegionLocations(TableName tableName) {
if (TableName.META_TABLE_NAME.equals(tableName)) {
CompletableFuture<List<HRegionLocation>> future = new CompletableFuture<>();
// For meta table, we use zk to fetch all locations.
AsyncRegistry registry = AsyncRegistryFactory.getRegistry(connection.getConfiguration());
addListener(registry.getMetaRegionLocation(), (metaRegions, err) -> {
if (err != null) {
future.completeExceptionally(err);
} else if (metaRegions == null || metaRegions.isEmpty() ||
metaRegions.getDefaultRegionLocation() == null) {
future.completeExceptionally(new IOException("meta region does not found"));
} else {
future.complete(Collections.singletonList(metaRegions.getDefaultRegionLocation()));
}
// close the registry.
IOUtils.closeQuietly(registry);
});
return future;
} else {
// For non-meta table, we fetch all locations by scanning hbase:meta table
return AsyncMetaTableAccessor.getTableHRegionLocations(metaTable, Optional.of(tableName));
}
}
/**
* Compact column family of a table, Asynchronous operation even if CompletableFuture.get()
*/
private CompletableFuture<Void> compact(TableName tableName, byte[] columnFamily, boolean major,
CompactType compactType) {
CompletableFuture<Void> future = new CompletableFuture<>();
switch (compactType) {
case MOB:
addListener(connection.registry.getMasterAddress(), (serverName, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
RegionInfo regionInfo = RegionInfo.createMobRegionInfo(tableName);
addListener(compact(serverName, regionInfo, major, columnFamily), (ret, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
future.complete(ret);
}
});
});
break;
case NORMAL:
addListener(getTableHRegionLocations(tableName), (locations, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
if (locations == null || locations.isEmpty()) {
future.completeExceptionally(new TableNotFoundException(tableName));
}
CompletableFuture<?>[] compactFutures =
locations.stream().filter(l -> l.getRegion() != null)
.filter(l -> !l.getRegion().isOffline()).filter(l -> l.getServerName() != null)
.map(l -> compact(l.getServerName(), l.getRegion(), major, columnFamily))
.toArray(CompletableFuture<?>[]::new);
// future complete unless all of the compact futures are completed.
addListener(CompletableFuture.allOf(compactFutures), (ret, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
future.complete(ret);
}
});
});
break;
default:
throw new IllegalArgumentException("Unknown compactType: " + compactType);
}
return future;
}
/**
* Compact the region at specific region server.
*/
private CompletableFuture<Void> compact(final ServerName sn, final RegionInfo hri,
final boolean major, byte[] columnFamily) {
return this
.<Void> newAdminCaller()
.serverName(sn)
.action(
(controller, stub) -> this.<CompactRegionRequest, CompactRegionResponse, Void> adminCall(
controller, stub, RequestConverter.buildCompactRegionRequest(hri.getRegionName(),
major, columnFamily), (s, c, req, done) -> s.compactRegion(c, req, done),
resp -> null)).call();
}
private byte[] toEncodeRegionName(byte[] regionName) {
try {
return RegionInfo.isEncodedRegionName(regionName) ? regionName
: Bytes.toBytes(RegionInfo.encodeRegionName(regionName));
} catch (IOException e) {
return regionName;
}
}
private void checkAndGetTableName(byte[] encodeRegionName, AtomicReference<TableName> tableName,
CompletableFuture<TableName> result) {
addListener(getRegionLocation(encodeRegionName), (location, err) -> {
if (err != null) {
result.completeExceptionally(err);
return;
}
RegionInfo regionInfo = location.getRegion();
if (regionInfo.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) {
result.completeExceptionally(
new IllegalArgumentException("Can't invoke merge on non-default regions directly"));
return;
}
if (!tableName.compareAndSet(null, regionInfo.getTable())) {
if (!tableName.get().equals(regionInfo.getTable())) {
// tables of this two region should be same.
result.completeExceptionally(
new IllegalArgumentException("Cannot merge regions from two different tables " +
tableName.get() + " and " + regionInfo.getTable()));
} else {
result.complete(tableName.get());
}
}
});
}
private CompletableFuture<TableName> checkRegionsAndGetTableName(byte[] encodeRegionNameA,
byte[] encodeRegionNameB) {
AtomicReference<TableName> tableNameRef = new AtomicReference<>();
CompletableFuture<TableName> future = new CompletableFuture<>();
checkAndGetTableName(encodeRegionNameA, tableNameRef, future);
checkAndGetTableName(encodeRegionNameB, tableNameRef, future);
return future;
}
@Override
public CompletableFuture<Boolean> mergeSwitch(boolean on) {
return setSplitOrMergeOn(on, MasterSwitchType.MERGE);
}
@Override
public CompletableFuture<Boolean> isMergeEnabled() {
return isSplitOrMergeOn(MasterSwitchType.MERGE);
}
@Override
public CompletableFuture<Boolean> splitSwitch(boolean on) {
return setSplitOrMergeOn(on, MasterSwitchType.SPLIT);
}
@Override
public CompletableFuture<Boolean> isSplitEnabled() {
return isSplitOrMergeOn(MasterSwitchType.SPLIT);
}
private CompletableFuture<Boolean> setSplitOrMergeOn(boolean on, MasterSwitchType switchType) {
SetSplitOrMergeEnabledRequest request =
RequestConverter.buildSetSplitOrMergeEnabledRequest(on, false, switchType);
return this
.<Boolean> newMasterCaller()
.action(
(controller, stub) -> this
.<SetSplitOrMergeEnabledRequest, SetSplitOrMergeEnabledResponse, Boolean> call(
controller, stub, request, (s, c, req, done) -> s.setSplitOrMergeEnabled(c, req,
done), (resp) -> resp.getPrevValueList().get(0))).call();
}
private CompletableFuture<Boolean> isSplitOrMergeOn(MasterSwitchType switchType) {
IsSplitOrMergeEnabledRequest request =
RequestConverter.buildIsSplitOrMergeEnabledRequest(switchType);
return this
.<Boolean> newMasterCaller()
.action(
(controller, stub) -> this
.<IsSplitOrMergeEnabledRequest, IsSplitOrMergeEnabledResponse, Boolean> call(
controller, stub, request,
(s, c, req, done) -> s.isSplitOrMergeEnabled(c, req, done),
(resp) -> resp.getEnabled())).call();
}
@Override
public CompletableFuture<Void> mergeRegions(byte[] nameOfRegionA, byte[] nameOfRegionB,
boolean forcible) {
CompletableFuture<Void> future = new CompletableFuture<>();
final byte[] encodeRegionNameA = toEncodeRegionName(nameOfRegionA);
final byte[] encodeRegionNameB = toEncodeRegionName(nameOfRegionB);
addListener(checkRegionsAndGetTableName(encodeRegionNameA, encodeRegionNameB),
(tableName, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
MergeTableRegionsRequest request = null;
try {
request = RequestConverter.buildMergeTableRegionsRequest(
new byte[][] { encodeRegionNameA, encodeRegionNameB }, forcible, ng.getNonceGroup(),
ng.newNonce());
} catch (DeserializationException e) {
future.completeExceptionally(e);
return;
}
addListener(
this.<MergeTableRegionsRequest, MergeTableRegionsResponse> procedureCall(request,
(s, c, req, done) -> s.mergeTableRegions(c, req, done), (resp) -> resp.getProcId(),
new MergeTableRegionProcedureBiConsumer(tableName)),
(ret, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
future.complete(ret);
}
});
});
return future;
}
@Override
public CompletableFuture<Void> split(TableName tableName) {
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(tableExists(tableName), (exist, error) -> {
if (error != null) {
future.completeExceptionally(error);
return;
}
if (!exist) {
future.completeExceptionally(new TableNotFoundException(tableName));
return;
}
addListener(
metaTable
.scanAll(new Scan().setReadType(ReadType.PREAD).addFamily(HConstants.CATALOG_FAMILY)
.withStartRow(MetaTableAccessor.getTableStartRowForMeta(tableName, QueryType.REGION))
.withStopRow(MetaTableAccessor.getTableStopRowForMeta(tableName, QueryType.REGION))),
(results, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
return;
}
if (results != null && !results.isEmpty()) {
List<CompletableFuture<Void>> splitFutures = new ArrayList<>();
for (Result r : results) {
if (r.isEmpty() || MetaTableAccessor.getRegionInfo(r) == null) {
continue;
}
RegionLocations rl = MetaTableAccessor.getRegionLocations(r);
if (rl != null) {
for (HRegionLocation h : rl.getRegionLocations()) {
if (h != null && h.getServerName() != null) {
RegionInfo hri = h.getRegion();
if (hri == null || hri.isSplitParent() ||
hri.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) {
continue;
}
splitFutures.add(split(hri, null));
}
}
}
}
addListener(
CompletableFuture
.allOf(splitFutures.toArray(new CompletableFuture<?>[splitFutures.size()])),
(ret, exception) -> {
if (exception != null) {
future.completeExceptionally(exception);
return;
}
future.complete(ret);
});
} else {
future.complete(null);
}
});
});
return future;
}
@Override
public CompletableFuture<Void> split(TableName tableName, byte[] splitPoint) {
CompletableFuture<Void> result = new CompletableFuture<>();
if (splitPoint == null) {
return failedFuture(new IllegalArgumentException("splitPoint can not be null."));
}
addListener(connection.getRegionLocator(tableName).getRegionLocation(splitPoint, true),
(loc, err) -> {
if (err != null) {
result.completeExceptionally(err);
} else if (loc == null || loc.getRegion() == null) {
result.completeExceptionally(new IllegalArgumentException(
"Region does not found: rowKey=" + Bytes.toStringBinary(splitPoint)));
} else {
addListener(splitRegion(loc.getRegion().getRegionName(), splitPoint), (ret, err2) -> {
if (err2 != null) {
result.completeExceptionally(err2);
} else {
result.complete(ret);
}
});
}
});
return result;
}
@Override
public CompletableFuture<Void> splitRegion(byte[] regionName) {
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(getRegionLocation(regionName), (location, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
RegionInfo regionInfo = location.getRegion();
if (regionInfo.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) {
future
.completeExceptionally(new IllegalArgumentException("Can't split replicas directly. " +
"Replicas are auto-split when their primary is split."));
return;
}
ServerName serverName = location.getServerName();
if (serverName == null) {
future
.completeExceptionally(new NoServerForRegionException(Bytes.toStringBinary(regionName)));
return;
}
addListener(split(regionInfo, null), (ret, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
future.complete(ret);
}
});
});
return future;
}
@Override
public CompletableFuture<Void> splitRegion(byte[] regionName, byte[] splitPoint) {
Preconditions.checkNotNull(splitPoint,
"splitPoint is null. If you don't specify a splitPoint, use splitRegion(byte[]) instead");
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(getRegionLocation(regionName), (location, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
RegionInfo regionInfo = location.getRegion();
if (regionInfo.getReplicaId() != RegionInfo.DEFAULT_REPLICA_ID) {
future
.completeExceptionally(new IllegalArgumentException("Can't split replicas directly. " +
"Replicas are auto-split when their primary is split."));
return;
}
ServerName serverName = location.getServerName();
if (serverName == null) {
future
.completeExceptionally(new NoServerForRegionException(Bytes.toStringBinary(regionName)));
return;
}
if (regionInfo.getStartKey() != null &&
Bytes.compareTo(regionInfo.getStartKey(), splitPoint) == 0) {
future.completeExceptionally(
new IllegalArgumentException("should not give a splitkey which equals to startkey!"));
return;
}
addListener(split(regionInfo, splitPoint), (ret, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
future.complete(ret);
}
});
});
return future;
}
private CompletableFuture<Void> split(final RegionInfo hri, byte[] splitPoint) {
CompletableFuture<Void> future = new CompletableFuture<>();
TableName tableName = hri.getTable();
SplitTableRegionRequest request = null;
try {
request = RequestConverter.buildSplitTableRegionRequest(hri, splitPoint, ng.getNonceGroup(),
ng.newNonce());
} catch (DeserializationException e) {
future.completeExceptionally(e);
return future;
}
addListener(this.<SplitTableRegionRequest, SplitTableRegionResponse> procedureCall(request,
(s, c, req, done) -> s.splitRegion(c, req, done), (resp) -> resp.getProcId(),
new SplitTableRegionProcedureBiConsumer(tableName)), (ret, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
future.complete(ret);
}
});
return future;
}
@Override
public CompletableFuture<Void> assign(byte[] regionName) {
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(getRegionInfo(regionName), (regionInfo, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
addListener(this.<Void> newMasterCaller()
.action(((controller, stub) -> this.<AssignRegionRequest, AssignRegionResponse, Void> call(
controller, stub, RequestConverter.buildAssignRegionRequest(regionInfo.getRegionName()),
(s, c, req, done) -> s.assignRegion(c, req, done), resp -> null)))
.call(), (ret, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
future.complete(ret);
}
});
});
return future;
}
@Override
public CompletableFuture<Void> unassign(byte[] regionName, boolean forcible) {
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(getRegionInfo(regionName), (regionInfo, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
addListener(
this.<Void> newMasterCaller()
.action(((controller, stub) -> this
.<UnassignRegionRequest, UnassignRegionResponse, Void> call(controller, stub,
RequestConverter.buildUnassignRegionRequest(regionInfo.getRegionName(), forcible),
(s, c, req, done) -> s.unassignRegion(c, req, done), resp -> null)))
.call(),
(ret, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
future.complete(ret);
}
});
});
return future;
}
@Override
public CompletableFuture<Void> offline(byte[] regionName) {
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(getRegionInfo(regionName), (regionInfo, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
addListener(
this.<Void> newMasterCaller()
.action(((controller, stub) -> this
.<OfflineRegionRequest, OfflineRegionResponse, Void> call(controller, stub,
RequestConverter.buildOfflineRegionRequest(regionInfo.getRegionName()),
(s, c, req, done) -> s.offlineRegion(c, req, done), resp -> null)))
.call(),
(ret, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
future.complete(ret);
}
});
});
return future;
}
@Override
public CompletableFuture<Void> move(byte[] regionName) {
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(getRegionInfo(regionName), (regionInfo, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
addListener(
moveRegion(
RequestConverter.buildMoveRegionRequest(regionInfo.getEncodedNameAsBytes(), null)),
(ret, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
future.complete(ret);
}
});
});
return future;
}
@Override
public CompletableFuture<Void> move(byte[] regionName, ServerName destServerName) {
Preconditions.checkNotNull(destServerName,
"destServerName is null. If you don't specify a destServerName, use move(byte[]) instead");
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(getRegionInfo(regionName), (regionInfo, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
addListener(moveRegion(RequestConverter
.buildMoveRegionRequest(regionInfo.getEncodedNameAsBytes(), destServerName)),
(ret, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
future.complete(ret);
}
});
});
return future;
}
private CompletableFuture<Void> moveRegion(MoveRegionRequest request) {
return this
.<Void> newMasterCaller()
.action(
(controller, stub) -> this.<MoveRegionRequest, MoveRegionResponse, Void> call(controller,
stub, request, (s, c, req, done) -> s.moveRegion(c, req, done), resp -> null)).call();
}
@Override
public CompletableFuture<Void> setQuota(QuotaSettings quota) {
return this
.<Void> newMasterCaller()
.action(
(controller, stub) -> this.<SetQuotaRequest, SetQuotaResponse, Void> call(controller,
stub, QuotaSettings.buildSetQuotaRequestProto(quota),
(s, c, req, done) -> s.setQuota(c, req, done), (resp) -> null)).call();
}
@Override
public CompletableFuture<List<QuotaSettings>> getQuota(QuotaFilter filter) {
CompletableFuture<List<QuotaSettings>> future = new CompletableFuture<>();
Scan scan = QuotaTableUtil.makeScan(filter);
this.connection.getTableBuilder(QuotaTableUtil.QUOTA_TABLE_NAME).build()
.scan(scan, new AdvancedScanResultConsumer() {
List<QuotaSettings> settings = new ArrayList<>();
@Override
public void onNext(Result[] results, ScanController controller) {
for (Result result : results) {
try {
QuotaTableUtil.parseResultToCollection(result, settings);
} catch (IOException e) {
controller.terminate();
future.completeExceptionally(e);
}
}
}
@Override
public void onError(Throwable error) {
future.completeExceptionally(error);
}
@Override
public void onComplete() {
future.complete(settings);
}
});
return future;
}
@Override
public CompletableFuture<Void> addReplicationPeer(String peerId,
ReplicationPeerConfig peerConfig, boolean enabled) {
return this.<AddReplicationPeerRequest, AddReplicationPeerResponse> procedureCall(
RequestConverter.buildAddReplicationPeerRequest(peerId, peerConfig, enabled),
(s, c, req, done) -> s.addReplicationPeer(c, req, done), (resp) -> resp.getProcId(),
new ReplicationProcedureBiConsumer(peerId, () -> "ADD_REPLICATION_PEER"));
}
@Override
public CompletableFuture<Void> removeReplicationPeer(String peerId) {
return this.<RemoveReplicationPeerRequest, RemoveReplicationPeerResponse> procedureCall(
RequestConverter.buildRemoveReplicationPeerRequest(peerId),
(s, c, req, done) -> s.removeReplicationPeer(c, req, done), (resp) -> resp.getProcId(),
new ReplicationProcedureBiConsumer(peerId, () -> "REMOVE_REPLICATION_PEER"));
}
@Override
public CompletableFuture<Void> enableReplicationPeer(String peerId) {
return this.<EnableReplicationPeerRequest, EnableReplicationPeerResponse> procedureCall(
RequestConverter.buildEnableReplicationPeerRequest(peerId),
(s, c, req, done) -> s.enableReplicationPeer(c, req, done), (resp) -> resp.getProcId(),
new ReplicationProcedureBiConsumer(peerId, () -> "ENABLE_REPLICATION_PEER"));
}
@Override
public CompletableFuture<Void> disableReplicationPeer(String peerId) {
return this.<DisableReplicationPeerRequest, DisableReplicationPeerResponse> procedureCall(
RequestConverter.buildDisableReplicationPeerRequest(peerId),
(s, c, req, done) -> s.disableReplicationPeer(c, req, done), (resp) -> resp.getProcId(),
new ReplicationProcedureBiConsumer(peerId, () -> "DISABLE_REPLICATION_PEER"));
}
@Override
public CompletableFuture<ReplicationPeerConfig> getReplicationPeerConfig(String peerId) {
return this
.<ReplicationPeerConfig> newMasterCaller()
.action(
(controller, stub) -> this
.<GetReplicationPeerConfigRequest, GetReplicationPeerConfigResponse, ReplicationPeerConfig> call(
controller, stub, RequestConverter.buildGetReplicationPeerConfigRequest(peerId), (
s, c, req, done) -> s.getReplicationPeerConfig(c, req, done),
(resp) -> ReplicationPeerConfigUtil.convert(resp.getPeerConfig()))).call();
}
@Override
public CompletableFuture<Void> updateReplicationPeerConfig(String peerId,
ReplicationPeerConfig peerConfig) {
return this
.<UpdateReplicationPeerConfigRequest, UpdateReplicationPeerConfigResponse> procedureCall(
RequestConverter.buildUpdateReplicationPeerConfigRequest(peerId, peerConfig),
(s, c, req, done) -> s.updateReplicationPeerConfig(c, req, done),
(resp) -> resp.getProcId(),
new ReplicationProcedureBiConsumer(peerId, () -> "UPDATE_REPLICATION_PEER_CONFIG"));
}
@Override
public CompletableFuture<Void> appendReplicationPeerTableCFs(String id,
Map<TableName, List<String>> tableCfs) {
if (tableCfs == null) {
return failedFuture(new ReplicationException("tableCfs is null"));
}
CompletableFuture<Void> future = new CompletableFuture<Void>();
addListener(getReplicationPeerConfig(id), (peerConfig, error) -> {
if (!completeExceptionally(future, error)) {
ReplicationPeerConfig newPeerConfig =
ReplicationPeerConfigUtil.appendTableCFsToReplicationPeerConfig(tableCfs, peerConfig);
addListener(updateReplicationPeerConfig(id, newPeerConfig), (result, err) -> {
if (!completeExceptionally(future, error)) {
future.complete(result);
}
});
}
});
return future;
}
@Override
public CompletableFuture<Void> removeReplicationPeerTableCFs(String id,
Map<TableName, List<String>> tableCfs) {
if (tableCfs == null) {
return failedFuture(new ReplicationException("tableCfs is null"));
}
CompletableFuture<Void> future = new CompletableFuture<Void>();
addListener(getReplicationPeerConfig(id), (peerConfig, error) -> {
if (!completeExceptionally(future, error)) {
ReplicationPeerConfig newPeerConfig = null;
try {
newPeerConfig = ReplicationPeerConfigUtil
.removeTableCFsFromReplicationPeerConfig(tableCfs, peerConfig, id);
} catch (ReplicationException e) {
future.completeExceptionally(e);
return;
}
addListener(updateReplicationPeerConfig(id, newPeerConfig), (result, err) -> {
if (!completeExceptionally(future, error)) {
future.complete(result);
}
});
}
});
return future;
}
@Override
public CompletableFuture<List<ReplicationPeerDescription>> listReplicationPeers() {
return listReplicationPeers(RequestConverter.buildListReplicationPeersRequest(null));
}
@Override
public CompletableFuture<List<ReplicationPeerDescription>> listReplicationPeers(Pattern pattern) {
Preconditions.checkNotNull(pattern,
"pattern is null. If you don't specify a pattern, use listReplicationPeers() instead");
return listReplicationPeers(RequestConverter.buildListReplicationPeersRequest(pattern));
}
private CompletableFuture<List<ReplicationPeerDescription>> listReplicationPeers(
ListReplicationPeersRequest request) {
return this
.<List<ReplicationPeerDescription>> newMasterCaller()
.action(
(controller, stub) -> this
.<ListReplicationPeersRequest, ListReplicationPeersResponse, List<ReplicationPeerDescription>> call(
controller,
stub,
request,
(s, c, req, done) -> s.listReplicationPeers(c, req, done),
(resp) -> resp.getPeerDescList().stream()
.map(ReplicationPeerConfigUtil::toReplicationPeerDescription)
.collect(Collectors.toList()))).call();
}
@Override
public CompletableFuture<List<TableCFs>> listReplicatedTableCFs() {
CompletableFuture<List<TableCFs>> future = new CompletableFuture<List<TableCFs>>();
addListener(listTableDescriptors(), (tables, error) -> {
if (!completeExceptionally(future, error)) {
List<TableCFs> replicatedTableCFs = new ArrayList<>();
tables.forEach(table -> {
Map<String, Integer> cfs = new HashMap<>();
Stream.of(table.getColumnFamilies())
.filter(column -> column.getScope() != HConstants.REPLICATION_SCOPE_LOCAL)
.forEach(column -> {
cfs.put(column.getNameAsString(), column.getScope());
});
if (!cfs.isEmpty()) {
replicatedTableCFs.add(new TableCFs(table.getTableName(), cfs));
}
});
future.complete(replicatedTableCFs);
}
});
return future;
}
@Override
public CompletableFuture<Void> snapshot(SnapshotDescription snapshotDesc) {
SnapshotProtos.SnapshotDescription snapshot =
ProtobufUtil.createHBaseProtosSnapshotDesc(snapshotDesc);
try {
ClientSnapshotDescriptionUtils.assertSnapshotRequestIsValid(snapshot);
} catch (IllegalArgumentException e) {
return failedFuture(e);
}
CompletableFuture<Void> future = new CompletableFuture<>();
final SnapshotRequest request = SnapshotRequest.newBuilder().setSnapshot(snapshot).build();
addListener(this.<Long> newMasterCaller()
.action((controller, stub) -> this.<SnapshotRequest, SnapshotResponse, Long> call(controller,
stub, request, (s, c, req, done) -> s.snapshot(c, req, done),
resp -> resp.getExpectedTimeout()))
.call(), (expectedTimeout, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
TimerTask pollingTask = new TimerTask() {
int tries = 0;
long startTime = EnvironmentEdgeManager.currentTime();
long endTime = startTime + expectedTimeout;
long maxPauseTime = expectedTimeout / maxAttempts;
@Override
public void run(Timeout timeout) throws Exception {
if (EnvironmentEdgeManager.currentTime() < endTime) {
addListener(isSnapshotFinished(snapshotDesc), (done, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else if (done) {
future.complete(null);
} else {
// retry again after pauseTime.
long pauseTime =
ConnectionUtils.getPauseTime(TimeUnit.NANOSECONDS.toMillis(pauseNs), ++tries);
pauseTime = Math.min(pauseTime, maxPauseTime);
AsyncConnectionImpl.RETRY_TIMER.newTimeout(this, pauseTime,
TimeUnit.MILLISECONDS);
}
});
} else {
future.completeExceptionally(
new SnapshotCreationException("Snapshot '" + snapshot.getName() +
"' wasn't completed in expectedTime:" + expectedTimeout + " ms", snapshotDesc));
}
}
};
AsyncConnectionImpl.RETRY_TIMER.newTimeout(pollingTask, 1, TimeUnit.MILLISECONDS);
});
return future;
}
@Override
public CompletableFuture<Boolean> isSnapshotFinished(SnapshotDescription snapshot) {
return this
.<Boolean> newMasterCaller()
.action(
(controller, stub) -> this.<IsSnapshotDoneRequest, IsSnapshotDoneResponse, Boolean> call(
controller,
stub,
IsSnapshotDoneRequest.newBuilder()
.setSnapshot(ProtobufUtil.createHBaseProtosSnapshotDesc(snapshot)).build(), (s, c,
req, done) -> s.isSnapshotDone(c, req, done), resp -> resp.getDone())).call();
}
@Override
public CompletableFuture<Void> restoreSnapshot(String snapshotName) {
boolean takeFailSafeSnapshot = this.connection.getConfiguration().getBoolean(
HConstants.SNAPSHOT_RESTORE_TAKE_FAILSAFE_SNAPSHOT,
HConstants.DEFAULT_SNAPSHOT_RESTORE_TAKE_FAILSAFE_SNAPSHOT);
return restoreSnapshot(snapshotName, takeFailSafeSnapshot);
}
@Override
public CompletableFuture<Void> restoreSnapshot(String snapshotName,
boolean takeFailSafeSnapshot) {
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(listSnapshots(Pattern.compile(snapshotName)), (snapshotDescriptions, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
TableName tableName = null;
if (snapshotDescriptions != null && !snapshotDescriptions.isEmpty()) {
for (SnapshotDescription snap : snapshotDescriptions) {
if (snap.getName().equals(snapshotName)) {
tableName = snap.getTableName();
break;
}
}
}
if (tableName == null) {
future.completeExceptionally(new RestoreSnapshotException(
"Unable to find the table name for snapshot=" + snapshotName));
return;
}
final TableName finalTableName = tableName;
addListener(tableExists(finalTableName), (exists, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else if (!exists) {
// if table does not exist, then just clone snapshot into new table.
completeConditionalOnFuture(future,
internalRestoreSnapshot(snapshotName, finalTableName));
} else {
addListener(isTableDisabled(finalTableName), (disabled, err4) -> {
if (err4 != null) {
future.completeExceptionally(err4);
} else if (!disabled) {
future.completeExceptionally(new TableNotDisabledException(finalTableName));
} else {
completeConditionalOnFuture(future,
restoreSnapshot(snapshotName, finalTableName, takeFailSafeSnapshot));
}
});
}
});
});
return future;
}
private CompletableFuture<Void> restoreSnapshot(String snapshotName, TableName tableName,
boolean takeFailSafeSnapshot) {
if (takeFailSafeSnapshot) {
CompletableFuture<Void> future = new CompletableFuture<>();
// Step.1 Take a snapshot of the current state
String failSafeSnapshotSnapshotNameFormat =
this.connection.getConfiguration().get(HConstants.SNAPSHOT_RESTORE_FAILSAFE_NAME,
HConstants.DEFAULT_SNAPSHOT_RESTORE_FAILSAFE_NAME);
final String failSafeSnapshotSnapshotName =
failSafeSnapshotSnapshotNameFormat.replace("{snapshot.name}", snapshotName)
.replace("{table.name}", tableName.toString().replace(TableName.NAMESPACE_DELIM, '.'))
.replace("{restore.timestamp}", String.valueOf(EnvironmentEdgeManager.currentTime()));
LOG.info("Taking restore-failsafe snapshot: " + failSafeSnapshotSnapshotName);
addListener(snapshot(failSafeSnapshotSnapshotName, tableName), (ret, err) -> {
if (err != null) {
future.completeExceptionally(err);
} else {
// Step.2 Restore snapshot
addListener(internalRestoreSnapshot(snapshotName, tableName), (void2, err2) -> {
if (err2 != null) {
// Step.3.a Something went wrong during the restore and try to rollback.
addListener(internalRestoreSnapshot(failSafeSnapshotSnapshotName, tableName),
(void3, err3) -> {
if (err3 != null) {
future.completeExceptionally(err3);
} else {
String msg =
"Restore snapshot=" + snapshotName + " failed. Rollback to snapshot=" +
failSafeSnapshotSnapshotName + " succeeded.";
future.completeExceptionally(new RestoreSnapshotException(msg));
}
});
} else {
// Step.3.b If the restore is succeeded, delete the pre-restore snapshot.
LOG.info("Deleting restore-failsafe snapshot: " + failSafeSnapshotSnapshotName);
addListener(deleteSnapshot(failSafeSnapshotSnapshotName), (ret3, err3) -> {
if (err3 != null) {
LOG.error(
"Unable to remove the failsafe snapshot: " + failSafeSnapshotSnapshotName,
err3);
future.completeExceptionally(err3);
} else {
future.complete(ret3);
}
});
}
});
}
});
return future;
} else {
return internalRestoreSnapshot(snapshotName, tableName);
}
}
private <T> void completeConditionalOnFuture(CompletableFuture<T> dependentFuture,
CompletableFuture<T> parentFuture) {
addListener(parentFuture, (res, err) -> {
if (err != null) {
dependentFuture.completeExceptionally(err);
} else {
dependentFuture.complete(res);
}
});
}
@Override
public CompletableFuture<Void> cloneSnapshot(String snapshotName, TableName tableName) {
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(tableExists(tableName), (exists, err) -> {
if (err != null) {
future.completeExceptionally(err);
} else if (exists) {
future.completeExceptionally(new TableExistsException(tableName));
} else {
completeConditionalOnFuture(future, internalRestoreSnapshot(snapshotName, tableName));
}
});
return future;
}
private CompletableFuture<Void> internalRestoreSnapshot(String snapshotName, TableName tableName) {
SnapshotProtos.SnapshotDescription snapshot = SnapshotProtos.SnapshotDescription.newBuilder()
.setName(snapshotName).setTable(tableName.getNameAsString()).build();
try {
ClientSnapshotDescriptionUtils.assertSnapshotRequestIsValid(snapshot);
} catch (IllegalArgumentException e) {
return failedFuture(e);
}
return waitProcedureResult(this
.<Long> newMasterCaller()
.action(
(controller, stub) -> this.<RestoreSnapshotRequest, RestoreSnapshotResponse, Long> call(
controller, stub, RestoreSnapshotRequest.newBuilder().setSnapshot(snapshot)
.setNonceGroup(ng.getNonceGroup()).setNonce(ng.newNonce()).build(), (s, c, req,
done) -> s.restoreSnapshot(c, req, done), (resp) -> resp.getProcId())).call());
}
@Override
public CompletableFuture<List<SnapshotDescription>> listSnapshots() {
return getCompletedSnapshots(null);
}
@Override
public CompletableFuture<List<SnapshotDescription>> listSnapshots(Pattern pattern) {
Preconditions.checkNotNull(pattern,
"pattern is null. If you don't specify a pattern, use listSnapshots() instead");
return getCompletedSnapshots(pattern);
}
private CompletableFuture<List<SnapshotDescription>> getCompletedSnapshots(Pattern pattern) {
return this.<List<SnapshotDescription>> newMasterCaller().action((controller, stub) -> this
.<GetCompletedSnapshotsRequest, GetCompletedSnapshotsResponse, List<SnapshotDescription>>
call(controller, stub, GetCompletedSnapshotsRequest.newBuilder().build(),
(s, c, req, done) -> s.getCompletedSnapshots(c, req, done),
resp -> ProtobufUtil.toSnapshotDescriptionList(resp, pattern)))
.call();
}
@Override
public CompletableFuture<List<SnapshotDescription>> listTableSnapshots(Pattern tableNamePattern) {
Preconditions.checkNotNull(tableNamePattern, "tableNamePattern is null."
+ " If you don't specify a tableNamePattern, use listSnapshots() instead");
return getCompletedSnapshots(tableNamePattern, null);
}
@Override
public CompletableFuture<List<SnapshotDescription>> listTableSnapshots(Pattern tableNamePattern,
Pattern snapshotNamePattern) {
Preconditions.checkNotNull(tableNamePattern, "tableNamePattern is null."
+ " If you don't specify a tableNamePattern, use listSnapshots(Pattern) instead");
Preconditions.checkNotNull(snapshotNamePattern, "snapshotNamePattern is null."
+ " If you don't specify a snapshotNamePattern, use listTableSnapshots(Pattern) instead");
return getCompletedSnapshots(tableNamePattern, snapshotNamePattern);
}
private CompletableFuture<List<SnapshotDescription>> getCompletedSnapshots(
Pattern tableNamePattern, Pattern snapshotNamePattern) {
CompletableFuture<List<SnapshotDescription>> future = new CompletableFuture<>();
addListener(listTableNames(tableNamePattern, false), (tableNames, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
if (tableNames == null || tableNames.size() <= 0) {
future.complete(Collections.emptyList());
return;
}
addListener(getCompletedSnapshots(snapshotNamePattern), (snapshotDescList, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
return;
}
if (snapshotDescList == null || snapshotDescList.isEmpty()) {
future.complete(Collections.emptyList());
return;
}
future.complete(snapshotDescList.stream()
.filter(snap -> (snap != null && tableNames.contains(snap.getTableName())))
.collect(Collectors.toList()));
});
});
return future;
}
@Override
public CompletableFuture<Void> deleteSnapshot(String snapshotName) {
return internalDeleteSnapshot(new SnapshotDescription(snapshotName));
}
@Override
public CompletableFuture<Void> deleteSnapshots() {
return internalDeleteSnapshots(null, null);
}
@Override
public CompletableFuture<Void> deleteSnapshots(Pattern snapshotNamePattern) {
Preconditions.checkNotNull(snapshotNamePattern, "snapshotNamePattern is null."
+ " If you don't specify a snapshotNamePattern, use deleteSnapshots() instead");
return internalDeleteSnapshots(null, snapshotNamePattern);
}
@Override
public CompletableFuture<Void> deleteTableSnapshots(Pattern tableNamePattern) {
Preconditions.checkNotNull(tableNamePattern, "tableNamePattern is null."
+ " If you don't specify a tableNamePattern, use deleteSnapshots() instead");
return internalDeleteSnapshots(tableNamePattern, null);
}
@Override
public CompletableFuture<Void> deleteTableSnapshots(Pattern tableNamePattern,
Pattern snapshotNamePattern) {
Preconditions.checkNotNull(tableNamePattern, "tableNamePattern is null."
+ " If you don't specify a tableNamePattern, use deleteSnapshots(Pattern) instead");
Preconditions.checkNotNull(snapshotNamePattern, "snapshotNamePattern is null."
+ " If you don't specify a snapshotNamePattern, use deleteSnapshots(Pattern) instead");
return internalDeleteSnapshots(tableNamePattern, snapshotNamePattern);
}
private CompletableFuture<Void> internalDeleteSnapshots(Pattern tableNamePattern,
Pattern snapshotNamePattern) {
CompletableFuture<List<SnapshotDescription>> listSnapshotsFuture;
if (tableNamePattern == null) {
listSnapshotsFuture = getCompletedSnapshots(snapshotNamePattern);
} else {
listSnapshotsFuture = getCompletedSnapshots(tableNamePattern, snapshotNamePattern);
}
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(listSnapshotsFuture, ((snapshotDescriptions, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
if (snapshotDescriptions == null || snapshotDescriptions.isEmpty()) {
future.complete(null);
return;
}
addListener(CompletableFuture.allOf(snapshotDescriptions.stream()
.map(this::internalDeleteSnapshot).toArray(CompletableFuture[]::new)), (v, e) -> {
if (e != null) {
future.completeExceptionally(e);
} else {
future.complete(v);
}
});
}));
return future;
}
private CompletableFuture<Void> internalDeleteSnapshot(SnapshotDescription snapshot) {
return this
.<Void> newMasterCaller()
.action(
(controller, stub) -> this.<DeleteSnapshotRequest, DeleteSnapshotResponse, Void> call(
controller,
stub,
DeleteSnapshotRequest.newBuilder()
.setSnapshot(ProtobufUtil.createHBaseProtosSnapshotDesc(snapshot)).build(), (s, c,
req, done) -> s.deleteSnapshot(c, req, done), resp -> null)).call();
}
@Override
public CompletableFuture<Void> execProcedure(String signature, String instance,
Map<String, String> props) {
CompletableFuture<Void> future = new CompletableFuture<>();
ProcedureDescription procDesc =
ProtobufUtil.buildProcedureDescription(signature, instance, props);
addListener(this.<Long> newMasterCaller()
.action((controller, stub) -> this.<ExecProcedureRequest, ExecProcedureResponse, Long> call(
controller, stub, ExecProcedureRequest.newBuilder().setProcedure(procDesc).build(),
(s, c, req, done) -> s.execProcedure(c, req, done), resp -> resp.getExpectedTimeout()))
.call(), (expectedTimeout, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
TimerTask pollingTask = new TimerTask() {
int tries = 0;
long startTime = EnvironmentEdgeManager.currentTime();
long endTime = startTime + expectedTimeout;
long maxPauseTime = expectedTimeout / maxAttempts;
@Override
public void run(Timeout timeout) throws Exception {
if (EnvironmentEdgeManager.currentTime() < endTime) {
addListener(isProcedureFinished(signature, instance, props), (done, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
return;
}
if (done) {
future.complete(null);
} else {
// retry again after pauseTime.
long pauseTime =
ConnectionUtils.getPauseTime(TimeUnit.NANOSECONDS.toMillis(pauseNs), ++tries);
pauseTime = Math.min(pauseTime, maxPauseTime);
AsyncConnectionImpl.RETRY_TIMER.newTimeout(this, pauseTime,
TimeUnit.MICROSECONDS);
}
});
} else {
future.completeExceptionally(new IOException("Procedure '" + signature + " : " +
instance + "' wasn't completed in expectedTime:" + expectedTimeout + " ms"));
}
}
};
// Queue the polling task into RETRY_TIMER to poll procedure state asynchronously.
AsyncConnectionImpl.RETRY_TIMER.newTimeout(pollingTask, 1, TimeUnit.MILLISECONDS);
});
return future;
}
@Override
public CompletableFuture<byte[]> execProcedureWithReturn(String signature, String instance,
Map<String, String> props) {
ProcedureDescription proDesc =
ProtobufUtil.buildProcedureDescription(signature, instance, props);
return this.<byte[]> newMasterCaller()
.action(
(controller, stub) -> this.<ExecProcedureRequest, ExecProcedureResponse, byte[]> call(
controller, stub, ExecProcedureRequest.newBuilder().setProcedure(proDesc).build(),
(s, c, req, done) -> s.execProcedureWithRet(c, req, done),
resp -> resp.hasReturnData() ? resp.getReturnData().toByteArray() : null))
.call();
}
@Override
public CompletableFuture<Boolean> isProcedureFinished(String signature, String instance,
Map<String, String> props) {
ProcedureDescription proDesc =
ProtobufUtil.buildProcedureDescription(signature, instance, props);
return this.<Boolean> newMasterCaller()
.action((controller, stub) -> this
.<IsProcedureDoneRequest, IsProcedureDoneResponse, Boolean> call(controller, stub,
IsProcedureDoneRequest.newBuilder().setProcedure(proDesc).build(),
(s, c, req, done) -> s.isProcedureDone(c, req, done), resp -> resp.getDone()))
.call();
}
@Override
public CompletableFuture<Boolean> abortProcedure(long procId, boolean mayInterruptIfRunning) {
return this.<Boolean> newMasterCaller().action(
(controller, stub) -> this.<AbortProcedureRequest, AbortProcedureResponse, Boolean> call(
controller, stub, AbortProcedureRequest.newBuilder().setProcId(procId).build(),
(s, c, req, done) -> s.abortProcedure(c, req, done), resp -> resp.getIsProcedureAborted()))
.call();
}
@Override
public CompletableFuture<String> getProcedures() {
return this
.<String> newMasterCaller()
.action(
(controller, stub) -> this
.<GetProceduresRequest, GetProceduresResponse, String> call(
controller, stub, GetProceduresRequest.newBuilder().build(),
(s, c, req, done) -> s.getProcedures(c, req, done),
resp -> ProtobufUtil.toProcedureJson(resp.getProcedureList()))).call();
}
@Override
public CompletableFuture<String> getLocks() {
return this
.<String> newMasterCaller()
.action(
(controller, stub) -> this.<GetLocksRequest, GetLocksResponse, String> call(
controller, stub, GetLocksRequest.newBuilder().build(),
(s, c, req, done) -> s.getLocks(c, req, done),
resp -> ProtobufUtil.toLockJson(resp.getLockList()))).call();
}
@Override
public CompletableFuture<Void> decommissionRegionServers(List<ServerName> servers, boolean offload) {
return this.<Void> newMasterCaller()
.action((controller, stub) -> this
.<DecommissionRegionServersRequest, DecommissionRegionServersResponse, Void> call(
controller, stub, RequestConverter.buildDecommissionRegionServersRequest(servers, offload),
(s, c, req, done) -> s.decommissionRegionServers(c, req, done), resp -> null))
.call();
}
@Override
public CompletableFuture<List<ServerName>> listDecommissionedRegionServers() {
return this.<List<ServerName>> newMasterCaller()
.action((controller, stub) -> this
.<ListDecommissionedRegionServersRequest, ListDecommissionedRegionServersResponse,
List<ServerName>> call(
controller, stub, ListDecommissionedRegionServersRequest.newBuilder().build(),
(s, c, req, done) -> s.listDecommissionedRegionServers(c, req, done),
resp -> resp.getServerNameList().stream().map(ProtobufUtil::toServerName)
.collect(Collectors.toList())))
.call();
}
@Override
public CompletableFuture<Void> recommissionRegionServer(ServerName server,
List<byte[]> encodedRegionNames) {
return this.<Void> newMasterCaller()
.action((controller, stub) -> this
.<RecommissionRegionServerRequest, RecommissionRegionServerResponse, Void> call(controller,
stub, RequestConverter.buildRecommissionRegionServerRequest(server, encodedRegionNames),
(s, c, req, done) -> s.recommissionRegionServer(c, req, done), resp -> null))
.call();
}
/**
* Get the region location for the passed region name. The region name may be a full region name
* or encoded region name. If the region does not found, then it'll throw an
* UnknownRegionException wrapped by a {@link CompletableFuture}
* @param regionNameOrEncodedRegionName
* @return region location, wrapped by a {@link CompletableFuture}
*/
@VisibleForTesting
CompletableFuture<HRegionLocation> getRegionLocation(byte[] regionNameOrEncodedRegionName) {
if (regionNameOrEncodedRegionName == null) {
return failedFuture(new IllegalArgumentException("Passed region name can't be null"));
}
try {
CompletableFuture<Optional<HRegionLocation>> future;
if (RegionInfo.isEncodedRegionName(regionNameOrEncodedRegionName)) {
future = AsyncMetaTableAccessor.getRegionLocationWithEncodedName(metaTable,
regionNameOrEncodedRegionName);
} else {
future = AsyncMetaTableAccessor.getRegionLocation(metaTable, regionNameOrEncodedRegionName);
}
CompletableFuture<HRegionLocation> returnedFuture = new CompletableFuture<>();
addListener(future, (location, err) -> {
if (err != null) {
returnedFuture.completeExceptionally(err);
return;
}
if (!location.isPresent() || location.get().getRegion() == null) {
returnedFuture.completeExceptionally(
new UnknownRegionException("Invalid region name or encoded region name: " +
Bytes.toStringBinary(regionNameOrEncodedRegionName)));
} else {
returnedFuture.complete(location.get());
}
});
return returnedFuture;
} catch (IOException e) {
return failedFuture(e);
}
}
/**
* Get the region info for the passed region name. The region name may be a full region name or
* encoded region name. If the region does not found, then it'll throw an UnknownRegionException
* wrapped by a {@link CompletableFuture}
* @param regionNameOrEncodedRegionName
* @return region info, wrapped by a {@link CompletableFuture}
*/
private CompletableFuture<RegionInfo> getRegionInfo(byte[] regionNameOrEncodedRegionName) {
if (regionNameOrEncodedRegionName == null) {
return failedFuture(new IllegalArgumentException("Passed region name can't be null"));
}
if (Bytes.equals(regionNameOrEncodedRegionName,
RegionInfoBuilder.FIRST_META_REGIONINFO.getRegionName()) ||
Bytes.equals(regionNameOrEncodedRegionName,
RegionInfoBuilder.FIRST_META_REGIONINFO.getEncodedNameAsBytes())) {
return CompletableFuture.completedFuture(RegionInfoBuilder.FIRST_META_REGIONINFO);
}
CompletableFuture<RegionInfo> future = new CompletableFuture<>();
addListener(getRegionLocation(regionNameOrEncodedRegionName), (location, err) -> {
if (err != null) {
future.completeExceptionally(err);
} else {
future.complete(location.getRegion());
}
});
return future;
}
private byte[][] getSplitKeys(byte[] startKey, byte[] endKey, int numRegions) {
if (numRegions < 3) {
throw new IllegalArgumentException("Must create at least three regions");
} else if (Bytes.compareTo(startKey, endKey) >= 0) {
throw new IllegalArgumentException("Start key must be smaller than end key");
}
if (numRegions == 3) {
return new byte[][] { startKey, endKey };
}
byte[][] splitKeys = Bytes.split(startKey, endKey, numRegions - 3);
if (splitKeys == null || splitKeys.length != numRegions - 1) {
throw new IllegalArgumentException("Unable to split key range into enough regions");
}
return splitKeys;
}
private void verifySplitKeys(byte[][] splitKeys) {
Arrays.sort(splitKeys, Bytes.BYTES_COMPARATOR);
// Verify there are no duplicate split keys
byte[] lastKey = null;
for (byte[] splitKey : splitKeys) {
if (Bytes.compareTo(splitKey, HConstants.EMPTY_BYTE_ARRAY) == 0) {
throw new IllegalArgumentException("Empty split key must not be passed in the split keys.");
}
if (lastKey != null && Bytes.equals(splitKey, lastKey)) {
throw new IllegalArgumentException("All split keys must be unique, " + "found duplicate: "
+ Bytes.toStringBinary(splitKey) + ", " + Bytes.toStringBinary(lastKey));
}
lastKey = splitKey;
}
}
private static abstract class ProcedureBiConsumer implements BiConsumer<Void, Throwable> {
abstract void onFinished();
abstract void onError(Throwable error);
@Override
public void accept(Void v, Throwable error) {
if (error != null) {
onError(error);
return;
}
onFinished();
}
}
private static abstract class TableProcedureBiConsumer extends ProcedureBiConsumer {
protected final TableName tableName;
TableProcedureBiConsumer(TableName tableName) {
this.tableName = tableName;
}
abstract String getOperationType();
String getDescription() {
return "Operation: " + getOperationType() + ", " + "Table Name: "
+ tableName.getNameWithNamespaceInclAsString();
}
@Override
void onFinished() {
LOG.info(getDescription() + " completed");
}
@Override
void onError(Throwable error) {
LOG.info(getDescription() + " failed with " + error.getMessage());
}
}
private static abstract class NamespaceProcedureBiConsumer extends ProcedureBiConsumer {
protected final String namespaceName;
NamespaceProcedureBiConsumer(String namespaceName) {
this.namespaceName = namespaceName;
}
abstract String getOperationType();
String getDescription() {
return "Operation: " + getOperationType() + ", Namespace: " + namespaceName;
}
@Override
void onFinished() {
LOG.info(getDescription() + " completed");
}
@Override
void onError(Throwable error) {
LOG.info(getDescription() + " failed with " + error.getMessage());
}
}
private static class CreateTableProcedureBiConsumer extends TableProcedureBiConsumer {
CreateTableProcedureBiConsumer(TableName tableName) {
super(tableName);
}
@Override
String getOperationType() {
return "CREATE";
}
}
private static class ModifyTableProcedureBiConsumer extends TableProcedureBiConsumer {
ModifyTableProcedureBiConsumer(AsyncAdmin admin, TableName tableName) {
super(tableName);
}
@Override
String getOperationType() {
return "ENABLE";
}
}
private class DeleteTableProcedureBiConsumer extends TableProcedureBiConsumer {
DeleteTableProcedureBiConsumer(TableName tableName) {
super(tableName);
}
@Override
String getOperationType() {
return "DELETE";
}
@Override
void onFinished() {
connection.getLocator().clearCache(this.tableName);
super.onFinished();
}
}
private static class TruncateTableProcedureBiConsumer extends TableProcedureBiConsumer {
TruncateTableProcedureBiConsumer(TableName tableName) {
super(tableName);
}
@Override
String getOperationType() {
return "TRUNCATE";
}
}
private static class EnableTableProcedureBiConsumer extends TableProcedureBiConsumer {
EnableTableProcedureBiConsumer(TableName tableName) {
super(tableName);
}
@Override
String getOperationType() {
return "ENABLE";
}
}
private static class DisableTableProcedureBiConsumer extends TableProcedureBiConsumer {
DisableTableProcedureBiConsumer(TableName tableName) {
super(tableName);
}
@Override
String getOperationType() {
return "DISABLE";
}
}
private static class AddColumnFamilyProcedureBiConsumer extends TableProcedureBiConsumer {
AddColumnFamilyProcedureBiConsumer(TableName tableName) {
super(tableName);
}
@Override
String getOperationType() {
return "ADD_COLUMN_FAMILY";
}
}
private static class DeleteColumnFamilyProcedureBiConsumer extends TableProcedureBiConsumer {
DeleteColumnFamilyProcedureBiConsumer(TableName tableName) {
super(tableName);
}
@Override
String getOperationType() {
return "DELETE_COLUMN_FAMILY";
}
}
private static class ModifyColumnFamilyProcedureBiConsumer extends TableProcedureBiConsumer {
ModifyColumnFamilyProcedureBiConsumer(TableName tableName) {
super(tableName);
}
@Override
String getOperationType() {
return "MODIFY_COLUMN_FAMILY";
}
}
private static class CreateNamespaceProcedureBiConsumer extends NamespaceProcedureBiConsumer {
CreateNamespaceProcedureBiConsumer(String namespaceName) {
super(namespaceName);
}
@Override
String getOperationType() {
return "CREATE_NAMESPACE";
}
}
private static class DeleteNamespaceProcedureBiConsumer extends NamespaceProcedureBiConsumer {
DeleteNamespaceProcedureBiConsumer(String namespaceName) {
super(namespaceName);
}
@Override
String getOperationType() {
return "DELETE_NAMESPACE";
}
}
private static class ModifyNamespaceProcedureBiConsumer extends NamespaceProcedureBiConsumer {
ModifyNamespaceProcedureBiConsumer(String namespaceName) {
super(namespaceName);
}
@Override
String getOperationType() {
return "MODIFY_NAMESPACE";
}
}
private static class MergeTableRegionProcedureBiConsumer extends TableProcedureBiConsumer {
MergeTableRegionProcedureBiConsumer(TableName tableName) {
super(tableName);
}
@Override
String getOperationType() {
return "MERGE_REGIONS";
}
}
private static class SplitTableRegionProcedureBiConsumer extends TableProcedureBiConsumer {
SplitTableRegionProcedureBiConsumer(TableName tableName) {
super(tableName);
}
@Override
String getOperationType() {
return "SPLIT_REGION";
}
}
private static class ReplicationProcedureBiConsumer extends ProcedureBiConsumer {
private final String peerId;
private final Supplier<String> getOperation;
ReplicationProcedureBiConsumer(String peerId, Supplier<String> getOperation) {
this.peerId = peerId;
this.getOperation = getOperation;
}
String getDescription() {
return "Operation: " + getOperation.get() + ", peerId: " + peerId;
}
@Override
void onFinished() {
LOG.info(getDescription() + " completed");
}
@Override
void onError(Throwable error) {
LOG.info(getDescription() + " failed with " + error.getMessage());
}
}
private CompletableFuture<Void> waitProcedureResult(CompletableFuture<Long> procFuture) {
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(procFuture, (procId, error) -> {
if (error != null) {
future.completeExceptionally(error);
return;
}
getProcedureResult(procId, future, 0);
});
return future;
}
private void getProcedureResult(long procId, CompletableFuture<Void> future, int retries) {
addListener(
this.<GetProcedureResultResponse> newMasterCaller()
.action((controller, stub) -> this
.<GetProcedureResultRequest, GetProcedureResultResponse, GetProcedureResultResponse> call(
controller, stub, GetProcedureResultRequest.newBuilder().setProcId(procId).build(),
(s, c, req, done) -> s.getProcedureResult(c, req, done), (resp) -> resp))
.call(),
(response, error) -> {
if (error != null) {
LOG.warn("failed to get the procedure result procId={}", procId,
ConnectionUtils.translateException(error));
retryTimer.newTimeout(t -> getProcedureResult(procId, future, retries + 1),
ConnectionUtils.getPauseTime(pauseNs, retries), TimeUnit.NANOSECONDS);
return;
}
if (response.getState() == GetProcedureResultResponse.State.RUNNING) {
retryTimer.newTimeout(t -> getProcedureResult(procId, future, retries + 1),
ConnectionUtils.getPauseTime(pauseNs, retries), TimeUnit.NANOSECONDS);
return;
}
if (response.hasException()) {
IOException ioe = ForeignExceptionUtil.toIOException(response.getException());
future.completeExceptionally(ioe);
} else {
future.complete(null);
}
});
}
private <T> CompletableFuture<T> failedFuture(Throwable error) {
CompletableFuture<T> future = new CompletableFuture<>();
future.completeExceptionally(error);
return future;
}
private <T> boolean completeExceptionally(CompletableFuture<T> future, Throwable error) {
if (error != null) {
future.completeExceptionally(error);
return true;
}
return false;
}
@Override
public CompletableFuture<ClusterMetrics> getClusterMetrics() {
return getClusterMetrics(EnumSet.allOf(Option.class));
}
@Override
public CompletableFuture<ClusterMetrics> getClusterMetrics(EnumSet<Option> options) {
return this
.<ClusterMetrics> newMasterCaller()
.action(
(controller, stub) -> this
.<GetClusterStatusRequest, GetClusterStatusResponse, ClusterMetrics> call(controller,
stub, RequestConverter.buildGetClusterStatusRequest(options),
(s, c, req, done) -> s.getClusterStatus(c, req, done),
resp -> ClusterMetricsBuilder.toClusterMetrics(resp.getClusterStatus()))).call();
}
@Override
public CompletableFuture<Void> shutdown() {
return this
.<Void> newMasterCaller()
.action(
(controller, stub) -> this.<ShutdownRequest, ShutdownResponse, Void> call(controller,
stub, ShutdownRequest.newBuilder().build(),
(s, c, req, done) -> s.shutdown(c, req, done), resp -> null)).call();
}
@Override
public CompletableFuture<Void> stopMaster() {
return this
.<Void> newMasterCaller()
.action(
(controller, stub) -> this.<StopMasterRequest, StopMasterResponse, Void> call(controller,
stub, StopMasterRequest.newBuilder().build(),
(s, c, req, done) -> s.stopMaster(c, req, done), resp -> null)).call();
}
@Override
public CompletableFuture<Void> stopRegionServer(ServerName serverName) {
StopServerRequest request =
RequestConverter.buildStopServerRequest("Called by admin client "
+ this.connection.toString());
return this
.<Void> newAdminCaller()
.action(
(controller, stub) -> this.<StopServerRequest, StopServerResponse, Void> adminCall(
controller, stub, request, (s, c, req, done) -> s.stopServer(controller, req, done),
resp -> null)).serverName(serverName).call();
}
@Override
public CompletableFuture<Void> updateConfiguration(ServerName serverName) {
return this
.<Void> newAdminCaller()
.action(
(controller, stub) -> this
.<UpdateConfigurationRequest, UpdateConfigurationResponse, Void> adminCall(
controller, stub, UpdateConfigurationRequest.getDefaultInstance(),
(s, c, req, done) -> s.updateConfiguration(controller, req, done), resp -> null))
.serverName(serverName).call();
}
@Override
public CompletableFuture<Void> updateConfiguration() {
CompletableFuture<Void> future = new CompletableFuture<Void>();
addListener(
getClusterMetrics(EnumSet.of(Option.LIVE_SERVERS, Option.MASTER, Option.BACKUP_MASTERS)),
(status, err) -> {
if (err != null) {
future.completeExceptionally(err);
} else {
List<CompletableFuture<Void>> futures = new ArrayList<>();
status.getLiveServerMetrics().keySet()
.forEach(server -> futures.add(updateConfiguration(server)));
futures.add(updateConfiguration(status.getMasterName()));
status.getBackupMasterNames().forEach(master -> futures.add(updateConfiguration(master)));
addListener(
CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[futures.size()])),
(result, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
future.complete(result);
}
});
}
});
return future;
}
@Override
public CompletableFuture<Void> rollWALWriter(ServerName serverName) {
return this
.<Void> newAdminCaller()
.action(
(controller, stub) -> this.<RollWALWriterRequest, RollWALWriterResponse, Void> adminCall(
controller, stub, RequestConverter.buildRollWALWriterRequest(),
(s, c, req, done) -> s.rollWALWriter(controller, req, done), resp -> null))
.serverName(serverName).call();
}
@Override
public CompletableFuture<Void> clearCompactionQueues(ServerName serverName, Set<String> queues) {
return this
.<Void> newAdminCaller()
.action(
(controller, stub) -> this
.<ClearCompactionQueuesRequest, ClearCompactionQueuesResponse, Void> adminCall(
controller, stub, RequestConverter.buildClearCompactionQueuesRequest(queues), (s,
c, req, done) -> s.clearCompactionQueues(controller, req, done), resp -> null))
.serverName(serverName).call();
}
@Override
public CompletableFuture<List<SecurityCapability>> getSecurityCapabilities() {
return this
.<List<SecurityCapability>> newMasterCaller()
.action(
(controller, stub) -> this
.<SecurityCapabilitiesRequest, SecurityCapabilitiesResponse, List<SecurityCapability>> call(
controller, stub, SecurityCapabilitiesRequest.newBuilder().build(), (s, c, req,
done) -> s.getSecurityCapabilities(c, req, done), (resp) -> ProtobufUtil
.toSecurityCapabilityList(resp.getCapabilitiesList()))).call();
}
@Override
public CompletableFuture<List<RegionMetrics>> getRegionMetrics(ServerName serverName) {
return getRegionMetrics(GetRegionLoadRequest.newBuilder().build(), serverName);
}
@Override
public CompletableFuture<List<RegionMetrics>> getRegionMetrics(ServerName serverName,
TableName tableName) {
Preconditions.checkNotNull(tableName,
"tableName is null. If you don't specify a tableName, use getRegionLoads() instead");
return getRegionMetrics(RequestConverter.buildGetRegionLoadRequest(tableName), serverName);
}
private CompletableFuture<List<RegionMetrics>> getRegionMetrics(GetRegionLoadRequest request,
ServerName serverName) {
return this.<List<RegionMetrics>> newAdminCaller()
.action((controller, stub) -> this
.<GetRegionLoadRequest, GetRegionLoadResponse, List<RegionMetrics>>
adminCall(controller, stub, request, (s, c, req, done) ->
s.getRegionLoad(controller, req, done), RegionMetricsBuilder::toRegionMetrics))
.serverName(serverName).call();
}
@Override
public CompletableFuture<Boolean> isMasterInMaintenanceMode() {
return this
.<Boolean> newMasterCaller()
.action(
(controller, stub) -> this
.<IsInMaintenanceModeRequest, IsInMaintenanceModeResponse, Boolean> call(controller,
stub, IsInMaintenanceModeRequest.newBuilder().build(),
(s, c, req, done) -> s.isMasterInMaintenanceMode(c, req, done),
resp -> resp.getInMaintenanceMode())).call();
}
@Override
public CompletableFuture<CompactionState> getCompactionState(TableName tableName,
CompactType compactType) {
CompletableFuture<CompactionState> future = new CompletableFuture<>();
switch (compactType) {
case MOB:
addListener(connection.registry.getMasterAddress(), (serverName, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
RegionInfo regionInfo = RegionInfo.createMobRegionInfo(tableName);
addListener(this.<GetRegionInfoResponse> newAdminCaller().serverName(serverName)
.action((controller, stub) -> this
.<GetRegionInfoRequest, GetRegionInfoResponse, GetRegionInfoResponse> adminCall(
controller, stub,
RequestConverter.buildGetRegionInfoRequest(regionInfo.getRegionName(), true),
(s, c, req, done) -> s.getRegionInfo(controller, req, done), resp -> resp))
.call(), (resp2, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
if (resp2.hasCompactionState()) {
future.complete(ProtobufUtil.createCompactionState(resp2.getCompactionState()));
} else {
future.complete(CompactionState.NONE);
}
}
});
});
break;
case NORMAL:
addListener(getTableHRegionLocations(tableName), (locations, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
ConcurrentLinkedQueue<CompactionState> regionStates = new ConcurrentLinkedQueue<>();
List<CompletableFuture<CompactionState>> futures = new ArrayList<>();
locations.stream().filter(loc -> loc.getServerName() != null)
.filter(loc -> loc.getRegion() != null).filter(loc -> !loc.getRegion().isOffline())
.map(loc -> loc.getRegion().getRegionName()).forEach(region -> {
futures.add(getCompactionStateForRegion(region).whenComplete((regionState, err2) -> {
// If any region compaction state is MAJOR_AND_MINOR
// the table compaction state is MAJOR_AND_MINOR, too.
if (err2 != null) {
future.completeExceptionally(unwrapCompletionException(err2));
} else if (regionState == CompactionState.MAJOR_AND_MINOR) {
future.complete(regionState);
} else {
regionStates.add(regionState);
}
}));
});
addListener(
CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[futures.size()])),
(ret, err3) -> {
// If future not completed, check all regions's compaction state
if (!future.isCompletedExceptionally() && !future.isDone()) {
CompactionState state = CompactionState.NONE;
for (CompactionState regionState : regionStates) {
switch (regionState) {
case MAJOR:
if (state == CompactionState.MINOR) {
future.complete(CompactionState.MAJOR_AND_MINOR);
} else {
state = CompactionState.MAJOR;
}
break;
case MINOR:
if (state == CompactionState.MAJOR) {
future.complete(CompactionState.MAJOR_AND_MINOR);
} else {
state = CompactionState.MINOR;
}
break;
case NONE:
default:
}
}
if (!future.isDone()) {
future.complete(state);
}
}
});
});
break;
default:
throw new IllegalArgumentException("Unknown compactType: " + compactType);
}
return future;
}
@Override
public CompletableFuture<CompactionState> getCompactionStateForRegion(byte[] regionName) {
CompletableFuture<CompactionState> future = new CompletableFuture<>();
addListener(getRegionLocation(regionName), (location, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
ServerName serverName = location.getServerName();
if (serverName == null) {
future
.completeExceptionally(new NoServerForRegionException(Bytes.toStringBinary(regionName)));
return;
}
addListener(
this.<GetRegionInfoResponse> newAdminCaller()
.action((controller, stub) -> this
.<GetRegionInfoRequest, GetRegionInfoResponse, GetRegionInfoResponse> adminCall(
controller, stub,
RequestConverter.buildGetRegionInfoRequest(location.getRegion().getRegionName(),
true),
(s, c, req, done) -> s.getRegionInfo(controller, req, done), resp -> resp))
.serverName(serverName).call(),
(resp2, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
if (resp2.hasCompactionState()) {
future.complete(ProtobufUtil.createCompactionState(resp2.getCompactionState()));
} else {
future.complete(CompactionState.NONE);
}
}
});
});
return future;
}
@Override
public CompletableFuture<Optional<Long>> getLastMajorCompactionTimestamp(TableName tableName) {
MajorCompactionTimestampRequest request =
MajorCompactionTimestampRequest.newBuilder()
.setTableName(ProtobufUtil.toProtoTableName(tableName)).build();
return this
.<Optional<Long>> newMasterCaller()
.action(
(controller, stub) -> this
.<MajorCompactionTimestampRequest, MajorCompactionTimestampResponse, Optional<Long>> call(
controller, stub, request,
(s, c, req, done) -> s.getLastMajorCompactionTimestamp(c, req, done),
ProtobufUtil::toOptionalTimestamp)).call();
}
@Override
public CompletableFuture<Optional<Long>> getLastMajorCompactionTimestampForRegion(
byte[] regionName) {
CompletableFuture<Optional<Long>> future = new CompletableFuture<>();
// regionName may be a full region name or encoded region name, so getRegionInfo(byte[]) first
addListener(getRegionInfo(regionName), (region, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
MajorCompactionTimestampForRegionRequest.Builder builder =
MajorCompactionTimestampForRegionRequest.newBuilder();
builder.setRegion(
RequestConverter.buildRegionSpecifier(RegionSpecifierType.REGION_NAME, regionName));
addListener(this.<Optional<Long>> newMasterCaller().action((controller, stub) -> this
.<MajorCompactionTimestampForRegionRequest,
MajorCompactionTimestampResponse, Optional<Long>> call(
controller, stub, builder.build(),
(s, c, req, done) -> s.getLastMajorCompactionTimestampForRegion(c, req, done),
ProtobufUtil::toOptionalTimestamp))
.call(), (timestamp, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
future.complete(timestamp);
}
});
});
return future;
}
@Override
public CompletableFuture<Boolean> balancerSwitch(final boolean on) {
return this
.<Boolean> newMasterCaller()
.action(
(controller, stub) -> this
.<SetBalancerRunningRequest, SetBalancerRunningResponse, Boolean> call(controller,
stub, RequestConverter.buildSetBalancerRunningRequest(on, true),
(s, c, req, done) -> s.setBalancerRunning(c, req, done),
(resp) -> resp.getPrevBalanceValue())).call();
}
@Override
public CompletableFuture<Boolean> balance(boolean forcible) {
return this
.<Boolean> newMasterCaller()
.action(
(controller, stub) -> this.<BalanceRequest, BalanceResponse, Boolean> call(controller,
stub, RequestConverter.buildBalanceRequest(forcible),
(s, c, req, done) -> s.balance(c, req, done), (resp) -> resp.getBalancerRan())).call();
}
@Override
public CompletableFuture<Boolean> isBalancerEnabled() {
return this
.<Boolean> newMasterCaller()
.action(
(controller, stub) -> this.<IsBalancerEnabledRequest, IsBalancerEnabledResponse, Boolean> call(
controller, stub, RequestConverter.buildIsBalancerEnabledRequest(),
(s, c, req, done) -> s.isBalancerEnabled(c, req, done), (resp) -> resp.getEnabled()))
.call();
}
@Override
public CompletableFuture<Boolean> normalizerSwitch(boolean on) {
return this
.<Boolean> newMasterCaller()
.action(
(controller, stub) -> this
.<SetNormalizerRunningRequest, SetNormalizerRunningResponse, Boolean> call(
controller, stub, RequestConverter.buildSetNormalizerRunningRequest(on), (s, c,
req, done) -> s.setNormalizerRunning(c, req, done), (resp) -> resp
.getPrevNormalizerValue())).call();
}
@Override
public CompletableFuture<Boolean> isNormalizerEnabled() {
return this
.<Boolean> newMasterCaller()
.action(
(controller, stub) -> this
.<IsNormalizerEnabledRequest, IsNormalizerEnabledResponse, Boolean> call(controller,
stub, RequestConverter.buildIsNormalizerEnabledRequest(),
(s, c, req, done) -> s.isNormalizerEnabled(c, req, done),
(resp) -> resp.getEnabled())).call();
}
@Override
public CompletableFuture<Boolean> normalize() {
return this
.<Boolean> newMasterCaller()
.action(
(controller, stub) -> this.<NormalizeRequest, NormalizeResponse, Boolean> call(
controller, stub, RequestConverter.buildNormalizeRequest(),
(s, c, req, done) -> s.normalize(c, req, done), (resp) -> resp.getNormalizerRan()))
.call();
}
@Override
public CompletableFuture<Boolean> cleanerChoreSwitch(boolean enabled) {
return this
.<Boolean> newMasterCaller()
.action(
(controller, stub) -> this
.<SetCleanerChoreRunningRequest, SetCleanerChoreRunningResponse, Boolean> call(
controller, stub, RequestConverter.buildSetCleanerChoreRunningRequest(enabled), (s,
c, req, done) -> s.setCleanerChoreRunning(c, req, done), (resp) -> resp
.getPrevValue())).call();
}
@Override
public CompletableFuture<Boolean> isCleanerChoreEnabled() {
return this
.<Boolean> newMasterCaller()
.action(
(controller, stub) -> this
.<IsCleanerChoreEnabledRequest, IsCleanerChoreEnabledResponse, Boolean> call(
controller, stub, RequestConverter.buildIsCleanerChoreEnabledRequest(), (s, c, req,
done) -> s.isCleanerChoreEnabled(c, req, done), (resp) -> resp.getValue()))
.call();
}
@Override
public CompletableFuture<Boolean> runCleanerChore() {
return this
.<Boolean> newMasterCaller()
.action(
(controller, stub) -> this
.<RunCleanerChoreRequest, RunCleanerChoreResponse, Boolean> call(controller, stub,
RequestConverter.buildRunCleanerChoreRequest(),
(s, c, req, done) -> s.runCleanerChore(c, req, done),
(resp) -> resp.getCleanerChoreRan())).call();
}
@Override
public CompletableFuture<Boolean> catalogJanitorSwitch(boolean enabled) {
return this
.<Boolean> newMasterCaller()
.action(
(controller, stub) -> this
.<EnableCatalogJanitorRequest, EnableCatalogJanitorResponse, Boolean> call(
controller, stub, RequestConverter.buildEnableCatalogJanitorRequest(enabled), (s,
c, req, done) -> s.enableCatalogJanitor(c, req, done), (resp) -> resp
.getPrevValue())).call();
}
@Override
public CompletableFuture<Boolean> isCatalogJanitorEnabled() {
return this
.<Boolean> newMasterCaller()
.action(
(controller, stub) -> this
.<IsCatalogJanitorEnabledRequest, IsCatalogJanitorEnabledResponse, Boolean> call(
controller, stub, RequestConverter.buildIsCatalogJanitorEnabledRequest(), (s, c,
req, done) -> s.isCatalogJanitorEnabled(c, req, done), (resp) -> resp
.getValue())).call();
}
@Override
public CompletableFuture<Integer> runCatalogJanitor() {
return this
.<Integer> newMasterCaller()
.action(
(controller, stub) -> this.<RunCatalogScanRequest, RunCatalogScanResponse, Integer> call(
controller, stub, RequestConverter.buildCatalogScanRequest(),
(s, c, req, done) -> s.runCatalogScan(c, req, done), (resp) -> resp.getScanResult()))
.call();
}
@Override
public <S, R> CompletableFuture<R> coprocessorService(Function<RpcChannel, S> stubMaker,
ServiceCaller<S, R> callable) {
MasterCoprocessorRpcChannelImpl channel =
new MasterCoprocessorRpcChannelImpl(this.<Message> newMasterCaller());
S stub = stubMaker.apply(channel);
CompletableFuture<R> future = new CompletableFuture<>();
ClientCoprocessorRpcController controller = new ClientCoprocessorRpcController();
callable.call(stub, controller, resp -> {
if (controller.failed()) {
future.completeExceptionally(controller.getFailed());
} else {
future.complete(resp);
}
});
return future;
}
@Override
public <S, R> CompletableFuture<R> coprocessorService(Function<RpcChannel, S> stubMaker,
ServiceCaller<S, R> callable, ServerName serverName) {
RegionServerCoprocessorRpcChannelImpl channel =
new RegionServerCoprocessorRpcChannelImpl(this.<Message> newServerCaller().serverName(
serverName));
S stub = stubMaker.apply(channel);
CompletableFuture<R> future = new CompletableFuture<>();
ClientCoprocessorRpcController controller = new ClientCoprocessorRpcController();
callable.call(stub, controller, resp -> {
if (controller.failed()) {
future.completeExceptionally(controller.getFailed());
} else {
future.complete(resp);
}
});
return future;
}
@Override
public CompletableFuture<List<ServerName>> clearDeadServers(List<ServerName> servers) {
return this.<List<ServerName>> newMasterCaller()
.action((controller, stub) -> this
.<ClearDeadServersRequest, ClearDeadServersResponse, List<ServerName>> call(
controller, stub, RequestConverter.buildClearDeadServersRequest(servers),
(s, c, req, done) -> s.clearDeadServers(c, req, done),
(resp) -> ProtobufUtil.toServerNameList(resp.getServerNameList())))
.call();
}
private <T> ServerRequestCallerBuilder<T> newServerCaller() {
return this.connection.callerFactory.<T> serverRequest()
.rpcTimeout(rpcTimeoutNs, TimeUnit.NANOSECONDS)
.operationTimeout(operationTimeoutNs, TimeUnit.NANOSECONDS)
.pause(pauseNs, TimeUnit.NANOSECONDS).maxAttempts(maxAttempts)
.startLogErrorsCnt(startLogErrorsCnt);
}
@Override
public CompletableFuture<Void> enableTableReplication(TableName tableName) {
if (tableName == null) {
return failedFuture(new IllegalArgumentException("Table name is null"));
}
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(tableExists(tableName), (exist, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
if (!exist) {
future.completeExceptionally(new TableNotFoundException(
"Table '" + tableName.getNameAsString() + "' does not exists."));
return;
}
addListener(getTableSplits(tableName), (splits, err1) -> {
if (err1 != null) {
future.completeExceptionally(err1);
} else {
addListener(checkAndSyncTableToPeerClusters(tableName, splits), (result, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
addListener(setTableReplication(tableName, true), (result3, err3) -> {
if (err3 != null) {
future.completeExceptionally(err3);
} else {
future.complete(result3);
}
});
}
});
}
});
});
return future;
}
@Override
public CompletableFuture<Void> disableTableReplication(TableName tableName) {
if (tableName == null) {
return failedFuture(new IllegalArgumentException("Table name is null"));
}
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(tableExists(tableName), (exist, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
if (!exist) {
future.completeExceptionally(new TableNotFoundException(
"Table '" + tableName.getNameAsString() + "' does not exists."));
return;
}
addListener(setTableReplication(tableName, false), (result, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
future.complete(result);
}
});
});
return future;
}
private CompletableFuture<byte[][]> getTableSplits(TableName tableName) {
CompletableFuture<byte[][]> future = new CompletableFuture<>();
addListener(getRegions(tableName), (regions, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
return;
}
if (regions.size() == 1) {
future.complete(null);
} else {
byte[][] splits = new byte[regions.size() - 1][];
for (int i = 1; i < regions.size(); i++) {
splits[i - 1] = regions.get(i).getStartKey();
}
future.complete(splits);
}
});
return future;
}
/**
* Connect to peer and check the table descriptor on peer:
* <ol>
* <li>Create the same table on peer when not exist.</li>
* <li>Throw an exception if the table already has replication enabled on any of the column
* families.</li>
* <li>Throw an exception if the table exists on peer cluster but descriptors are not same.</li>
* </ol>
* @param tableName name of the table to sync to the peer
* @param splits table split keys
*/
private CompletableFuture<Void> checkAndSyncTableToPeerClusters(TableName tableName,
byte[][] splits) {
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(listReplicationPeers(), (peers, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
if (peers == null || peers.size() <= 0) {
future.completeExceptionally(
new IllegalArgumentException("Found no peer cluster for replication."));
return;
}
List<CompletableFuture<Void>> futures = new ArrayList<>();
peers.stream().filter(peer -> peer.getPeerConfig().needToReplicate(tableName))
.forEach(peer -> {
futures.add(trySyncTableToPeerCluster(tableName, splits, peer));
});
addListener(
CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[futures.size()])),
(result, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
future.complete(result);
}
});
});
return future;
}
private CompletableFuture<Void> trySyncTableToPeerCluster(TableName tableName, byte[][] splits,
ReplicationPeerDescription peer) {
Configuration peerConf = null;
try {
peerConf =
ReplicationPeerConfigUtil.getPeerClusterConfiguration(connection.getConfiguration(), peer);
} catch (IOException e) {
return failedFuture(e);
}
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(ConnectionFactory.createAsyncConnection(peerConf), (conn, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
addListener(getDescriptor(tableName), (tableDesc, err1) -> {
if (err1 != null) {
future.completeExceptionally(err1);
return;
}
AsyncAdmin peerAdmin = conn.getAdmin();
addListener(peerAdmin.tableExists(tableName), (exist, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
return;
}
if (!exist) {
CompletableFuture<Void> createTableFuture = null;
if (splits == null) {
createTableFuture = peerAdmin.createTable(tableDesc);
} else {
createTableFuture = peerAdmin.createTable(tableDesc, splits);
}
addListener(createTableFuture, (result, err3) -> {
if (err3 != null) {
future.completeExceptionally(err3);
} else {
future.complete(result);
}
});
} else {
addListener(compareTableWithPeerCluster(tableName, tableDesc, peer, peerAdmin),
(result, err4) -> {
if (err4 != null) {
future.completeExceptionally(err4);
} else {
future.complete(result);
}
});
}
});
});
});
return future;
}
private CompletableFuture<Void> compareTableWithPeerCluster(TableName tableName,
TableDescriptor tableDesc, ReplicationPeerDescription peer, AsyncAdmin peerAdmin) {
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(peerAdmin.getDescriptor(tableName), (peerTableDesc, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
if (peerTableDesc == null) {
future.completeExceptionally(
new IllegalArgumentException("Failed to get table descriptor for table " +
tableName.getNameAsString() + " from peer cluster " + peer.getPeerId()));
return;
}
if (TableDescriptor.COMPARATOR_IGNORE_REPLICATION.compare(peerTableDesc, tableDesc) != 0) {
future.completeExceptionally(new IllegalArgumentException(
"Table " + tableName.getNameAsString() + " exists in peer cluster " + peer.getPeerId() +
", but the table descriptors are not same when compared with source cluster." +
" Thus can not enable the table's replication switch."));
return;
}
future.complete(null);
});
return future;
}
/**
* Set the table's replication switch if the table's replication switch is already not set.
* @param tableName name of the table
* @param enableRep is replication switch enable or disable
*/
private CompletableFuture<Void> setTableReplication(TableName tableName, boolean enableRep) {
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(getDescriptor(tableName), (tableDesc, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
if (!tableDesc.matchReplicationScope(enableRep)) {
int scope =
enableRep ? HConstants.REPLICATION_SCOPE_GLOBAL : HConstants.REPLICATION_SCOPE_LOCAL;
TableDescriptor newTableDesc =
TableDescriptorBuilder.newBuilder(tableDesc).setReplicationScope(scope).build();
addListener(modifyTable(newTableDesc), (result, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
} else {
future.complete(result);
}
});
} else {
future.complete(null);
}
});
return future;
}
@Override
public CompletableFuture<CacheEvictionStats> clearBlockCache(TableName tableName) {
CompletableFuture<CacheEvictionStats> future = new CompletableFuture<>();
addListener(getTableHRegionLocations(tableName), (locations, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
Map<ServerName, List<RegionInfo>> regionInfoByServerName =
locations.stream().filter(l -> l.getRegion() != null)
.filter(l -> !l.getRegion().isOffline()).filter(l -> l.getServerName() != null)
.collect(Collectors.groupingBy(l -> l.getServerName(),
Collectors.mapping(l -> l.getRegion(), Collectors.toList())));
List<CompletableFuture<CacheEvictionStats>> futures = new ArrayList<>();
CacheEvictionStatsAggregator aggregator = new CacheEvictionStatsAggregator();
for (Map.Entry<ServerName, List<RegionInfo>> entry : regionInfoByServerName.entrySet()) {
futures
.add(clearBlockCache(entry.getKey(), entry.getValue()).whenComplete((stats, err2) -> {
if (err2 != null) {
future.completeExceptionally(unwrapCompletionException(err2));
} else {
aggregator.append(stats);
}
}));
}
addListener(CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])),
(ret, err3) -> {
if (err3 != null) {
future.completeExceptionally(unwrapCompletionException(err3));
} else {
future.complete(aggregator.sum());
}
});
});
return future;
}
@Override
public CompletableFuture<Void> cloneTableSchema(TableName tableName, TableName newTableName,
boolean preserveSplits) {
CompletableFuture<Void> future = new CompletableFuture<>();
addListener(tableExists(tableName), (exist, err) -> {
if (err != null) {
future.completeExceptionally(err);
return;
}
if (!exist) {
future.completeExceptionally(new TableNotFoundException(tableName));
return;
}
addListener(tableExists(newTableName), (exist1, err1) -> {
if (err1 != null) {
future.completeExceptionally(err1);
return;
}
if (exist1) {
future.completeExceptionally(new TableExistsException(newTableName));
return;
}
addListener(getDescriptor(tableName), (tableDesc, err2) -> {
if (err2 != null) {
future.completeExceptionally(err2);
return;
}
TableDescriptor newTableDesc = TableDescriptorBuilder.copy(newTableName, tableDesc);
if (preserveSplits) {
addListener(getTableSplits(tableName), (splits, err3) -> {
if (err3 != null) {
future.completeExceptionally(err3);
} else {
addListener(createTable(newTableDesc, splits), (result, err4) -> {
if (err4 != null) {
future.completeExceptionally(err4);
} else {
future.complete(result);
}
});
}
});
} else {
addListener(createTable(newTableDesc), (result, err5) -> {
if (err5 != null) {
future.completeExceptionally(err5);
} else {
future.complete(result);
}
});
}
});
});
});
return future;
}
private CompletableFuture<CacheEvictionStats> clearBlockCache(ServerName serverName,
List<RegionInfo> hris) {
return this.<CacheEvictionStats> newAdminCaller().action((controller, stub) -> this
.<ClearRegionBlockCacheRequest, ClearRegionBlockCacheResponse, CacheEvictionStats> adminCall(
controller, stub, RequestConverter.buildClearRegionBlockCacheRequest(hris),
(s, c, req, done) -> s.clearRegionBlockCache(controller, req, done),
resp -> ProtobufUtil.toCacheEvictionStats(resp.getStats())))
.serverName(serverName).call();
}
}
|
package com.zpj.appmanager.utils;
import android.content.Context;
import android.support.v4.view.ViewPager;
import com.zpj.appmanager.R;
import com.zpj.utils.ScreenUtils;
import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;
public class MagicIndicatorHelper {
public static void bindViewPager(Context context, MagicIndicator magicIndicator, ViewPager viewPager, String[] tabTitles) {
bindViewPager(context, magicIndicator, viewPager, tabTitles, false);
}
public static void bindViewPager(Context context, MagicIndicator magicIndicator, ViewPager viewPager, String[] tabTitles, boolean adjustMode) {
int normalTextColor = context.getResources().getColor(R.color.middle_gray_1);
builder(context)
.setMagicIndicator(magicIndicator)
.setViewPager(viewPager)
.setTabTitles(tabTitles)
.setAdjustMode(adjustMode)
.setOnGetTitleViewListener((context12, index) -> {
ColorTransitionPagerTitleView titleView = new ColorTransitionPagerTitleView(context12);
titleView.setNormalColor(normalTextColor); // context.getResources().getColor(R.color.color_text_normal)
titleView.setSelectedColor(context12.getResources().getColor(R.color.colorPrimary));
titleView.setTextSize(14);
titleView.setText(tabTitles[index]);
titleView.setOnClickListener(view1 -> viewPager.setCurrentItem(index, true));
return titleView;
})
.setOnGetIndicatorListener(context1 -> {
LinePagerIndicator indicator = new LinePagerIndicator(context1);
indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
indicator.setLineHeight(ScreenUtils.dp2px(context1, 4f));
indicator.setLineWidth(ScreenUtils.dp2px(context1, 12f));
indicator.setRoundRadius(ScreenUtils.dp2px(context1, 4f));
indicator.setColors(context1.getResources().getColor(R.color.colorPrimary), context1.getResources().getColor(R.color.colorPrimary));
return indicator;
})
.build();
}
public static Builder builder(Context context) {
return new Builder(context);
}
public interface OnGetTitleViewListener {
IPagerTitleView getTitleView(Context context, int index);
}
public interface OnGetIndicatorListener {
IPagerIndicator getIndicator(Context context);
}
public static class Builder {
private Context context;
private MagicIndicator magicIndicator;
private ViewPager viewPager;
private String[] tabTitles;
private boolean adjustMode;
private OnGetTitleViewListener onGetTitleViewListener;
private OnGetIndicatorListener onGetIndicatorListener;
private Builder(Context context) {
this.context = context;
}
public Builder setMagicIndicator(MagicIndicator magicIndicator) {
this.magicIndicator = magicIndicator;
return this;
}
public Builder setViewPager(ViewPager viewPager) {
this.viewPager = viewPager;
return this;
}
public Builder setTabTitles(String[] tabTitles) {
this.tabTitles = tabTitles;
return this;
}
public Builder setAdjustMode(boolean adjustMode) {
this.adjustMode = adjustMode;
return this;
}
public Builder setOnGetTitleViewListener(OnGetTitleViewListener onGetTitleViewListener) {
this.onGetTitleViewListener = onGetTitleViewListener;
return this;
}
public Builder setOnGetIndicatorListener(OnGetIndicatorListener onGetIndicatorListener) {
this.onGetIndicatorListener = onGetIndicatorListener;
return this;
}
public void build() {
CommonNavigator navigator = new CommonNavigator(context);
navigator.setAdjustMode(adjustMode);
int normalTextColor = context.getResources().getColor(R.color.middle_gray_1);
navigator.setAdapter(new CommonNavigatorAdapter() {
@Override
public int getCount() {
return tabTitles.length;
}
@Override
public IPagerTitleView getTitleView(Context context, int index) {
if (onGetTitleViewListener != null) {
return onGetTitleViewListener.getTitleView(context, index);
}
ColorTransitionPagerTitleView titleView = new ColorTransitionPagerTitleView(context);
titleView.setNormalColor(normalTextColor); // context.getResources().getColor(R.color.color_text_normal)
titleView.setSelectedColor(context.getResources().getColor(R.color.colorPrimary));
titleView.setTextSize(14);
titleView.setText(tabTitles[index]);
titleView.setOnClickListener(view1 -> viewPager.setCurrentItem(index, true));
return titleView;
}
@Override
public IPagerIndicator getIndicator(Context context) {
if (onGetIndicatorListener != null) {
return onGetIndicatorListener.getIndicator(context);
}
LinePagerIndicator indicator = new LinePagerIndicator(context);
indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
indicator.setLineHeight(ScreenUtils.dp2px(context, 4f));
indicator.setLineWidth(ScreenUtils.dp2px(context, 12f));
indicator.setRoundRadius(ScreenUtils.dp2px(context, 4f));
indicator.setColors(context.getResources().getColor(R.color.colorPrimary), context.getResources().getColor(R.color.colorPrimary));
return indicator;
}
});
magicIndicator.setNavigator(navigator);
ViewPagerHelper.bind(magicIndicator, viewPager);
}
}
}
|
package org.wltea.analyzer.core;
/**
* 子分词器接口
*/
interface ISegmenter {
/**
* 从分析器读取下一个可能分解的词元对象
*
* @param context 分词算法上下文
*/
void analyze(AnalyzeContext context);
/**
* 重置子分析器状态
*/
void reset();
}
|
package com.pojo;
import java.sql.Timestamp;
/**
* ZucaishengfuKjgg entity. @author MyEclipse Persistence Tools
*/
public class ZucaishengfuKjgg implements java.io.Serializable {
// Fields
private Integer id;
private SoccerGame soccerGame;
private Timestamp kaijiangTime;
private Integer result;
private String score;
// Constructors
/** default constructor */
public ZucaishengfuKjgg() {
}
/** full constructor */
public ZucaishengfuKjgg(SoccerGame soccerGame, Timestamp kaijiangTime, Integer result, String score) {
this.soccerGame = soccerGame;
this.kaijiangTime = kaijiangTime;
this.result = result;
this.score = score;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public SoccerGame getSoccerGame() {
return this.soccerGame;
}
public void setSoccerGame(SoccerGame soccerGame) {
this.soccerGame = soccerGame;
}
public Timestamp getKaijiangTime() {
return this.kaijiangTime;
}
public void setKaijiangTime(Timestamp kaijiangTime) {
this.kaijiangTime = kaijiangTime;
}
public Integer getResult() {
return this.result;
}
public void setResult(Integer result) {
this.result = result;
}
public String getScore() {
return this.score;
}
public void setScore(String score) {
this.score = score;
}
}
|
package me.storm.ninegag.ui.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import me.storm.ninegag.App;
import me.storm.ninegag.R;
import me.storm.ninegag.model.Category;
/**
* Created by storm on 14-3-25.
*/
public class DrawerAdapter extends BaseAdapter {
private ListView mListView;
public DrawerAdapter(ListView listView) {
mListView = listView;
}
@Override
public int getCount() {
return Category.values().length;
}
@Override
public Category getItem(int position) {
return Category.values()[position];
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(App.getContext()).inflate(R.layout.listitem_drawer, null);
}
TextView textView = (TextView) convertView.findViewById(R.id.textView);
textView.setText(getItem(position).getDisplayName());
textView.setSelected(mListView.isItemChecked(position));
return convertView;
}
}
|
package com.module1;
import java.util.Scanner;
public class t17_7 {
public static void main(String[] args) {
System.out.print(Integer.toString(new Scanner(System.in).nextInt()).length());
}
}
|
/**
*
*/
package org.gusdb.wdk.model.test;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
/**
* @author Jerric
* @created Sep 22, 2005
*/
public class CommandHelper {
public static CommandLine parseOptions(String cmdName, Options options,
String[] args) {
CommandLineParser parser = new BasicParser();
CommandLine cmdLine = null;
try {
// parse the command line arguments
cmdLine = parser.parse(options, args);
} catch (ParseException exp) {
// oops, something went wrong
System.err.println("");
System.err.println("Parsing failed. Reason: " + exp.getMessage());
System.err.println("");
usage(cmdName, options);
}
return cmdLine;
}
public static Options declareOptions(String[] names, String[] descs,
boolean[] required, int[] args) {
Options options = new Options();
// get the minimal size
int min = (names.length < descs.length) ? names.length : descs.length;
if (min > required.length) min = required.length;
if (min > args.length) min = args.length;
// model name
for (int i = 0; i < min; i++) {
addOption(options, required[i], names[i], descs[i], args[i]);
}
// verbose
Option verbose = new Option("verbose",
"Print out more information while running test.");
options.addOption(verbose);
return options;
}
public static void addOption(Options options, boolean required,
String argName, String desc, int arg) {
Option option = new Option(argName, true, desc);
option.setRequired(required);
option.setArgName(argName);
if (arg != 0) option.setArgs(arg);
options.addOption(option);
}
public static void usage(String cmdName, Options options) {
String newline = System.getProperty("line.separator");
StringBuffer sb = new StringBuffer();
// add command name
sb.append(cmdName);
// add command syntax
for (Object objOption : options.getOptions()) {
Option option = (Option) objOption;
if (option.isRequired()) sb.append(" -");
else sb.append(" [-");
sb.append(option.getOpt());
sb.append(' ');
sb.append(option.getOpt());
if (!option.isRequired()) sb.append(']');
}
sb.append(newline);
String cmdlineSyntax = sb.toString();
String header = "Run Unit test cases. Options:";
String footer = " ";
// PrintWriter stderr = new PrintWriter(System.err);
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(75, cmdlineSyntax, header, options, footer);
System.exit(1);
}
}
|
package org.ripple.bouncycastle.jce.provider;
import java.security.InvalidAlgorithmParameterException;
import java.security.cert.CRLSelector;
import java.security.cert.CertSelector;
import java.security.cert.CertStore;
import java.security.cert.CertStoreException;
import java.security.cert.CertStoreParameters;
import java.security.cert.CertStoreSpi;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.ripple.bouncycastle.jce.MultiCertStoreParameters;
public class MultiCertStoreSpi
extends CertStoreSpi
{
private MultiCertStoreParameters params;
public MultiCertStoreSpi(CertStoreParameters params)
throws InvalidAlgorithmParameterException
{
super(params);
if (!(params instanceof MultiCertStoreParameters))
{
throw new InvalidAlgorithmParameterException("org.ripple.bouncycastle.jce.provider.MultiCertStoreSpi: parameter must be a MultiCertStoreParameters object\n" + params.toString());
}
this.params = (MultiCertStoreParameters)params;
}
public Collection engineGetCertificates(CertSelector certSelector)
throws CertStoreException
{
boolean searchAllStores = params.getSearchAllStores();
Iterator iter = params.getCertStores().iterator();
List allCerts = searchAllStores ? new ArrayList() : Collections.EMPTY_LIST;
while (iter.hasNext())
{
CertStore store = (CertStore)iter.next();
Collection certs = store.getCertificates(certSelector);
if (searchAllStores)
{
allCerts.addAll(certs);
}
else if (!certs.isEmpty())
{
return certs;
}
}
return allCerts;
}
public Collection engineGetCRLs(CRLSelector crlSelector)
throws CertStoreException
{
boolean searchAllStores = params.getSearchAllStores();
Iterator iter = params.getCertStores().iterator();
List allCRLs = searchAllStores ? new ArrayList() : Collections.EMPTY_LIST;
while (iter.hasNext())
{
CertStore store = (CertStore)iter.next();
Collection crls = store.getCRLs(crlSelector);
if (searchAllStores)
{
allCRLs.addAll(crls);
}
else if (!crls.isEmpty())
{
return crls;
}
}
return allCRLs;
}
}
|
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
package com.twilio.rest.video.v1;
import com.twilio.base.Deleter;
import com.twilio.exception.ApiConnectionException;
import com.twilio.exception.ApiException;
import com.twilio.exception.RestException;
import com.twilio.http.HttpMethod;
import com.twilio.http.Request;
import com.twilio.http.Response;
import com.twilio.http.TwilioRestClient;
import com.twilio.rest.Domains;
/**
* PLEASE NOTE that this class contains preview products that are subject to
* change. Use them with caution. If you currently do not have developer preview
* access, please contact help@twilio.com.
*/
public class CompositionHookDeleter extends Deleter<CompositionHook> {
private final String pathSid;
/**
* Construct a new CompositionHookDeleter.
*
* @param pathSid The SID that identifies the resource to delete
*/
public CompositionHookDeleter(final String pathSid) {
this.pathSid = pathSid;
}
/**
* Make the request to the Twilio API to perform the delete.
*
* @param client TwilioRestClient with which to make the request
*/
@Override
@SuppressWarnings("checkstyle:linelength")
public boolean delete(final TwilioRestClient client) {
Request request = new Request(
HttpMethod.DELETE,
Domains.VIDEO.toString(),
"/v1/CompositionHooks/" + this.pathSid + ""
);
Response response = client.request(request);
if (response == null) {
throw new ApiConnectionException("CompositionHook delete failed: Unable to connect to server");
} else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) {
RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper());
if (restException == null) {
throw new ApiException("Server Error, no content");
}
throw new ApiException(restException);
}
return response.getStatusCode() == 204;
}
}
|
/*
* Copyright 2012-2017 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.route53.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* A complex type that contains general information about the hosted zone.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/HostedZone" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class HostedZone implements Serializable, Cloneable {
/**
* <p>
* The ID that Amazon Route 53 assigned to the hosted zone when you created it.
* </p>
*/
private String id;
/**
* <p>
* The name of the domain. For public hosted zones, this is the name that you have registered with your DNS
* registrar.
* </p>
* <p>
* For information about how to specify characters other than <code>a-z</code>, <code>0-9</code>, and <code>-</code>
* (hyphen) and how to specify internationalized domain names, see <a>CreateHostedZone</a>.
* </p>
*/
private String name;
/**
* <p>
* The value that you specified for <code>CallerReference</code> when you created the hosted zone.
* </p>
*/
private String callerReference;
/**
* <p>
* A complex type that includes the <code>Comment</code> and <code>PrivateZone</code> elements. If you omitted the
* <code>HostedZoneConfig</code> and <code>Comment</code> elements from the request, the <code>Config</code> and
* <code>Comment</code> elements don't appear in the response.
* </p>
*/
private HostedZoneConfig config;
/**
* <p>
* The number of resource record sets in the hosted zone.
* </p>
*/
private Long resourceRecordSetCount;
/**
* Default constructor for HostedZone object. Callers should use the setter or fluent setter (with...) methods to
* initialize the object after creating it.
*/
public HostedZone() {
}
/**
* Constructs a new HostedZone object. Callers should use the setter or fluent setter (with...) methods to
* initialize any additional object members.
*
* @param id
* The ID that Amazon Route 53 assigned to the hosted zone when you created it.
* @param name
* The name of the domain. For public hosted zones, this is the name that you have registered with your DNS
* registrar.</p>
* <p>
* For information about how to specify characters other than <code>a-z</code>, <code>0-9</code>, and
* <code>-</code> (hyphen) and how to specify internationalized domain names, see <a>CreateHostedZone</a>.
* @param callerReference
* The value that you specified for <code>CallerReference</code> when you created the hosted zone.
*/
public HostedZone(String id, String name, String callerReference) {
setId(id);
setName(name);
setCallerReference(callerReference);
}
/**
* <p>
* The ID that Amazon Route 53 assigned to the hosted zone when you created it.
* </p>
*
* @param id
* The ID that Amazon Route 53 assigned to the hosted zone when you created it.
*/
public void setId(String id) {
this.id = id;
}
/**
* <p>
* The ID that Amazon Route 53 assigned to the hosted zone when you created it.
* </p>
*
* @return The ID that Amazon Route 53 assigned to the hosted zone when you created it.
*/
public String getId() {
return this.id;
}
/**
* <p>
* The ID that Amazon Route 53 assigned to the hosted zone when you created it.
* </p>
*
* @param id
* The ID that Amazon Route 53 assigned to the hosted zone when you created it.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public HostedZone withId(String id) {
setId(id);
return this;
}
/**
* <p>
* The name of the domain. For public hosted zones, this is the name that you have registered with your DNS
* registrar.
* </p>
* <p>
* For information about how to specify characters other than <code>a-z</code>, <code>0-9</code>, and <code>-</code>
* (hyphen) and how to specify internationalized domain names, see <a>CreateHostedZone</a>.
* </p>
*
* @param name
* The name of the domain. For public hosted zones, this is the name that you have registered with your DNS
* registrar.</p>
* <p>
* For information about how to specify characters other than <code>a-z</code>, <code>0-9</code>, and
* <code>-</code> (hyphen) and how to specify internationalized domain names, see <a>CreateHostedZone</a>.
*/
public void setName(String name) {
this.name = name;
}
/**
* <p>
* The name of the domain. For public hosted zones, this is the name that you have registered with your DNS
* registrar.
* </p>
* <p>
* For information about how to specify characters other than <code>a-z</code>, <code>0-9</code>, and <code>-</code>
* (hyphen) and how to specify internationalized domain names, see <a>CreateHostedZone</a>.
* </p>
*
* @return The name of the domain. For public hosted zones, this is the name that you have registered with your DNS
* registrar.</p>
* <p>
* For information about how to specify characters other than <code>a-z</code>, <code>0-9</code>, and
* <code>-</code> (hyphen) and how to specify internationalized domain names, see <a>CreateHostedZone</a>.
*/
public String getName() {
return this.name;
}
/**
* <p>
* The name of the domain. For public hosted zones, this is the name that you have registered with your DNS
* registrar.
* </p>
* <p>
* For information about how to specify characters other than <code>a-z</code>, <code>0-9</code>, and <code>-</code>
* (hyphen) and how to specify internationalized domain names, see <a>CreateHostedZone</a>.
* </p>
*
* @param name
* The name of the domain. For public hosted zones, this is the name that you have registered with your DNS
* registrar.</p>
* <p>
* For information about how to specify characters other than <code>a-z</code>, <code>0-9</code>, and
* <code>-</code> (hyphen) and how to specify internationalized domain names, see <a>CreateHostedZone</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public HostedZone withName(String name) {
setName(name);
return this;
}
/**
* <p>
* The value that you specified for <code>CallerReference</code> when you created the hosted zone.
* </p>
*
* @param callerReference
* The value that you specified for <code>CallerReference</code> when you created the hosted zone.
*/
public void setCallerReference(String callerReference) {
this.callerReference = callerReference;
}
/**
* <p>
* The value that you specified for <code>CallerReference</code> when you created the hosted zone.
* </p>
*
* @return The value that you specified for <code>CallerReference</code> when you created the hosted zone.
*/
public String getCallerReference() {
return this.callerReference;
}
/**
* <p>
* The value that you specified for <code>CallerReference</code> when you created the hosted zone.
* </p>
*
* @param callerReference
* The value that you specified for <code>CallerReference</code> when you created the hosted zone.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public HostedZone withCallerReference(String callerReference) {
setCallerReference(callerReference);
return this;
}
/**
* <p>
* A complex type that includes the <code>Comment</code> and <code>PrivateZone</code> elements. If you omitted the
* <code>HostedZoneConfig</code> and <code>Comment</code> elements from the request, the <code>Config</code> and
* <code>Comment</code> elements don't appear in the response.
* </p>
*
* @param config
* A complex type that includes the <code>Comment</code> and <code>PrivateZone</code> elements. If you
* omitted the <code>HostedZoneConfig</code> and <code>Comment</code> elements from the request, the
* <code>Config</code> and <code>Comment</code> elements don't appear in the response.
*/
public void setConfig(HostedZoneConfig config) {
this.config = config;
}
/**
* <p>
* A complex type that includes the <code>Comment</code> and <code>PrivateZone</code> elements. If you omitted the
* <code>HostedZoneConfig</code> and <code>Comment</code> elements from the request, the <code>Config</code> and
* <code>Comment</code> elements don't appear in the response.
* </p>
*
* @return A complex type that includes the <code>Comment</code> and <code>PrivateZone</code> elements. If you
* omitted the <code>HostedZoneConfig</code> and <code>Comment</code> elements from the request, the
* <code>Config</code> and <code>Comment</code> elements don't appear in the response.
*/
public HostedZoneConfig getConfig() {
return this.config;
}
/**
* <p>
* A complex type that includes the <code>Comment</code> and <code>PrivateZone</code> elements. If you omitted the
* <code>HostedZoneConfig</code> and <code>Comment</code> elements from the request, the <code>Config</code> and
* <code>Comment</code> elements don't appear in the response.
* </p>
*
* @param config
* A complex type that includes the <code>Comment</code> and <code>PrivateZone</code> elements. If you
* omitted the <code>HostedZoneConfig</code> and <code>Comment</code> elements from the request, the
* <code>Config</code> and <code>Comment</code> elements don't appear in the response.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public HostedZone withConfig(HostedZoneConfig config) {
setConfig(config);
return this;
}
/**
* <p>
* The number of resource record sets in the hosted zone.
* </p>
*
* @param resourceRecordSetCount
* The number of resource record sets in the hosted zone.
*/
public void setResourceRecordSetCount(Long resourceRecordSetCount) {
this.resourceRecordSetCount = resourceRecordSetCount;
}
/**
* <p>
* The number of resource record sets in the hosted zone.
* </p>
*
* @return The number of resource record sets in the hosted zone.
*/
public Long getResourceRecordSetCount() {
return this.resourceRecordSetCount;
}
/**
* <p>
* The number of resource record sets in the hosted zone.
* </p>
*
* @param resourceRecordSetCount
* The number of resource record sets in the hosted zone.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public HostedZone withResourceRecordSetCount(Long resourceRecordSetCount) {
setResourceRecordSetCount(resourceRecordSetCount);
return this;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getId() != null)
sb.append("Id: ").append(getId()).append(",");
if (getName() != null)
sb.append("Name: ").append(getName()).append(",");
if (getCallerReference() != null)
sb.append("CallerReference: ").append(getCallerReference()).append(",");
if (getConfig() != null)
sb.append("Config: ").append(getConfig()).append(",");
if (getResourceRecordSetCount() != null)
sb.append("ResourceRecordSetCount: ").append(getResourceRecordSetCount());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof HostedZone == false)
return false;
HostedZone other = (HostedZone) obj;
if (other.getId() == null ^ this.getId() == null)
return false;
if (other.getId() != null && other.getId().equals(this.getId()) == false)
return false;
if (other.getName() == null ^ this.getName() == null)
return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false)
return false;
if (other.getCallerReference() == null ^ this.getCallerReference() == null)
return false;
if (other.getCallerReference() != null && other.getCallerReference().equals(this.getCallerReference()) == false)
return false;
if (other.getConfig() == null ^ this.getConfig() == null)
return false;
if (other.getConfig() != null && other.getConfig().equals(this.getConfig()) == false)
return false;
if (other.getResourceRecordSetCount() == null ^ this.getResourceRecordSetCount() == null)
return false;
if (other.getResourceRecordSetCount() != null && other.getResourceRecordSetCount().equals(this.getResourceRecordSetCount()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode());
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getCallerReference() == null) ? 0 : getCallerReference().hashCode());
hashCode = prime * hashCode + ((getConfig() == null) ? 0 : getConfig().hashCode());
hashCode = prime * hashCode + ((getResourceRecordSetCount() == null) ? 0 : getResourceRecordSetCount().hashCode());
return hashCode;
}
@Override
public HostedZone clone() {
try {
return (HostedZone) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
// Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.util.HostPlatform;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import eu.medsea.mimeutil.MimeException;
import eu.medsea.mimeutil.MimeType;
import eu.medsea.mimeutil.MimeUtil2;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Singleton
public class MimeUtilFileTypeRegistry implements FileTypeRegistry {
private static final String KEY_SAFE = "safe";
private static final String SECTION_MIMETYPE = "mimetype";
private static final Logger log =
LoggerFactory.getLogger(MimeUtilFileTypeRegistry.class);
private final Config cfg;
private MimeUtil2 mimeUtil;
@Inject
MimeUtilFileTypeRegistry(@GerritServerConfig final Config gsc) {
cfg = gsc;
mimeUtil = new MimeUtil2();
register("eu.medsea.mimeutil.detector.ExtensionMimeDetector");
register("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
if (HostPlatform.isWin32()) {
register("eu.medsea.mimeutil.detector.WindowsRegistryMimeDetector");
}
}
private void register(String name) {
mimeUtil.registerMimeDetector(name);
}
@SuppressWarnings("unchecked")
public MimeType getMimeType(final String path, final byte[] content) {
Set<MimeType> mimeTypes = new HashSet<MimeType>();
if (content != null && content.length > 0) {
try {
mimeTypes.addAll(mimeUtil.getMimeTypes(content));
} catch (MimeException e) {
log.warn("Unable to determine MIME type from content", e);
}
}
try {
mimeTypes.addAll(mimeUtil.getMimeTypes(path));
} catch (MimeException e) {
log.warn("Unable to determine MIME type from path", e);
}
if (isUnknownType(mimeTypes)) {
return MimeUtil2.UNKNOWN_MIME_TYPE;
}
final List<MimeType> types = new ArrayList<MimeType>(mimeTypes);
Collections.sort(types, new Comparator<MimeType>() {
@Override
public int compare(MimeType a, MimeType b) {
return b.getSpecificity() - a.getSpecificity();
}
});
return types.get(0);
}
public boolean isSafeInline(final MimeType type) {
if (MimeUtil2.UNKNOWN_MIME_TYPE.equals(type)) {
// Most browsers perform content type sniffing when they get told
// a generic content type. This is bad, so assume we cannot send
// the file inline.
//
return false;
}
final boolean any = isSafe(cfg, "*/*", false);
final boolean genericMedia = isSafe(cfg, type.getMediaType() + "/*", any);
return isSafe(cfg, type.toString(), genericMedia);
}
private static boolean isSafe(Config cfg, String type, boolean def) {
return cfg.getBoolean(SECTION_MIMETYPE, type, KEY_SAFE, def);
}
private static boolean isUnknownType(Collection<MimeType> mimeTypes) {
if (mimeTypes.isEmpty()) {
return true;
}
return mimeTypes.size() == 1
&& mimeTypes.contains(MimeUtil2.UNKNOWN_MIME_TYPE);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.